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