596bf3b53ff057051138e2d3f1021b6354060c5e
[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 * Delete contact, ensuring it is not the domain contact
1194 *
1195 * @param int $contactID
1196 * Contact ID to delete
1197 */
1198 public function contactDelete($contactID) {
1199 $domain = new CRM_Core_BAO_Domain;
1200 $domain->contact_id = $contactID;
1201 if (!$domain->find(TRUE)) {
1202 $this->callAPISuccess('contact', 'delete', array(
1203 'id' => $contactID,
1204 'skip_undelete' => 1,
1205 ));
1206 }
1207 }
1208
1209 /**
1210 * @param int $contactTypeId
1211 *
1212 * @throws Exception
1213 */
1214 public function contactTypeDelete($contactTypeId) {
1215 require_once 'CRM/Contact/BAO/ContactType.php';
1216 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
1217 if (!$result) {
1218 throw new Exception('Could not delete contact type');
1219 }
1220 }
1221
1222 /**
1223 * @param array $params
1224 *
1225 * @return mixed
1226 */
1227 public function membershipTypeCreate($params = array()) {
1228 CRM_Member_PseudoConstant::flush('membershipType');
1229 CRM_Core_Config::clearDBCache();
1230 $memberOfOrganization = $this->organizationCreate();
1231 $params = array_merge(array(
1232 'name' => 'General',
1233 'duration_unit' => 'year',
1234 'duration_interval' => 1,
1235 'period_type' => 'rolling',
1236 'member_of_contact_id' => $memberOfOrganization,
1237 'domain_id' => 1,
1238 'financial_type_id' => 1,
1239 'is_active' => 1,
1240 'sequential' => 1,
1241 'visibility' => 'Public',
1242 ), $params);
1243
1244 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
1245
1246 CRM_Member_PseudoConstant::flush('membershipType');
1247 CRM_Utils_Cache::singleton()->flush();
1248
1249 return $result['id'];
1250 }
1251
1252 /**
1253 * @param array $params
1254 *
1255 * @return mixed
1256 */
1257 public function contactMembershipCreate($params) {
1258 $pre = array(
1259 'join_date' => '2007-01-21',
1260 'start_date' => '2007-01-21',
1261 'end_date' => '2007-12-21',
1262 'source' => 'Payment',
1263 );
1264
1265 foreach ($pre as $key => $val) {
1266 if (!isset($params[$key])) {
1267 $params[$key] = $val;
1268 }
1269 }
1270
1271 $result = $this->callAPISuccess('Membership', 'create', $params);
1272 return $result['id'];
1273 }
1274
1275 /**
1276 * Delete Membership Type
1277 *
1278 * @param array $params
1279 */
1280 public function membershipTypeDelete($params) {
1281 $this->callAPISuccess('MembershipType', 'Delete', $params);
1282 }
1283
1284 /**
1285 * @param int $membershipID
1286 */
1287 public function membershipDelete($membershipID) {
1288 $deleteParams = array('id' => $membershipID);
1289 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
1290 return;
1291 }
1292
1293 /**
1294 * @param string $name
1295 *
1296 * @return mixed
1297 */
1298 public function membershipStatusCreate($name = 'test member status') {
1299 $params['name'] = $name;
1300 $params['start_event'] = 'start_date';
1301 $params['end_event'] = 'end_date';
1302 $params['is_current_member'] = 1;
1303 $params['is_active'] = 1;
1304
1305 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
1306 CRM_Member_PseudoConstant::flush('membershipStatus');
1307 return $result['id'];
1308 }
1309
1310 /**
1311 * @param int $membershipStatusID
1312 */
1313 public function membershipStatusDelete($membershipStatusID) {
1314 if (!$membershipStatusID) {
1315 return;
1316 }
1317 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
1318 return;
1319 }
1320
1321 /**
1322 * @param array $params
1323 *
1324 * @return mixed
1325 */
1326 public function relationshipTypeCreate($params = array()) {
1327 $params = array_merge(array(
1328 'name_a_b' => 'Relation 1 for relationship type create',
1329 'name_b_a' => 'Relation 2 for relationship type create',
1330 'contact_type_a' => 'Individual',
1331 'contact_type_b' => 'Organization',
1332 'is_reserved' => 1,
1333 'is_active' => 1,
1334 ),
1335 $params
1336 );
1337
1338 $result = $this->callAPISuccess('relationship_type', 'create', $params);
1339 CRM_Core_PseudoConstant::flush('relationshipType');
1340
1341 return $result['id'];
1342 }
1343
1344 /**
1345 * Delete Relatinship Type
1346 *
1347 * @param int $relationshipTypeID
1348 */
1349 public function relationshipTypeDelete($relationshipTypeID) {
1350 $params['id'] = $relationshipTypeID;
1351 $this->callAPISuccess('relationship_type', 'delete', $params);
1352 }
1353
1354 /**
1355 * @param array $params
1356 *
1357 * @return mixed
1358 */
1359 public function paymentProcessorTypeCreate($params = NULL) {
1360 if (is_null($params)) {
1361 $params = array(
1362 'name' => 'API_Test_PP',
1363 'title' => 'API Test Payment Processor',
1364 'class_name' => 'CRM_Core_Payment_APITest',
1365 'billing_mode' => 'form',
1366 'is_recur' => 0,
1367 'is_reserved' => 1,
1368 'is_active' => 1,
1369 );
1370 }
1371 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
1372
1373 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1374
1375 return $result['id'];
1376 }
1377
1378 /**
1379 * Create Participant
1380 *
1381 * @param array $params
1382 * Array of contact id and event id values.
1383 *
1384 * @return int
1385 * $id of participant created
1386 */
1387 public function participantCreate($params) {
1388 if (empty($params['contact_id'])) {
1389 $params['contact_id'] = $this->individualCreate();
1390 }
1391 if (empty($params['event_id'])) {
1392 $event = $this->eventCreate();
1393 $params['event_id'] = $event['id'];
1394 }
1395 $defaults = array(
1396 'status_id' => 2,
1397 'role_id' => 1,
1398 'register_date' => 20070219,
1399 'source' => 'Wimbeldon',
1400 'event_level' => 'Payment',
1401 'debug' => 1,
1402 );
1403
1404 $params = array_merge($defaults, $params);
1405 $result = $this->callAPISuccess('Participant', 'create', $params);
1406 return $result['id'];
1407 }
1408
1409 /**
1410 * Create Payment Processor
1411 *
1412 * @return CRM_Financial_DAO_PaymentProcessor
1413 * instance of Payment Processsor
1414 */
1415 public function processorCreate() {
1416 $processorParams = array(
1417 'domain_id' => 1,
1418 'name' => 'Dummy',
1419 'payment_processor_type_id' => 10,
1420 'financial_account_id' => 12,
1421 'is_active' => 1,
1422 'user_name' => '',
1423 'url_site' => 'http://dummy.com',
1424 'url_recur' => 'http://dummy.com',
1425 'billing_mode' => 1,
1426 );
1427 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
1428 return $paymentProcessor;
1429 }
1430
1431 /**
1432 * Create contribution page
1433 *
1434 * @param array $params
1435 * @return array
1436 * Array of contribution page
1437 */
1438 public function contributionPageCreate($params) {
1439 $this->_pageParams = array(
1440 'title' => 'Test Contribution Page',
1441 'financial_type_id' => 1,
1442 'currency' => 'USD',
1443 'financial_account_id' => 1,
1444 'payment_processor' => $params['processor_id'],
1445 'is_active' => 1,
1446 'is_allow_other_amount' => 1,
1447 'min_amount' => 10,
1448 'max_amount' => 1000,
1449 );
1450 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1451 return $contributionPage;
1452 }
1453
1454 /**
1455 * Create Tag
1456 *
1457 * @param array $params
1458 * @return array
1459 * result of created tag
1460 */
1461 public function tagCreate($params = array()) {
1462 $defaults = array(
1463 'name' => 'New Tag3',
1464 'description' => 'This is description for Our New Tag ',
1465 'domain_id' => '1',
1466 );
1467 $params = array_merge($defaults, $params);
1468 $result = $this->callAPISuccess('Tag', 'create', $params);
1469 return $result['values'][$result['id']];
1470 }
1471
1472 /**
1473 * Delete Tag
1474 *
1475 * @param int $tagId
1476 * Id of the tag to be deleted.
1477 *
1478 * @return int
1479 */
1480 public function tagDelete($tagId) {
1481 require_once 'api/api.php';
1482 $params = array(
1483 'tag_id' => $tagId,
1484 );
1485 $result = $this->callAPISuccess('Tag', 'delete', $params);
1486 return $result['id'];
1487 }
1488
1489 /**
1490 * Add entity(s) to the tag
1491 *
1492 * @param array $params
1493 *
1494 * @return bool
1495 */
1496 public function entityTagAdd($params) {
1497 $result = $this->callAPISuccess('entity_tag', 'create', $params);
1498 return TRUE;
1499 }
1500
1501 /**
1502 * Create contribution
1503 *
1504 * @param int $cID
1505 * Contact_id.
1506 *
1507 * @return int
1508 * id of created contribution
1509 */
1510 public function pledgeCreate($cID) {
1511 $params = array(
1512 'contact_id' => $cID,
1513 'pledge_create_date' => date('Ymd'),
1514 'start_date' => date('Ymd'),
1515 'scheduled_date' => date('Ymd'),
1516 'amount' => 100.00,
1517 'pledge_status_id' => '2',
1518 'financial_type_id' => '1',
1519 'pledge_original_installment_amount' => 20,
1520 'frequency_interval' => 5,
1521 'frequency_unit' => 'year',
1522 'frequency_day' => 15,
1523 'installments' => 5,
1524 );
1525
1526 $result = $this->callAPISuccess('Pledge', 'create', $params);
1527 return $result['id'];
1528 }
1529
1530 /**
1531 * Delete contribution
1532 *
1533 * @param int $pledgeId
1534 */
1535 public function pledgeDelete($pledgeId) {
1536 $params = array(
1537 'pledge_id' => $pledgeId,
1538 );
1539 $this->callAPISuccess('Pledge', 'delete', $params);
1540 }
1541
1542 /**
1543 * Create contribution
1544 *
1545 * @param int $cID
1546 * Contact_id.
1547 * @param int $cTypeID
1548 * Id of financial type.
1549 * @param int $invoiceID
1550 * @param int $trxnID
1551 * @param int $paymentInstrumentID
1552 * @param bool $isFee
1553 *
1554 * @return int
1555 * id of created contribution
1556 */
1557 public function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1558 $params = array(
1559 'domain_id' => 1,
1560 'contact_id' => $cID,
1561 'receive_date' => date('Ymd'),
1562 'total_amount' => 100.00,
1563 'financial_type_id' => empty($cTypeID) ? 1 : $cTypeID,
1564 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1565 'non_deductible_amount' => 10.00,
1566 'trxn_id' => $trxnID,
1567 'invoice_id' => $invoiceID,
1568 'source' => 'SSF',
1569 'contribution_status_id' => 1,
1570 // 'note' => 'Donating for Nobel Cause', *Fixme
1571 );
1572
1573 if ($isFee) {
1574 $params['fee_amount'] = 5.00;
1575 $params['net_amount'] = 95.00;
1576 }
1577
1578 $result = $this->callAPISuccess('contribution', 'create', $params);
1579 return $result['id'];
1580 }
1581
1582 /**
1583 * Create online contribution
1584 *
1585 * @param array $params
1586 * @param int $financialType
1587 * Id of financial type.
1588 * @param int $invoiceID
1589 * @param int $trxnID
1590 *
1591 * @return int
1592 * id of created contribution
1593 */
1594 public function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1595 $contribParams = array(
1596 'contact_id' => $params['contact_id'],
1597 'receive_date' => date('Ymd'),
1598 'total_amount' => 100.00,
1599 'financial_type_id' => $financialType,
1600 'contribution_page_id' => $params['contribution_page_id'],
1601 'trxn_id' => 12345,
1602 'invoice_id' => 67890,
1603 'source' => 'SSF',
1604 );
1605 $contribParams = array_merge($contribParams, $params);
1606 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
1607
1608 return $result['id'];
1609 }
1610
1611 /**
1612 * Delete contribution
1613 *
1614 * @param int $contributionId
1615 *
1616 * @return array|int
1617 */
1618 public function contributionDelete($contributionId) {
1619 $params = array(
1620 'contribution_id' => $contributionId,
1621 );
1622 $result = $this->callAPISuccess('contribution', 'delete', $params);
1623 return $result;
1624 }
1625
1626 /**
1627 * Create an Event
1628 *
1629 * @param array $params
1630 * Name-value pair for an event.
1631 *
1632 * @return array
1633 */
1634 public function eventCreate($params = array()) {
1635 // if no contact was passed, make up a dummy event creator
1636 if (!isset($params['contact_id'])) {
1637 $params['contact_id'] = $this->_contactCreate(array(
1638 'contact_type' => 'Individual',
1639 'first_name' => 'Event',
1640 'last_name' => 'Creator',
1641 ));
1642 }
1643
1644 // set defaults for missing params
1645 $params = array_merge(array(
1646 'title' => 'Annual CiviCRM meet',
1647 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1648 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1649 'event_type_id' => 1,
1650 'is_public' => 1,
1651 'start_date' => 20081021,
1652 'end_date' => 20081023,
1653 'is_online_registration' => 1,
1654 'registration_start_date' => 20080601,
1655 'registration_end_date' => 20081015,
1656 'max_participants' => 100,
1657 'event_full_text' => 'Sorry! We are already full',
1658 'is_monetory' => 0,
1659 'is_active' => 1,
1660 'is_show_location' => 0,
1661 ), $params);
1662
1663 return $this->callAPISuccess('Event', 'create', $params);
1664 }
1665
1666 /**
1667 * Delete event
1668 *
1669 * @param int $id
1670 * ID of the event.
1671 *
1672 * @return array|int
1673 */
1674 public function eventDelete($id) {
1675 $params = array(
1676 'event_id' => $id,
1677 );
1678 return $this->callAPISuccess('event', 'delete', $params);
1679 }
1680
1681 /**
1682 * Delete participant
1683 *
1684 * @param int $participantID
1685 *
1686 * @return array|int
1687 */
1688 public function participantDelete($participantID) {
1689 $params = array(
1690 'id' => $participantID,
1691 );
1692 return $this->callAPISuccess('Participant', 'delete', $params);
1693 }
1694
1695 /**
1696 * Create participant payment
1697 *
1698 * @param int $participantID
1699 * @param int $contributionID
1700 * @return int
1701 * $id of created payment
1702 */
1703 public function participantPaymentCreate($participantID, $contributionID = NULL) {
1704 //Create Participant Payment record With Values
1705 $params = array(
1706 'participant_id' => $participantID,
1707 'contribution_id' => $contributionID,
1708 );
1709
1710 $result = $this->callAPISuccess('participant_payment', 'create', $params);
1711 return $result['id'];
1712 }
1713
1714 /**
1715 * Delete participant payment
1716 *
1717 * @param int $paymentID
1718 */
1719 public function participantPaymentDelete($paymentID) {
1720 $params = array(
1721 'id' => $paymentID,
1722 );
1723 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
1724 }
1725
1726 /**
1727 * Add a Location
1728 *
1729 * @param int $contactID
1730 * @return int
1731 * location id of created location
1732 */
1733 public function locationAdd($contactID) {
1734 $address = array(
1735 1 => array(
1736 'location_type' => 'New Location Type',
1737 'is_primary' => 1,
1738 'name' => 'Saint Helier St',
1739 'county' => 'Marin',
1740 'country' => 'United States',
1741 'state_province' => 'Michigan',
1742 'supplemental_address_1' => 'Hallmark Ct',
1743 'supplemental_address_2' => 'Jersey Village',
1744 ),
1745 );
1746
1747 $params = array(
1748 'contact_id' => $contactID,
1749 'address' => $address,
1750 'location_format' => '2.0',
1751 'location_type' => 'New Location Type',
1752 );
1753
1754 $result = $this->callAPISuccess('Location', 'create', $params);
1755 return $result;
1756 }
1757
1758 /**
1759 * Delete Locations of contact
1760 *
1761 * @param array $params
1762 * Parameters.
1763 */
1764 public function locationDelete($params) {
1765 $this->callAPISuccess('Location', 'delete', $params);
1766 }
1767
1768 /**
1769 * Add a Location Type
1770 *
1771 * @param array $params
1772 * @return CRM_Core_DAO_LocationType
1773 * location id of created location
1774 */
1775 public function locationTypeCreate($params = NULL) {
1776 if ($params === NULL) {
1777 $params = array(
1778 'name' => 'New Location Type',
1779 'vcard_name' => 'New Location Type',
1780 'description' => 'Location Type for Delete',
1781 'is_active' => 1,
1782 );
1783 }
1784
1785 $locationType = new CRM_Core_DAO_LocationType();
1786 $locationType->copyValues($params);
1787 $locationType->save();
1788 // clear getfields cache
1789 CRM_Core_PseudoConstant::flush();
1790 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
1791 return $locationType;
1792 }
1793
1794 /**
1795 * Delete a Location Type
1796 *
1797 * @param int location type id
1798 */
1799 public function locationTypeDelete($locationTypeId) {
1800 $locationType = new CRM_Core_DAO_LocationType();
1801 $locationType->id = $locationTypeId;
1802 $locationType->delete();
1803 }
1804
1805 /**
1806 * Add a Group
1807 *
1808 * @param array $params
1809 * @return int
1810 * groupId of created group
1811 */
1812 public function groupCreate($params = array()) {
1813 $params = array_merge(array(
1814 'name' => 'Test Group 1',
1815 'domain_id' => 1,
1816 'title' => 'New Test Group Created',
1817 'description' => 'New Test Group Created',
1818 'is_active' => 1,
1819 'visibility' => 'Public Pages',
1820 'group_type' => array(
1821 '1' => 1,
1822 '2' => 1,
1823 ),
1824 ), $params);
1825
1826 $result = $this->callAPISuccess('Group', 'create', $params);
1827 return $result['id'];
1828 }
1829
1830
1831 /**
1832 * Function to add a Group
1833 *
1834 * @params array to add group
1835 *
1836 * @param array $params
1837 * @return int
1838 * groupId of created group
1839 */
1840 public function groupContactCreate($groupID, $totalCount = 10) {
1841 $params = array('group_id' => $groupID);
1842 for ($i = 1; $i <= $totalCount; $i++) {
1843 $contactID = $this->individualCreate();
1844 if ($i == 1) {
1845 $params += array('contact_id' => $contactID);
1846 }
1847 else {
1848 $params += array("contact_id.$i" => $contactID);
1849 }
1850 }
1851 $result = $this->callAPISuccess('GroupContact', 'create', $params);
1852
1853 return $result;
1854 }
1855
1856 /**
1857 * Delete a Group
1858 *
1859 * @param int $gid
1860 */
1861 public function groupDelete($gid) {
1862
1863 $params = array(
1864 'id' => $gid,
1865 );
1866
1867 $this->callAPISuccess('Group', 'delete', $params);
1868 }
1869
1870 /**
1871 * Create a UFField
1872 * @param array $params
1873 */
1874 public function uFFieldCreate($params = array()) {
1875 $params = array_merge(array(
1876 'uf_group_id' => 1,
1877 'field_name' => 'first_name',
1878 'is_active' => 1,
1879 'is_required' => 1,
1880 'visibility' => 'Public Pages and Listings',
1881 'is_searchable' => '1',
1882 'label' => 'first_name',
1883 'field_type' => 'Individual',
1884 'weight' => 1,
1885 ), $params);
1886 $this->callAPISuccess('uf_field', 'create', $params);
1887 }
1888
1889 /**
1890 * Add a UF Join Entry
1891 *
1892 * @param array $params
1893 * @return int
1894 * $id of created UF Join
1895 */
1896 public function ufjoinCreate($params = NULL) {
1897 if ($params === NULL) {
1898 $params = array(
1899 'is_active' => 1,
1900 'module' => 'CiviEvent',
1901 'entity_table' => 'civicrm_event',
1902 'entity_id' => 3,
1903 'weight' => 1,
1904 'uf_group_id' => 1,
1905 );
1906 }
1907 $result = $this->callAPISuccess('uf_join', 'create', $params);
1908 return $result;
1909 }
1910
1911 /**
1912 * Delete a UF Join Entry
1913 *
1914 * @param array with missing uf_group_id
1915 */
1916 public function ufjoinDelete($params = NULL) {
1917 if ($params === NULL) {
1918 $params = array(
1919 'is_active' => 1,
1920 'module' => 'CiviEvent',
1921 'entity_table' => 'civicrm_event',
1922 'entity_id' => 3,
1923 'weight' => 1,
1924 'uf_group_id' => '',
1925 );
1926 }
1927
1928 crm_add_uf_join($params);
1929 }
1930
1931 /**
1932 * Create Group for a contact
1933 *
1934 * @param int $contactId
1935 */
1936 public function contactGroupCreate($contactId) {
1937 $params = array(
1938 'contact_id.1' => $contactId,
1939 'group_id' => 1,
1940 );
1941
1942 $this->callAPISuccess('GroupContact', 'Create', $params);
1943 }
1944
1945 /**
1946 * Delete Group for a contact
1947 *
1948 * @param int $contactId
1949 */
1950 public function contactGroupDelete($contactId) {
1951 $params = array(
1952 'contact_id.1' => $contactId,
1953 'group_id' => 1,
1954 );
1955 $this->civicrm_api('GroupContact', 'Delete', $params);
1956 }
1957
1958 /**
1959 * Create Activity
1960 *
1961 * @param array $params
1962 * @return array|int
1963 */
1964 public function activityCreate($params = NULL) {
1965
1966 if ($params === NULL) {
1967 $individualSourceID = $this->individualCreate();
1968
1969 $contactParams = array(
1970 'first_name' => 'Julia',
1971 'Last_name' => 'Anderson',
1972 'prefix' => 'Ms.',
1973 'email' => 'julia_anderson@civicrm.org',
1974 'contact_type' => 'Individual',
1975 );
1976
1977 $individualTargetID = $this->individualCreate($contactParams);
1978
1979 $params = array(
1980 'source_contact_id' => $individualSourceID,
1981 'target_contact_id' => array($individualTargetID),
1982 'assignee_contact_id' => array($individualTargetID),
1983 'subject' => 'Discussion on warm beer',
1984 'activity_date_time' => date('Ymd'),
1985 'duration_hours' => 30,
1986 'duration_minutes' => 20,
1987 'location' => 'Baker Street',
1988 'details' => 'Lets schedule a meeting',
1989 'status_id' => 1,
1990 'activity_name' => 'Meeting',
1991 );
1992 }
1993
1994 $result = $this->callAPISuccess('Activity', 'create', $params);
1995
1996 $result['target_contact_id'] = $individualTargetID;
1997 $result['assignee_contact_id'] = $individualTargetID;
1998 return $result;
1999 }
2000
2001 /**
2002 * Create an activity type
2003 *
2004 * @param array $params
2005 * Parameters.
2006 */
2007 public function activityTypeCreate($params) {
2008 $result = $this->callAPISuccess('ActivityType', 'create', $params);
2009 return $result;
2010 }
2011
2012 /**
2013 * Delete activity type
2014 *
2015 * @param int $activityTypeId
2016 * Id of the activity type.
2017 */
2018 public function activityTypeDelete($activityTypeId) {
2019 $params['activity_type_id'] = $activityTypeId;
2020 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
2021 return $result;
2022 }
2023
2024 /**
2025 * Create custom group
2026 *
2027 * @param array $params
2028 * @return array|int
2029 */
2030 public function customGroupCreate($params = array()) {
2031 $defaults = array(
2032 'title' => 'new custom group',
2033 'extends' => 'Contact',
2034 'domain_id' => 1,
2035 'style' => 'Inline',
2036 'is_active' => 1,
2037 );
2038
2039 $params = array_merge($defaults, $params);
2040
2041 if (strlen($params['title']) > 13) {
2042 $params['title'] = substr($params['title'], 0, 13);
2043 }
2044
2045 //have a crack @ deleting it first in the hope this will prevent derailing our tests
2046 $this->callAPISuccess('custom_group', 'get', array(
2047 'title' => $params['title'],
2048 array('api.custom_group.delete' => 1),
2049 ));
2050
2051 return $this->callAPISuccess('custom_group', 'create', $params);
2052 }
2053
2054 /**
2055 * Existing function doesn't allow params to be over-ridden so need a new one
2056 * this one allows you to only pass in the params you want to change
2057 */
2058 public function CustomGroupCreateByParams($params = array()) {
2059 $defaults = array(
2060 'title' => "API Custom Group",
2061 'extends' => 'Contact',
2062 'domain_id' => 1,
2063 'style' => 'Inline',
2064 'is_active' => 1,
2065 );
2066 $params = array_merge($defaults, $params);
2067 return $this->callAPISuccess('custom_group', 'create', $params);
2068 }
2069
2070 /**
2071 * Create custom group with multi fields
2072 */
2073 public function CustomGroupMultipleCreateByParams($params = array()) {
2074 $defaults = array(
2075 'style' => 'Tab',
2076 'is_multiple' => 1,
2077 );
2078 $params = array_merge($defaults, $params);
2079 return $this->CustomGroupCreateByParams($params);
2080 }
2081
2082 /**
2083 * Create custom group with multi fields
2084 */
2085 public function CustomGroupMultipleCreateWithFields($params = array()) {
2086 // also need to pass on $params['custom_field'] if not set but not in place yet
2087 $ids = array();
2088 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
2089 $ids['custom_group_id'] = $customGroup['id'];
2090
2091 $customField = $this->customFieldCreate(array(
2092 'custom_group_id' => $ids['custom_group_id'],
2093 'label' => 'field_1' . $ids['custom_group_id'],
2094 ));
2095
2096 $ids['custom_field_id'][] = $customField['id'];
2097
2098 $customField = $this->customFieldCreate(array(
2099 'custom_group_id' => $ids['custom_group_id'],
2100 'default_value' => '',
2101 'label' => 'field_2' . $ids['custom_group_id'],
2102 ));
2103 $ids['custom_field_id'][] = $customField['id'];
2104
2105 $customField = $this->customFieldCreate(array(
2106 'custom_group_id' => $ids['custom_group_id'],
2107 'default_value' => '',
2108 'label' => 'field_3' . $ids['custom_group_id'],
2109 ));
2110 $ids['custom_field_id'][] = $customField['id'];
2111
2112 return $ids;
2113 }
2114
2115 /**
2116 * Create a custom group with a single text custom field. See
2117 * participant:testCreateWithCustom for how to use this
2118 *
2119 * @param string $function
2120 * __FUNCTION__.
2121 * @param string $filename
2122 * $file __FILE__.
2123 *
2124 * @return array
2125 * ids of created objects
2126 */
2127 public function entityCustomGroupWithSingleFieldCreate($function, $filename) {
2128 $params = array('title' => $function);
2129 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2130 $params['extends'] = $entity ? $entity : 'Contact';
2131 $customGroup = $this->CustomGroupCreate($params);
2132 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
2133 CRM_Core_PseudoConstant::flush();
2134
2135 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
2136 }
2137
2138 /**
2139 * Delete custom group
2140 *
2141 * @param int $customGroupID
2142 *
2143 * @return array|int
2144 */
2145 public function customGroupDelete($customGroupID) {
2146 $params['id'] = $customGroupID;
2147 return $this->callAPISuccess('custom_group', 'delete', $params);
2148 }
2149
2150 /**
2151 * Create custom field
2152 *
2153 * @param array $params
2154 * (custom_group_id) is required.
2155 * @return array
2156 */
2157 public function customFieldCreate($params) {
2158 $params = array_merge(array(
2159 'label' => 'Custom Field',
2160 'data_type' => 'String',
2161 'html_type' => 'Text',
2162 'is_searchable' => 1,
2163 'is_active' => 1,
2164 'default_value' => 'defaultValue',
2165 ), $params);
2166
2167 $result = $this->callAPISuccess('custom_field', 'create', $params);
2168 // these 2 functions are called with force to flush static caches
2169 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
2170 CRM_Core_Component::getEnabledComponents(1);
2171 return $result;
2172 }
2173
2174 /**
2175 * Delete custom field
2176 *
2177 * @param int $customFieldID
2178 *
2179 * @return array|int
2180 */
2181 public function customFieldDelete($customFieldID) {
2182
2183 $params['id'] = $customFieldID;
2184 return $this->callAPISuccess('custom_field', 'delete', $params);
2185 }
2186
2187 /**
2188 * Create note
2189 *
2190 * @param int $cId
2191 * @return array
2192 */
2193 public function noteCreate($cId) {
2194 $params = array(
2195 'entity_table' => 'civicrm_contact',
2196 'entity_id' => $cId,
2197 'note' => 'hello I am testing Note',
2198 'contact_id' => $cId,
2199 'modified_date' => date('Ymd'),
2200 'subject' => 'Test Note',
2201 );
2202
2203 return $this->callAPISuccess('Note', 'create', $params);
2204 }
2205
2206 /**
2207 * Enable CiviCampaign Component
2208 */
2209 public function enableCiviCampaign() {
2210 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
2211 // force reload of config object
2212 $config = CRM_Core_Config::singleton(TRUE, TRUE);
2213 //flush cache by calling with reset
2214 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2215 }
2216
2217 /**
2218 * Create test generated example in api/v3/examples.
2219 * To turn this off (e.g. on the server) set
2220 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2221 * in your settings file
2222 * @param array $params
2223 * Array as passed to civicrm_api function.
2224 * @param array $result
2225 * Array as received from the civicrm_api function.
2226 * @param string $function
2227 * Calling function - generally __FUNCTION__.
2228 * @param string $filename
2229 * Called from file - generally __FILE__.
2230 * @param string $description
2231 * Descriptive text for the example file.
2232 * @param string $subfile
2233 * Name for subfile - if this is completed the example will be put in a subfolder (named by the entity).
2234 * @param string $action
2235 * Optional action - otherwise taken from function name.
2236 */
2237 public function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2238 if (defined('DONT_DOCUMENT_TEST_CONFIG') && DONT_DOCUMENT_TEST_CONFIG) {
2239 return;
2240 }
2241 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2242 //todo - this is a bit cludgey
2243 if (empty($action)) {
2244 if (strstr($function, 'Create')) {
2245 $action = empty($action) ? 'create' : $action;
2246 $entityAction = 'Create';
2247 }
2248 elseif (strstr($function, 'GetSingle')) {
2249 $action = empty($action) ? 'getsingle' : $action;
2250 $entityAction = 'GetSingle';
2251 }
2252 elseif (strstr($function, 'GetValue')) {
2253 $action = empty($action) ? 'getvalue' : $action;
2254 $entityAction = 'GetValue';
2255 }
2256 elseif (strstr($function, 'GetCount')) {
2257 $action = empty($action) ? 'getcount' : $action;
2258 $entityAction = 'GetCount';
2259 }
2260 elseif (strstr($function, 'GetFields')) {
2261 $action = empty($action) ? 'getfields' : $action;
2262 $entityAction = 'GetFields';
2263 }
2264 elseif (strstr($function, 'GetList')) {
2265 $action = empty($action) ? 'getlist' : $action;
2266 $entityAction = 'GetList';
2267 }
2268 elseif (strstr($function, 'GetActions')) {
2269 $action = empty($action) ? 'getactions' : $action;
2270 $entityAction = 'GetActions';
2271 }
2272 elseif (strstr($function, 'Get')) {
2273 $action = empty($action) ? 'get' : $action;
2274 $entityAction = 'Get';
2275 }
2276 elseif (strstr($function, 'Delete')) {
2277 $action = empty($action) ? 'delete' : $action;
2278 $entityAction = 'Delete';
2279 }
2280 elseif (strstr($function, 'Update')) {
2281 $action = empty($action) ? 'update' : $action;
2282 $entityAction = 'Update';
2283 }
2284 elseif (strstr($function, 'Subscribe')) {
2285 $action = empty($action) ? 'subscribe' : $action;
2286 $entityAction = 'Subscribe';
2287 }
2288 elseif (strstr($function, 'Submit')) {
2289 $action = empty($action) ? 'submit' : $action;
2290 $entityAction = 'Submit';
2291 }
2292 elseif (strstr($function, 'Apply')) {
2293 $action = empty($action) ? 'apply' : $action;
2294 $entityAction = 'Apply';
2295 }
2296 elseif (strstr($function, 'Replace')) {
2297 $action = empty($action) ? 'replace' : $action;
2298 $entityAction = 'Replace';
2299 }
2300 }
2301 else {
2302 $entityAction = ucwords($action);
2303 }
2304
2305 $this->tidyExampleResult($result);
2306 if (isset($params['version'])) {
2307 unset($params['version']);
2308 }
2309 // a cleverer person than me would do it in a single regex
2310 if (strstr($entity, 'UF')) {
2311 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2312 }
2313 else {
2314 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2315 }
2316 $smarty = CRM_Core_Smarty::singleton();
2317 $smarty->assign('testfunction', $function);
2318 $function = $fnPrefix . "_" . strtolower($action);
2319 $smarty->assign('function', $function);
2320 $smarty->assign('fnPrefix', $fnPrefix);
2321 $smarty->assign('params', $params);
2322 $smarty->assign('entity', $entity);
2323 $smarty->assign('filename', basename($filename));
2324 $smarty->assign('description', $description);
2325 $smarty->assign('result', $result);
2326
2327 $smarty->assign('action', $action);
2328 if (empty($subfile)) {
2329 $subfile = $entityAction;
2330 }
2331 if (file_exists('../tests/templates/documentFunction.tpl')) {
2332 if (!is_dir("../api/v3/examples/$entity")) {
2333 mkdir("../api/v3/examples/$entity");
2334 }
2335 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2336 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2337 fclose($f);
2338 }
2339 }
2340
2341 /**
2342 * Tidy up examples array so that fields that change often ..don't
2343 * and debug related fields are unset
2344 *
2345 * @param array $result
2346 */
2347 public function tidyExampleResult(&$result) {
2348 if (!is_array($result)) {
2349 return;
2350 }
2351 $fieldsToChange = array(
2352 'hash' => '67eac7789eaee00',
2353 'modified_date' => '2012-11-14 16:02:35',
2354 'created_date' => '2013-07-28 08:49:19',
2355 'create_date' => '20120130621222105',
2356 'application_received_date' => '20130728084957',
2357 'in_date' => '2013-07-28 08:50:19',
2358 'scheduled_date' => '20130728085413',
2359 'approval_date' => '20130728085413',
2360 'pledge_start_date_high' => '20130726090416',
2361 'start_date' => '2013-07-29 00:00:00',
2362 'event_start_date' => '2013-07-29 00:00:00',
2363 'end_date' => '2013-08-04 00:00:00',
2364 'event_end_date' => '2013-08-04 00:00:00',
2365 'decision_date' => '20130805000000',
2366 );
2367
2368 $keysToUnset = array('xdebug', 'undefined_fields');
2369 foreach ($keysToUnset as $unwantedKey) {
2370 if (isset($result[$unwantedKey])) {
2371 unset($result[$unwantedKey]);
2372 }
2373 }
2374 if (isset($result['values'])) {
2375 if (!is_array($result['values'])) {
2376 return;
2377 }
2378 $resultArray = &$result['values'];
2379 }
2380 elseif (is_array($result)) {
2381 $resultArray = &$result;
2382 }
2383 else {
2384 return;
2385 }
2386
2387 foreach ($resultArray as $index => &$values) {
2388 if (!is_array($values)) {
2389 continue;
2390 }
2391 foreach ($values as $key => &$value) {
2392 if (substr($key, 0, 3) == 'api' && is_array($value)) {
2393 if (isset($value['is_error'])) {
2394 // we have a std nested result format
2395 $this->tidyExampleResult($value);
2396 }
2397 else {
2398 foreach ($value as &$nestedResult) {
2399 // this is an alternative syntax for nested results a keyed array of results
2400 $this->tidyExampleResult($nestedResult);
2401 }
2402 }
2403 }
2404 if (in_array($key, $keysToUnset)) {
2405 unset($values[$key]);
2406 break;
2407 }
2408 if (array_key_exists($key, $fieldsToChange) && !empty($value)) {
2409 $value = $fieldsToChange[$key];
2410 }
2411 if (is_string($value)) {
2412 $value = addslashes($value);
2413 }
2414 }
2415 }
2416 }
2417
2418 /**
2419 * Delete note
2420 *
2421 * @param array $params
2422 *
2423 * @return array|int
2424 */
2425 public function noteDelete($params) {
2426 return $this->callAPISuccess('Note', 'delete', $params);
2427 }
2428
2429 /**
2430 * Create custom field with Option Values
2431 *
2432 * @param array $customGroup
2433 * @param string $name
2434 * Name of custom field.
2435 *
2436 * @return array|int
2437 */
2438 public function customFieldOptionValueCreate($customGroup, $name) {
2439 $fieldParams = array(
2440 'custom_group_id' => $customGroup['id'],
2441 'name' => 'test_custom_group',
2442 'label' => 'Country',
2443 'html_type' => 'Select',
2444 'data_type' => 'String',
2445 'weight' => 4,
2446 'is_required' => 1,
2447 'is_searchable' => 0,
2448 'is_active' => 1,
2449 );
2450
2451 $optionGroup = array(
2452 'domain_id' => 1,
2453 'name' => 'option_group1',
2454 'label' => 'option_group_label1',
2455 );
2456
2457 $optionValue = array(
2458 'option_label' => array('Label1', 'Label2'),
2459 'option_value' => array('value1', 'value2'),
2460 'option_name' => array($name . '_1', $name . '_2'),
2461 'option_weight' => array(1, 2),
2462 'option_status' => 1,
2463 );
2464
2465 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2466
2467 return $this->callAPISuccess('custom_field', 'create', $params);
2468 }
2469
2470 /**
2471 * @param $entities
2472 *
2473 * @return bool
2474 */
2475 public function confirmEntitiesDeleted($entities) {
2476 foreach ($entities as $entity) {
2477
2478 $result = $this->callAPISuccess($entity, 'Get', array());
2479 if ($result['error'] == 1 || $result['count'] > 0) {
2480 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2481 return TRUE;
2482 }
2483 }
2484 }
2485
2486 /**
2487 * @param $tablesToTruncate
2488 * @param bool $dropCustomValueTables
2489 * @throws \Exception
2490 */
2491 public function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2492 if ($this->tx) {
2493 throw new Exception("CiviUnitTestCase: quickCleanup() is not compatible with useTransaction()");
2494 }
2495 if ($dropCustomValueTables) {
2496 $tablesToTruncate[] = 'civicrm_custom_group';
2497 $tablesToTruncate[] = 'civicrm_custom_field';
2498 }
2499
2500 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
2501
2502 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2503 foreach ($tablesToTruncate as $table) {
2504 $sql = "TRUNCATE TABLE $table";
2505 CRM_Core_DAO::executeQuery($sql);
2506 }
2507 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2508
2509 if ($dropCustomValueTables) {
2510 $dbName = self::getDBName();
2511 $query = "
2512 SELECT TABLE_NAME as tableName
2513 FROM INFORMATION_SCHEMA.TABLES
2514 WHERE TABLE_SCHEMA = '{$dbName}'
2515 AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2516 ";
2517
2518 $tableDAO = CRM_Core_DAO::executeQuery($query);
2519 while ($tableDAO->fetch()) {
2520 $sql = "DROP TABLE {$tableDAO->tableName}";
2521 CRM_Core_DAO::executeQuery($sql);
2522 }
2523 }
2524 }
2525
2526 /**
2527 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2528 */
2529 public function quickCleanUpFinancialEntities() {
2530 $tablesToTruncate = array(
2531 'civicrm_contribution',
2532 'civicrm_contribution_soft',
2533 'civicrm_financial_trxn',
2534 'civicrm_financial_item',
2535 'civicrm_contribution_recur',
2536 'civicrm_line_item',
2537 'civicrm_contribution_page',
2538 'civicrm_payment_processor',
2539 'civicrm_entity_financial_trxn',
2540 'civicrm_membership',
2541 'civicrm_membership_type',
2542 'civicrm_membership_payment',
2543 'civicrm_membership_log',
2544 'civicrm_membership_block',
2545 'civicrm_event',
2546 'civicrm_participant',
2547 'civicrm_participant_payment',
2548 'civicrm_pledge',
2549 'civicrm_price_set_entity',
2550 'civicrm_price_field_value',
2551 'civicrm_price_field',
2552 );
2553 $this->quickCleanup($tablesToTruncate);
2554 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_membership_status WHERE name NOT IN('New', 'Current', 'Grace', 'Expired', 'Pending', 'Cancelled', 'Deceased')");
2555 $this->restoreDefaultPriceSetConfig();
2556 $var = TRUE;
2557 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
2558 }
2559
2560 public function restoreDefaultPriceSetConfig() {
2561 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)");
2562 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)");
2563 }
2564 /*
2565 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2566 * Default behaviour is to also delete the entity
2567 * @param array $params
2568 * Params array to check agains.
2569 * @param int $id
2570 * Id of the entity concerned.
2571 * @param string $entity
2572 * Name of entity concerned (e.g. membership).
2573 * @param bool $delete
2574 * Should the entity be deleted as part of this check.
2575 * @param string $errorText
2576 * Text to print on error.
2577 */
2578 /**
2579 * @param array $params
2580 * @param int $id
2581 * @param $entity
2582 * @param int $delete
2583 * @param string $errorText
2584 *
2585 * @throws Exception
2586 */
2587 public function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2588
2589 $result = $this->callAPISuccessGetSingle($entity, array(
2590 'id' => $id,
2591 ));
2592
2593 if ($delete) {
2594 $this->callAPISuccess($entity, 'Delete', array(
2595 'id' => $id,
2596 ));
2597 }
2598 $dateFields = $keys = $dateTimeFields = array();
2599 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
2600 foreach ($fields['values'] as $field => $settings) {
2601 if (array_key_exists($field, $result)) {
2602 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2603 }
2604 else {
2605 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2606 }
2607 $type = CRM_Utils_Array::value('type', $settings);
2608 if ($type == CRM_Utils_Type::T_DATE) {
2609 $dateFields[] = $settings['name'];
2610 // we should identify both real names & unique names as dates
2611 if ($field != $settings['name']) {
2612 $dateFields[] = $field;
2613 }
2614 }
2615 if ($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2616 $dateTimeFields[] = $settings['name'];
2617 // we should identify both real names & unique names as dates
2618 if ($field != $settings['name']) {
2619 $dateTimeFields[] = $field;
2620 }
2621 }
2622 }
2623
2624 if (strtolower($entity) == 'contribution') {
2625 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2626 // this is not returned in id format
2627 unset($params['payment_instrument_id']);
2628 $params['contribution_source'] = $params['source'];
2629 unset($params['source']);
2630 }
2631
2632 foreach ($params as $key => $value) {
2633 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
2634 continue;
2635 }
2636 if (in_array($key, $dateFields)) {
2637 $value = date('Y-m-d', strtotime($value));
2638 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2639 }
2640 if (in_array($key, $dateTimeFields)) {
2641 $value = date('Y-m-d H:i:s', strtotime($value));
2642 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
2643 }
2644 $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);
2645 }
2646 }
2647
2648 /**
2649 * Get formatted values in the actual and expected result
2650 * @param array $actual
2651 * Actual calculated values.
2652 * @param array $expected
2653 * Expected values.
2654 */
2655 public function checkArrayEquals(&$actual, &$expected) {
2656 self::unsetId($actual);
2657 self::unsetId($expected);
2658 $this->assertEquals($actual, $expected);
2659 }
2660
2661 /**
2662 * Unset the key 'id' from the array
2663 * @param array $unformattedArray
2664 * The array from which the 'id' has to be unset.
2665 */
2666 public static function unsetId(&$unformattedArray) {
2667 $formattedArray = array();
2668 if (array_key_exists('id', $unformattedArray)) {
2669 unset($unformattedArray['id']);
2670 }
2671 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
2672 foreach ($unformattedArray['values'] as $key => $value) {
2673 if (is_array($value)) {
2674 foreach ($value as $k => $v) {
2675 if ($k == 'id') {
2676 unset($value[$k]);
2677 }
2678 }
2679 }
2680 elseif ($key == 'id') {
2681 $unformattedArray[$key];
2682 }
2683 $formattedArray = array($value);
2684 }
2685 $unformattedArray['values'] = $formattedArray;
2686 }
2687 }
2688
2689 /**
2690 * Helper to enable/disable custom directory support
2691 *
2692 * @param array $customDirs
2693 * With members:.
2694 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2695 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2696 */
2697 public function customDirectories($customDirs) {
2698 require_once 'CRM/Core/Config.php';
2699 $config = CRM_Core_Config::singleton();
2700
2701 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2702 unset($config->customPHPPathDir);
2703 }
2704 elseif ($customDirs['php_path'] === TRUE) {
2705 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2706 }
2707 else {
2708 $config->customPHPPathDir = $php_path;
2709 }
2710
2711 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2712 unset($config->customTemplateDir);
2713 }
2714 elseif ($customDirs['template_path'] === TRUE) {
2715 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2716 }
2717 else {
2718 $config->customTemplateDir = $template_path;
2719 }
2720 }
2721
2722 /**
2723 * Generate a temporary folder
2724 *
2725 * @param string $prefix
2726 * @return string
2727 */
2728 public function createTempDir($prefix = 'test-') {
2729 $tempDir = CRM_Utils_File::tempdir($prefix);
2730 $this->tempDirs[] = $tempDir;
2731 return $tempDir;
2732 }
2733
2734 public function cleanTempDirs() {
2735 if (!is_array($this->tempDirs)) {
2736 // fix test errors where this is not set
2737 return;
2738 }
2739 foreach ($this->tempDirs as $tempDir) {
2740 if (is_dir($tempDir)) {
2741 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2742 }
2743 }
2744 }
2745
2746 /**
2747 * Temporarily replace the singleton extension with a different one
2748 */
2749 public function setExtensionSystem(CRM_Extension_System $system) {
2750 if ($this->origExtensionSystem == NULL) {
2751 $this->origExtensionSystem = CRM_Extension_System::singleton();
2752 }
2753 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2754 }
2755
2756 public function unsetExtensionSystem() {
2757 if ($this->origExtensionSystem !== NULL) {
2758 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2759 $this->origExtensionSystem = NULL;
2760 }
2761 }
2762
2763 /**
2764 * Temporarily alter the settings-metadata to add a mock setting.
2765 *
2766 * WARNING: The setting metadata will disappear on the next cache-clear.
2767 *
2768 * @param $extras
2769 * @return void
2770 */
2771 public function setMockSettingsMetaData($extras) {
2772 CRM_Core_BAO_Setting::$_cache = array();
2773 $this->callAPISuccess('system', 'flush', array());
2774 CRM_Core_BAO_Setting::$_cache = array();
2775
2776 CRM_Utils_Hook::singleton()
2777 ->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2778 $metadata = array_merge($metadata, $extras);
2779 });
2780
2781 $fields = $this->callAPISuccess('setting', 'getfields', array());
2782 foreach ($extras as $key => $spec) {
2783 $this->assertNotEmpty($spec['title']);
2784 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2785 }
2786 }
2787
2788 /**
2789 * @param string $name
2790 */
2791 public function financialAccountDelete($name) {
2792 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2793 $financialAccount->name = $name;
2794 if ($financialAccount->find(TRUE)) {
2795 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2796 $entityFinancialType->financial_account_id = $financialAccount->id;
2797 $entityFinancialType->delete();
2798 $financialAccount->delete();
2799 }
2800 }
2801
2802 /**
2803 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2804 * (NB unclear if this is still required)
2805 */
2806 public function _sethtmlGlobals() {
2807 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2808 'required' => array(
2809 'html_quickform_rule_required',
2810 'HTML/QuickForm/Rule/Required.php',
2811 ),
2812 'maxlength' => array(
2813 'html_quickform_rule_range',
2814 'HTML/QuickForm/Rule/Range.php',
2815 ),
2816 'minlength' => array(
2817 'html_quickform_rule_range',
2818 'HTML/QuickForm/Rule/Range.php',
2819 ),
2820 'rangelength' => array(
2821 'html_quickform_rule_range',
2822 'HTML/QuickForm/Rule/Range.php',
2823 ),
2824 'email' => array(
2825 'html_quickform_rule_email',
2826 'HTML/QuickForm/Rule/Email.php',
2827 ),
2828 'regex' => array(
2829 'html_quickform_rule_regex',
2830 'HTML/QuickForm/Rule/Regex.php',
2831 ),
2832 'lettersonly' => array(
2833 'html_quickform_rule_regex',
2834 'HTML/QuickForm/Rule/Regex.php',
2835 ),
2836 'alphanumeric' => array(
2837 'html_quickform_rule_regex',
2838 'HTML/QuickForm/Rule/Regex.php',
2839 ),
2840 'numeric' => array(
2841 'html_quickform_rule_regex',
2842 'HTML/QuickForm/Rule/Regex.php',
2843 ),
2844 'nopunctuation' => array(
2845 'html_quickform_rule_regex',
2846 'HTML/QuickForm/Rule/Regex.php',
2847 ),
2848 'nonzero' => array(
2849 'html_quickform_rule_regex',
2850 'HTML/QuickForm/Rule/Regex.php',
2851 ),
2852 'callback' => array(
2853 'html_quickform_rule_callback',
2854 'HTML/QuickForm/Rule/Callback.php',
2855 ),
2856 'compare' => array(
2857 'html_quickform_rule_compare',
2858 'HTML/QuickForm/Rule/Compare.php',
2859 ),
2860 );
2861 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2862 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2863 'group' => array(
2864 'HTML/QuickForm/group.php',
2865 'HTML_QuickForm_group',
2866 ),
2867 'hidden' => array(
2868 'HTML/QuickForm/hidden.php',
2869 'HTML_QuickForm_hidden',
2870 ),
2871 'reset' => array(
2872 'HTML/QuickForm/reset.php',
2873 'HTML_QuickForm_reset',
2874 ),
2875 'checkbox' => array(
2876 'HTML/QuickForm/checkbox.php',
2877 'HTML_QuickForm_checkbox',
2878 ),
2879 'file' => array(
2880 'HTML/QuickForm/file.php',
2881 'HTML_QuickForm_file',
2882 ),
2883 'image' => array(
2884 'HTML/QuickForm/image.php',
2885 'HTML_QuickForm_image',
2886 ),
2887 'password' => array(
2888 'HTML/QuickForm/password.php',
2889 'HTML_QuickForm_password',
2890 ),
2891 'radio' => array(
2892 'HTML/QuickForm/radio.php',
2893 'HTML_QuickForm_radio',
2894 ),
2895 'button' => array(
2896 'HTML/QuickForm/button.php',
2897 'HTML_QuickForm_button',
2898 ),
2899 'submit' => array(
2900 'HTML/QuickForm/submit.php',
2901 'HTML_QuickForm_submit',
2902 ),
2903 'select' => array(
2904 'HTML/QuickForm/select.php',
2905 'HTML_QuickForm_select',
2906 ),
2907 'hiddenselect' => array(
2908 'HTML/QuickForm/hiddenselect.php',
2909 'HTML_QuickForm_hiddenselect',
2910 ),
2911 'text' => array(
2912 'HTML/QuickForm/text.php',
2913 'HTML_QuickForm_text',
2914 ),
2915 'textarea' => array(
2916 'HTML/QuickForm/textarea.php',
2917 'HTML_QuickForm_textarea',
2918 ),
2919 'fckeditor' => array(
2920 'HTML/QuickForm/fckeditor.php',
2921 'HTML_QuickForm_FCKEditor',
2922 ),
2923 'tinymce' => array(
2924 'HTML/QuickForm/tinymce.php',
2925 'HTML_QuickForm_TinyMCE',
2926 ),
2927 'dojoeditor' => array(
2928 'HTML/QuickForm/dojoeditor.php',
2929 'HTML_QuickForm_dojoeditor',
2930 ),
2931 'link' => array(
2932 'HTML/QuickForm/link.php',
2933 'HTML_QuickForm_link',
2934 ),
2935 'advcheckbox' => array(
2936 'HTML/QuickForm/advcheckbox.php',
2937 'HTML_QuickForm_advcheckbox',
2938 ),
2939 'date' => array(
2940 'HTML/QuickForm/date.php',
2941 'HTML_QuickForm_date',
2942 ),
2943 'static' => array(
2944 'HTML/QuickForm/static.php',
2945 'HTML_QuickForm_static',
2946 ),
2947 'header' => array(
2948 'HTML/QuickForm/header.php',
2949 'HTML_QuickForm_header',
2950 ),
2951 'html' => array(
2952 'HTML/QuickForm/html.php',
2953 'HTML_QuickForm_html',
2954 ),
2955 'hierselect' => array(
2956 'HTML/QuickForm/hierselect.php',
2957 'HTML_QuickForm_hierselect',
2958 ),
2959 'autocomplete' => array(
2960 'HTML/QuickForm/autocomplete.php',
2961 'HTML_QuickForm_autocomplete',
2962 ),
2963 'xbutton' => array(
2964 'HTML/QuickForm/xbutton.php',
2965 'HTML_QuickForm_xbutton',
2966 ),
2967 'advmultiselect' => array(
2968 'HTML/QuickForm/advmultiselect.php',
2969 'HTML_QuickForm_advmultiselect',
2970 ),
2971 );
2972 }
2973
2974 /**
2975 * Set up an acl allowing contact to see 2 specified groups
2976 * - $this->_permissionedGroup & $this->_permissionedDisabledGroup
2977 *
2978 * You need to have pre-created these groups & created the user e.g
2979 * $this->createLoggedInUser();
2980 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2981 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2982 */
2983 public function setupACL() {
2984 global $_REQUEST;
2985 $_REQUEST = $this->_params;
2986
2987 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
2988 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2989 $optionValue = $this->callAPISuccess('option_value', 'create', array(
2990 'option_group_id' => $optionGroupID,
2991 'label' => 'pick me',
2992 'value' => 55,
2993 ));
2994
2995 CRM_Core_DAO::executeQuery("
2996 TRUNCATE civicrm_acl_cache
2997 ");
2998
2999 CRM_Core_DAO::executeQuery("
3000 TRUNCATE civicrm_acl_contact_cache
3001 ");
3002
3003 CRM_Core_DAO::executeQuery("
3004 INSERT INTO civicrm_acl_entity_role (
3005 `acl_role_id`, `entity_table`, `entity_id`
3006 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
3007 ");
3008
3009 CRM_Core_DAO::executeQuery("
3010 INSERT INTO civicrm_acl (
3011 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3012 )
3013 VALUES (
3014 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
3015 );
3016 ");
3017
3018 CRM_Core_DAO::executeQuery("
3019 INSERT INTO civicrm_acl (
3020 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
3021 )
3022 VALUES (
3023 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
3024 );
3025 ");
3026 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
3027 $this->callAPISuccess('group_contact', 'create', array(
3028 'group_id' => $this->_permissionedGroup,
3029 'contact_id' => $this->_loggedInUser,
3030 ));
3031 //flush cache
3032 CRM_ACL_BAO_Cache::resetCache();
3033 CRM_Contact_BAO_Group::getPermissionClause(TRUE);
3034 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
3035 }
3036
3037 /**
3038 * Alter default price set so that the field numbers are not all 1 (hiding errors)
3039 */
3040 public function offsetDefaultPriceSet() {
3041 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
3042 $firstID = $contributionPriceSet['id'];
3043 $this->callAPISuccess('price_set', 'create', array(
3044 'id' => $contributionPriceSet['id'],
3045 'is_active' => 0,
3046 'name' => 'old',
3047 ));
3048 unset($contributionPriceSet['id']);
3049 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
3050 $priceField = $this->callAPISuccess('price_field', 'getsingle', array(
3051 'price_set_id' => $firstID,
3052 'options' => array('limit' => 1),
3053 ));
3054 unset($priceField['id']);
3055 $priceField['price_set_id'] = $newPriceSet['id'];
3056 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
3057 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array(
3058 'price_set_id' => $firstID,
3059 'sequential' => 1,
3060 'options' => array('limit' => 1),
3061 ));
3062
3063 unset($priceFieldValue['id']);
3064 //create some padding to use up ids
3065 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3066 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
3067 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
3068 }
3069
3070 /**
3071 * Create an instance of the paypal processor
3072 * @todo this isn't a great place to put it - but really it belongs on a class that extends
3073 * this parent class & we don't have a structure for that yet
3074 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
3075 * & the best protection agains that is the functions this class affords
3076 */
3077 public function paymentProcessorCreate($params = array()) {
3078 $params = array_merge(array(
3079 'name' => 'demo',
3080 'domain_id' => CRM_Core_Config::domainID(),
3081 'payment_processor_type_id' => 'PayPal',
3082 'is_active' => 1,
3083 'is_default' => 0,
3084 'is_test' => 1,
3085 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
3086 'password' => '1183377788',
3087 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
3088 'url_site' => 'https://www.sandbox.paypal.com/',
3089 'url_api' => 'https://api-3t.sandbox.paypal.com/',
3090 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
3091 'class_name' => 'Payment_PayPalImpl',
3092 'billing_mode' => 3,
3093 'financial_type_id' => 1,
3094 ),
3095 $params);
3096 if (!is_numeric($params['payment_processor_type_id'])) {
3097 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
3098 //here
3099 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
3100 'name' => $params['payment_processor_type_id'],
3101 'return' => 'id',
3102 ), 'integer');
3103 }
3104 $result = $this->callAPISuccess('payment_processor', 'create', $params);
3105 return $result['id'];
3106 }
3107
3108 /**
3109 * Set up initial recurring payment allowing subsequent IPN payments
3110 */
3111 public function setupRecurringPaymentProcessorTransaction() {
3112 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array(
3113 'contact_id' => $this->_contactID,
3114 'amount' => 1000,
3115 'sequential' => 1,
3116 'installments' => 5,
3117 'frequency_unit' => 'Month',
3118 'frequency_interval' => 1,
3119 'invoice_id' => $this->_invoiceID,
3120 'contribution_status_id' => 2,
3121 'processor_id' => $this->_paymentProcessorID,
3122 'api.contribution.create' => array(
3123 'total_amount' => '200',
3124 'invoice_id' => $this->_invoiceID,
3125 'financial_type_id' => 1,
3126 'contribution_status_id' => 'Pending',
3127 'contact_id' => $this->_contactID,
3128 'contribution_page_id' => $this->_contributionPageID,
3129 'payment_processor_id' => $this->_paymentProcessorID,
3130 ),
3131 ));
3132 $this->_contributionRecurID = $contributionRecur['id'];
3133 $this->_contributionID = $contributionRecur['values']['0']['api.contribution.create']['id'];
3134 }
3135
3136 /**
3137 * 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
3138 */
3139 public function setupMembershipRecurringPaymentProcessorTransaction() {
3140 $this->ids['membership_type'] = $this->membershipTypeCreate();
3141 //create a contribution so our membership & contribution don't both have id = 1
3142 $this->contributionCreate($this->_contactID, 1, 'abcd', '345j');
3143 $this->setupRecurringPaymentProcessorTransaction();
3144
3145 $this->ids['membership'] = $this->callAPISuccess('membership', 'create', array(
3146 'contact_id' => $this->_contactID,
3147 'membership_type_id' => $this->ids['membership_type'],
3148 'contribution_recur_id' => $this->_contributionRecurID,
3149 'format.only_id' => TRUE,
3150 ));
3151 //CRM-15055 creates line items we don't want so get rid of them so we can set up our own line items
3152 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_line_item");
3153
3154 $this->callAPISuccess('line_item', 'create', array(
3155 'entity_table' => 'civicrm_membership',
3156 'entity_id' => $this->ids['membership'],
3157 'contribution_id' => $this->_contributionID,
3158 'label' => 'General',
3159 'qty' => 1,
3160 'unit_price' => 200,
3161 'line_total' => 200,
3162 'financial_type_id' => 1,
3163 'price_field_id' => $this->callAPISuccess('price_field', 'getvalue', array(
3164 'return' => 'id',
3165 'label' => 'Membership Amount',
3166 )),
3167 'price_field_value_id' => $this->callAPISuccess('price_field_value', 'getvalue', array(
3168 'return' => 'id',
3169 'label' => 'General',
3170 )),
3171 ));
3172 $this->callAPISuccess('membership_payment', 'create', array(
3173 'contribution_id' => $this->_contributionID,
3174 'membership_id' => $this->ids['membership'],
3175 ));
3176 }
3177
3178 /**
3179 * @param $message
3180 *
3181 * @throws Exception
3182 */
3183 public function CiviUnitTestCase_fatalErrorHandler($message) {
3184 throw new Exception("{$message['message']}: {$message['code']}");
3185 }
3186
3187 /**
3188 * Helper function to create new mailing
3189 * @return mixed
3190 */
3191 public function createMailing() {
3192 $params = array(
3193 'subject' => 'maild' . rand(),
3194 'body_text' => 'bdkfhdskfhduew',
3195 'name' => 'mailing name' . rand(),
3196 'created_id' => 1,
3197 'api.mailing_job.create' => 0,
3198 );
3199
3200 $result = $this->callAPISuccess('Mailing', 'create', $params);
3201 return $result['id'];
3202 }
3203
3204 /**
3205 * Helper function to delete mailing
3206 * @param $id
3207 */
3208 public function deleteMailing($id) {
3209 $params = array(
3210 'id' => $id,
3211 );
3212
3213 $this->callAPISuccess('Mailing', 'delete', $params);
3214 }
3215
3216 /**
3217 * Wrap the entire test case in a transaction
3218 *
3219 * Only subsequent DB statements will be wrapped in TX -- this cannot
3220 * retroactively wrap old DB statements. Therefore, it makes sense to
3221 * call this at the beginning of setUp().
3222 *
3223 * Note: Recall that TRUNCATE and ALTER will force-commit transactions, so
3224 * this option does not work with, e.g., custom-data.
3225 *
3226 * WISHLIST: Monitor SQL queries in unit-tests and generate an exception
3227 * if TRUNCATE or ALTER is called while using a transaction.
3228 *
3229 * @param bool $nest
3230 * Whether to use nesting or reference-counting.
3231 */
3232 public function useTransaction($nest = TRUE) {
3233 if (!$this->tx) {
3234 $this->tx = new CRM_Core_Transaction($nest);
3235 $this->tx->rollback();
3236 }
3237 }
3238
3239 public function clearOutputBuffer() {
3240 while (ob_get_level() > 0) {
3241 ob_end_clean();
3242 }
3243 }
3244 }