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