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