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