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