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