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