CRM-14793 add test for incorrect behaviour
[civicrm-core.git] / tests / phpunit / CiviTest / CiviUnitTestCase.php
CommitLineData
6a488035
TO
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/**
30 * Include configuration
31 */
32define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
33define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
34
35if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
36 require_once CIVICRM_SETTINGS_LOCAL_PATH;
37}
38require_once CIVICRM_SETTINGS_PATH;
39/**
40 * Include class definitions
41 */
42require_once 'PHPUnit/Extensions/Database/TestCase.php';
43require_once 'PHPUnit/Framework/TestResult.php';
44require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php';
45require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php';
46require_once 'PHPUnit/Extensions/Database/DataSet/QueryDataSet.php';
47require_once 'tests/phpunit/Utils.php';
48require_once 'api/api.php';
49require_once 'CRM/Financial/BAO/FinancialType.php';
50define('API_LATEST_VERSION', 3);
51
52/**
53 * Base class for CiviCRM unit tests
54 *
55 * Common functions for unit tests
56 * @package CiviCRM
57 */
58class CiviUnitTestCase extends PHPUnit_Extensions_Database_TestCase {
59
f6722559 60 /**
61 * api version - easier to override than just a defin
62 */
63 protected $_apiversion = API_LATEST_VERSION;
6a488035
TO
64 /**
65 * Database has been initialized
66 *
67 * @var boolean
68 */
69 private static $dbInit = FALSE;
70
71 /**
72 * Database connection
73 *
74 * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection
75 */
76 protected $_dbconn;
77
78 /**
79 * The database name
80 *
81 * @var string
82 */
83 static protected $_dbName;
84
0b6f58fa
ARW
85 /**
86 * Track tables we have modified during a test
87 */
88 protected $_tablesToTruncate = array();
89
6a488035
TO
90 /**
91 * @var array of temporary directory names
92 */
93 protected $tempDirs;
94
95 /**
96 * @var Utils instance
97 */
98 public static $utils;
99
100 /**
101 * @var boolean populateOnce allows to skip db resets in setUp
102 *
103 * WARNING! USE WITH CAUTION - IT'LL RENDER DATA DEPENDENCIES
104 * BETWEEN TESTS WHEN RUN IN SUITE. SUITABLE FOR LOCAL, LIMITED
105 * "CHECK RUNS" ONLY!
106 *
107 * IF POSSIBLE, USE $this->DBResetRequired = FALSE IN YOUR TEST CASE!
108 *
109 * see also: http://forum.civicrm.org/index.php/topic,18065.0.html
110 */
111 public static $populateOnce = FALSE;
112
113 /**
114 * Allow classes to state E-notice compliance
115 */
eafce897 116 public $_eNoticeCompliant = TRUE;
6a488035
TO
117
118 /**
119 * @var boolean DBResetRequired allows skipping DB reset
120 * in specific test case. If you still need
121 * to reset single test (method) of such case, call
122 * $this->cleanDB() in the first line of this
123 * test (method).
124 */
125 public $DBResetRequired = TRUE;
126
127 /**
128 * Constructor
129 *
130 * Because we are overriding the parent class constructor, we
131 * need to show the same arguments as exist in the constructor of
132 * PHPUnit_Framework_TestCase, since
133 * PHPUnit_Framework_TestSuite::createTest() creates a
134 * ReflectionClass of the Test class and checks the constructor
135 * of that class to decide how to set up the test.
136 *
137 * @param string $name
138 * @param array $data
139 * @param string $dataName
140 */
141 function __construct($name = NULL, array$data = array(), $dataName = '') {
142 parent::__construct($name, $data, $dataName);
143
144 // we need full error reporting
145 error_reporting(E_ALL & ~E_NOTICE);
146
147 if (!empty($GLOBALS['mysql_db'])) {
148 self::$_dbName = $GLOBALS['mysql_db'];
149 }
150 else {
151 self::$_dbName = 'civicrm_tests_dev';
152 }
153
154 // create test database
155 self::$utils = new Utils($GLOBALS['mysql_host'],
fc3c781d 156 $GLOBALS['mysql_port'],
6a488035
TO
157 $GLOBALS['mysql_user'],
158 $GLOBALS['mysql_pass']
159 );
160
161 // also load the class loader
162 require_once 'CRM/Core/ClassLoader.php';
163 CRM_Core_ClassLoader::singleton()->register();
164 if (function_exists('_civix_phpunit_setUp')) { // FIXME: loosen coupling
165 _civix_phpunit_setUp();
166 }
167 }
168
4cbe18b8
EM
169 /**
170 * @return bool
171 */
6a488035
TO
172 function requireDBReset() {
173 return $this->DBResetRequired;
174 }
175
4cbe18b8
EM
176 /**
177 * @return string
178 */
6a488035
TO
179 static function getDBName() {
180 $dbName = !empty($GLOBALS['mysql_db']) ? $GLOBALS['mysql_db'] : 'civicrm_tests_dev';
181 return $dbName;
182 }
183
184 /**
185 * Create database connection for this instance
186 *
187 * Initialize the test database if it hasn't been initialized
188 *
189 * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection connection
190 */
191 protected function getConnection() {
192 $dbName = self::$_dbName;
193 if (!self::$dbInit) {
194 $dbName = self::getDBName();
195
196 // install test database
197 echo PHP_EOL . "Installing {$dbName} database" . PHP_EOL;
198
99117745 199 static::_populateDB(FALSE, $this);
6a488035
TO
200
201 self::$dbInit = TRUE;
202 }
203 return $this->createDefaultDBConnection(self::$utils->pdo, $dbName);
204 }
205
206 /**
207 * Required implementation of abstract method
208 */
209 protected function getDataSet() {
210 }
211
99117745
TO
212 /**
213 * @param bool $perClass
214 * @param null $object
215 * @return bool TRUE if the populate logic runs; FALSE if it is skipped
216 */
217 protected static function _populateDB($perClass = FALSE, &$object = NULL) {
6a488035
TO
218
219 if ($perClass || $object == NULL) {
220 $dbreset = TRUE;
221 }
222 else {
223 $dbreset = $object->requireDBReset();
224 }
225
226 if (self::$populateOnce || !$dbreset) {
99117745 227 return FALSE;
6a488035
TO
228 }
229 self::$populateOnce = NULL;
230
231 $dbName = self::getDBName();
232 $pdo = self::$utils->pdo;
233 // only consider real tables and not views
234 $tables = $pdo->query("SELECT table_name FROM INFORMATION_SCHEMA.TABLES
235 WHERE TABLE_SCHEMA = '{$dbName}' AND TABLE_TYPE = 'BASE TABLE'");
236
237 $truncates = array();
238 $drops = array();
239 foreach ($tables as $table) {
240 // skip log tables
241 if (substr($table['table_name'], 0, 4) == 'log_') {
242 continue;
243 }
244
245 // don't change list of installed extensions
246 if ($table['table_name'] == 'civicrm_extension') {
247 continue;
248 }
249
250 if (substr($table['table_name'], 0, 14) == 'civicrm_value_') {
251 $drops[] = 'DROP TABLE ' . $table['table_name'] . ';';
252 }
253 else {
254 $truncates[] = 'TRUNCATE ' . $table['table_name'] . ';';
255 }
256 }
257
258 $queries = array(
259 "USE {$dbName};",
260 "SET foreign_key_checks = 0",
261 // SQL mode needs to be strict, that's our standard
262 "SET SQL_MODE='STRICT_ALL_TABLES';",
263 "SET global innodb_flush_log_at_trx_commit = 2;",
264 );
265 $queries = array_merge($queries, $truncates);
266 $queries = array_merge($queries, $drops);
267 foreach ($queries as $query) {
268 if (self::$utils->do_query($query) === FALSE) {
269 // failed to create test database
270 echo "failed to create test db.";
271 exit;
272 }
273 }
274
275 // initialize test database
276 $sql_file2 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/civicrm_data.mysql";
277 $sql_file3 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data.mysql";
278 $sql_file4 = dirname(dirname(dirname(dirname(__FILE__)))) . "/sql/test_data_second_domain.mysql";
279
280 $query2 = file_get_contents($sql_file2);
281 $query3 = file_get_contents($sql_file3);
282 $query4 = file_get_contents($sql_file4);
283 if (self::$utils->do_query($query2) === FALSE) {
284 echo "Cannot load civicrm_data.mysql. Aborting.";
285 exit;
286 }
287 if (self::$utils->do_query($query3) === FALSE) {
288 echo "Cannot load test_data.mysql. Aborting.";
289 exit;
290 }
291 if (self::$utils->do_query($query4) === FALSE) {
292 echo "Cannot load test_data.mysql. Aborting.";
293 exit;
294 }
295
296 // done with all the loading, get transactions back
297 if (self::$utils->do_query("set global innodb_flush_log_at_trx_commit = 1;") === FALSE) {
298 echo "Cannot set global? Huh?";
299 exit;
300 }
301
302 if (self::$utils->do_query("SET foreign_key_checks = 1") === FALSE) {
303 echo "Cannot get foreign keys back? Huh?";
304 exit;
305 }
306
307 unset($query, $query2, $query3);
308
309 // Rebuild triggers
310 civicrm_api('system', 'flush', array('version' => 3, 'triggers' => 1));
99117745
TO
311
312 return TRUE;
6a488035
TO
313 }
314
315 public static function setUpBeforeClass() {
99117745 316 static::_populateDB(TRUE);
6a488035
TO
317
318 // also set this global hack
319 $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array();
03a1f367
TO
320
321 $env = new CRM_Utils_Check_Env();
7342d7c4 322 CRM_Utils_Check::singleton()->assertValid($env->checkMysqlTime());
6a488035
TO
323 }
324
325 /**
326 * Common setup functions for all unit tests
327 */
328 protected function setUp() {
329 CRM_Utils_Hook::singleton(TRUE);
330 $this->errorScope = CRM_Core_TemporaryErrorScope::useException(); // REVERT
331 // Use a temporary file for STDIN
332 $GLOBALS['stdin'] = tmpfile();
333 if ($GLOBALS['stdin'] === FALSE) {
334 echo "Couldn't open temporary file\n";
335 exit(1);
336 }
337
338 // Get and save a connection to the database
339 $this->_dbconn = $this->getConnection();
340
341 // reload database before each test
342 // $this->_populateDB();
343
344 // "initialize" CiviCRM to avoid problems when running single tests
345 // FIXME: look at it closer in second stage
346
347 // initialize the object once db is loaded
72ad6c1b 348 CRM_Core_Config::$_mail = NULL;
6a488035
TO
349 $config = CRM_Core_Config::singleton();
350
351 // when running unit tests, use mockup user framework
352 $config->setUserFramework('UnitTests');
353
354 // also fix the fatal error handler to throw exceptions,
355 // rather than exit
356 $config->fatalErrorHandler = 'CiviUnitTestCase_fatalErrorHandler';
357
358 // enable backtrace to get meaningful errors
359 $config->backtrace = 1;
360
361 // disable any left-over test extensions
362 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
363
364 // reset all the caches
365 CRM_Utils_System::flushCache();
366
367 // clear permissions stub to not check permissions
368 $config = CRM_Core_Config::singleton();
369 $config->userPermissionClass->permissions = NULL;
370
371 //flush component settings
372 CRM_Core_Component::getEnabledComponents(TRUE);
373
374 if ($this->_eNoticeCompliant) {
375 error_reporting(E_ALL);
376 }
377 else {
378 error_reporting(E_ALL & ~E_NOTICE);
379 }
380 }
381
0b6f58fa
ARW
382 /**
383 * Read everything from the datasets directory and insert into the db
384 */
385 public function loadAllFixtures() {
386 $fixturesDir = __DIR__ . '/../../fixtures';
387
388 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 0;");
389
390 $xmlFiles = glob($fixturesDir . '/*.xml');
391 foreach ($xmlFiles as $xmlFixture) {
392 $op = new PHPUnit_Extensions_Database_Operation_Insert();
393 $dataset = new PHPUnit_Extensions_Database_DataSet_XMLDataSet($xmlFixture);
394 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
395 $op->execute($this->_dbconn, $dataset);
396 }
397
398 $yamlFiles = glob($fixturesDir . '/*.yaml');
399 foreach ($yamlFiles as $yamlFixture) {
400 $op = new PHPUnit_Extensions_Database_Operation_Insert();
401 $dataset = new PHPUnit_Extensions_Database_DataSet_YamlDataSet($yamlFixture);
402 $this->_tablesToTruncate = array_merge($this->_tablesToTruncate, $dataset->getTableNames());
403 $op->execute($this->_dbconn, $dataset);
404 }
405
406 $this->getConnection()->getConnection()->query("SET FOREIGN_KEY_CHECKS = 1;");
407 }
408
6a488035
TO
409 /**
410 * emulate a logged in user since certain functions use that
411 * value to store a record in the DB (like activity)
412 * CRM-8180
413 */
414 public function createLoggedInUser() {
415 $params = array(
416 'first_name' => 'Logged In',
417 'last_name' => 'User ' . rand(),
418 'contact_type' => 'Individual',
419 );
420 $contactID = $this->individualCreate($params);
421
422 $session = CRM_Core_Session::singleton();
423 $session->set('userID', $contactID);
424 }
425
426 public function cleanDB() {
427 self::$populateOnce = NULL;
428 $this->DBResetRequired = TRUE;
429
430 $this->_dbconn = $this->getConnection();
99117745 431 static::_populateDB();
6a488035
TO
432 $this->tempDirs = array();
433 }
434
435 /**
436 * Common teardown functions for all unit tests
437 */
438 protected function tearDown() {
439 error_reporting(E_ALL & ~E_NOTICE);
440 $tablesToTruncate = array('civicrm_contact');
441 $this->quickCleanup($tablesToTruncate);
442 $this->cleanTempDirs();
443 $this->unsetExtensionSystem();
444 }
445
446 /**
447 * FIXME: Maybe a better way to do it
448 */
449 function foreignKeyChecksOff() {
450 self::$utils = new Utils($GLOBALS['mysql_host'],
fc3c781d 451 $GLOBALS['mysql_port'],
6a488035
TO
452 $GLOBALS['mysql_user'],
453 $GLOBALS['mysql_pass']
454 );
455 $dbName = self::getDBName();
456 $query = "USE {$dbName};" . "SET foreign_key_checks = 1";
457 if (self::$utils->do_query($query) === FALSE) {
458 // fail happens
459 echo 'Cannot set foreign_key_checks = 0';
460 exit(1);
461 }
462 return TRUE;
463 }
464
465 function foreignKeyChecksOn() {
466 // FIXME: might not be needed if previous fixme implemented
467 }
468
469 /**
470 * Generic function to compare expected values after an api call to retrieved
471 * DB values.
472 *
473 * @daoName string DAO Name of object we're evaluating.
474 * @id int Id of object
475 * @match array Associative array of field name => expected value. Empty if asserting
476 * that a DELETE occurred
477 * @delete boolean True if we're checking that a DELETE action occurred.
478 */
479 function assertDBState($daoName, $id, $match, $delete = FALSE) {
480 if (empty($id)) {
481 // adding this here since developers forget to check for an id
482 // and hence we get the first value in the db
483 $this->fail('ID not populated. Please fix your assertDBState usage!!!');
484 }
485
4d5c2eb5 486 $object = new $daoName();
6a488035
TO
487 $object->id = $id;
488 $verifiedCount = 0;
489
490 // If we're asserting successful record deletion, make sure object is NOT found.
491 if ($delete) {
492 if ($object->find(TRUE)) {
493 $this->fail("Object not deleted by delete operation: $daoName, $id");
494 }
495 return;
496 }
497
498 // Otherwise check matches of DAO field values against expected values in $match.
499 if ($object->find(TRUE)) {
500 $fields = & $object->fields();
501 foreach ($fields as $name => $value) {
502 $dbName = $value['name'];
503 if (isset($match[$name])) {
504 $verifiedCount++;
505 $this->assertEquals($object->$dbName, $match[$name]);
506 }
507 elseif (isset($match[$dbName])) {
508 $verifiedCount++;
509 $this->assertEquals($object->$dbName, $match[$dbName]);
510 }
511 }
512 }
513 else {
514 $this->fail("Could not retrieve object: $daoName, $id");
515 }
516 $object->free();
517 $matchSize = count($match);
518 if ($verifiedCount != $matchSize) {
519 $this->fail("Did not verify all fields in match array: $daoName, $id. Verified count = $verifiedCount. Match array size = $matchSize");
520 }
521 }
522
523 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
4cbe18b8
EM
524 /**
525 * @param $daoName
526 * @param $searchValue
527 * @param $returnColumn
528 * @param $searchColumn
529 * @param $message
530 *
531 * @return null|string
532 * @throws PHPUnit_Framework_AssertionFailedError
533 */
6a488035
TO
534 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
535 if (empty($searchValue)) {
536 $this->fail("empty value passed to assertDBNotNull");
537 }
538 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
539 $this->assertNotNull($value, $message);
540
541 return $value;
542 }
543
544 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
4cbe18b8
EM
545 /**
546 * @param $daoName
547 * @param $searchValue
548 * @param $returnColumn
549 * @param $searchColumn
550 * @param $message
551 */
6a488035
TO
552 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
553 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
554 $this->assertNull($value, $message);
555 }
556
557 // Request a record from the DB by id. Success if row not found.
4cbe18b8
EM
558 /**
559 * @param $daoName
560 * @param $id
561 * @param null $message
562 */
6a488035
TO
563 function assertDBRowNotExist($daoName, $id, $message = NULL) {
564 $message = $message ? $message : "$daoName (#$id) should not exist";
565 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
566 $this->assertNull($value, $message);
567 }
568
569 // Request a record from the DB by id. Success if row not found.
4cbe18b8
EM
570 /**
571 * @param $daoName
572 * @param $id
573 * @param null $message
574 */
6a488035
TO
575 function assertDBRowExist($daoName, $id, $message = NULL) {
576 $message = $message ? $message : "$daoName (#$id) should exist";
577 $value = CRM_Core_DAO::getFieldValue($daoName, $id, 'id', 'id', TRUE);
578 $this->assertEquals($id, $value, $message);
579 }
580
581 // Compare a single column value in a retrieved DB record to an expected value
4cbe18b8
EM
582 /**
583 * @param $daoName
584 * @param $searchValue
585 * @param $returnColumn
586 * @param $searchColumn
587 * @param $expectedValue
588 * @param $message
589 */
6a488035
TO
590 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
591 $expectedValue, $message
592 ) {
593 $value = CRM_Core_DAO::getFieldValue($daoName, $searchValue, $returnColumn, $searchColumn, TRUE);
594 $this->assertEquals($value, $expectedValue, $message);
595 }
596
597 // Compare all values in a single retrieved DB record to an array of expected values
4cbe18b8
EM
598 /**
599 * @param $daoName
600 * @param $searchParams
601 * @param $expectedValues
602 */
6a488035
TO
603 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
604 //get the values from db
605 $dbValues = array();
606 CRM_Core_DAO::commonRetrieve($daoName, $searchParams, $dbValues);
607
608 // compare db values with expected values
609 self::assertAttributesEquals($expectedValues, $dbValues);
610 }
611
612 /**
613 * Assert that a SQL query returns a given value
614 *
615 * The first argument is an expected value. The remaining arguments are passed
616 * to CRM_Core_DAO::singleValueQuery
617 *
618 * Example: $this->assertSql(2, 'select count(*) from foo where foo.bar like "%1"',
619 * array(1 => array("Whiz", "String")));
620 */
621 function assertDBQuery($expected, $query, $params = array()) {
622 $actual = CRM_Core_DAO::singleValueQuery($query, $params);
623 $this->assertEquals($expected, $actual,
624 sprintf('expected=[%s] actual=[%s] query=[%s]',
625 $expected, $actual, CRM_Core_DAO::composeQuery($query, $params, FALSE)
626 )
627 );
628 }
629
630 /**
631 * Assert that two array-trees are exactly equal, notwithstanding
632 * the sorting of keys
633 *
634 * @param array $expected
635 * @param array $actual
636 */
637 function assertTreeEquals($expected, $actual) {
638 $e = array();
639 $a = array();
640 CRM_Utils_Array::flatten($expected, $e, '', ':::');
641 CRM_Utils_Array::flatten($actual, $a, '', ':::');
642 ksort($e);
643 ksort($a);
644
645 $this->assertEquals($e, $a);
646 }
647
dc92f2f8
TO
648 /**
649 * Assert that two numbers are approximately equal
650 *
651 * @param int|float $expected
652 * @param int|float $actual
653 * @param int|float $tolerance
654 * @param string $message
655 */
656 function assertApproxEquals($expected, $actual, $tolerance, $message = NULL) {
657 if ($message === NULL) {
658 $message = sprintf("approx-equals: expected=[%.3f] actual=[%.3f] tolerance=[%.3f]", $expected, $actual, $tolerance);
659 }
660 $this->assertTrue(abs($actual - $expected) < $tolerance, $message);
661 }
662
4cbe18b8
EM
663 /**
664 * @param $expectedValues
665 * @param $actualValues
666 * @param null $message
667 *
668 * @throws PHPUnit_Framework_AssertionFailedError
669 */
6a488035
TO
670 function assertAttributesEquals($expectedValues, $actualValues, $message = NULL) {
671 foreach ($expectedValues as $paramName => $paramValue) {
672 if (isset($actualValues[$paramName])) {
07fd63f5 673 $this->assertEquals($paramValue, $actualValues[$paramName], "Value Mismatch On $paramName - value 1 is " . print_r($paramValue, TRUE) . " value 2 is " . print_r($actualValues[$paramName], TRUE) );
6a488035
TO
674 }
675 else {
676 $this->fail("Attribute '$paramName' not present in actual array.");
677 }
678 }
679 }
680
4cbe18b8
EM
681 /**
682 * @param $key
683 * @param $list
684 */
6a488035
TO
685 function assertArrayKeyExists($key, &$list) {
686 $result = isset($list[$key]) ? TRUE : FALSE;
687 $this->assertTrue($result, ts("%1 element exists?",
688 array(1 => $key)
689 ));
690 }
691
4cbe18b8
EM
692 /**
693 * @param $key
694 * @param $list
695 */
6a488035
TO
696 function assertArrayValueNotNull($key, &$list) {
697 $this->assertArrayKeyExists($key, $list);
698
699 $value = isset($list[$key]) ? $list[$key] : NULL;
700 $this->assertTrue($value,
701 ts("%1 element not null?",
702 array(1 => $key)
703 )
704 );
705 }
706
c8950569
KJ
707 /**
708 * check that api returned 'is_error' => 0
709 * else provide full message
710 * @param array $apiResult api result
711 * @param string $prefix extra test to add to message
712 */
6a488035
TO
713 function assertAPISuccess($apiResult, $prefix = '') {
714 if (!empty($prefix)) {
715 $prefix .= ': ';
716 }
7681ca91 717 $errorMessage = empty($apiResult['error_message']) ? '' : " " . $apiResult['error_message'];
f6722559 718
719 if(!empty($apiResult['debug_information'])) {
720 $errorMessage .= "\n " . print_r($apiResult['debug_information'], TRUE);
721 }
7681ca91 722 if(!empty($apiResult['trace'])){
723 $errorMessage .= "\n" . print_r($apiResult['trace'], TRUE);
724 }
725 $this->assertEquals(0, $apiResult['is_error'], $prefix . $errorMessage);
6a488035
TO
726 }
727
feb2a730 728 /**
729 * check that api returned 'is_error' => 1
730 * else provide full message
2a6da8d7 731 *
feb2a730 732 * @param array $apiResult api result
733 * @param string $prefix extra test to add to message
2a6da8d7 734 * @param null $expectedError
feb2a730 735 */
64fe97da 736 function assertAPIFailure($apiResult, $prefix = '', $expectedError = NULL) {
feb2a730 737 if (!empty($prefix)) {
738 $prefix .= ': ';
739 }
64fe97da 740 if($expectedError && !empty($apiResult['is_error'])){
741 $this->assertEquals($expectedError, $apiResult['error_message'], 'api error message not as expected' . $prefix );
742 }
feb2a730 743 $this->assertEquals(1, $apiResult['is_error'], "api call should have failed but it succeeded " . $prefix . (print_r($apiResult, TRUE)));
f6722559 744 $this->assertNotEmpty($apiResult['error_message']);
feb2a730 745 }
746
4cbe18b8
EM
747 /**
748 * @param $expected
749 * @param $actual
750 * @param string $message
751 */
6a488035
TO
752 function assertType($expected, $actual, $message = '') {
753 return $this->assertInternalType($expected, $actual, $message);
754 }
54bd1003 755
c43d01f3 756 /**
757 * check that a deleted item has been deleted
758 */
759 function assertAPIDeleted($entity, $id) {
760 $this->callAPISuccess($entity, 'getcount', array('id' => $id), 0);
761 }
762
763
f6722559 764 /**
765 * check that api returned 'is_error' => 1
766 * else provide full message
2a6da8d7
EM
767 * @param $result
768 * @param $expected
769 * @param array $valuesToExclude
f6722559 770 * @param string $prefix extra test to add to message
2a6da8d7 771 * @internal param array $apiResult api result
f6722559 772 */
773 function assertAPIArrayComparison($result, $expected, $valuesToExclude = array(), $prefix = '') {
774 $valuesToExclude = array_merge($valuesToExclude, array('debug', 'xdebug', 'sequential'));
775 foreach ($valuesToExclude as $value) {
776 if(isset($result[$value])) {
777 unset($result[$value]);
778 }
779 if(isset($expected[$value])) {
780 unset($expected[$value]);
781 }
782 }
783 $this->assertEquals($result, $expected, "api result array comparison failed " . $prefix . print_r($result, TRUE) . ' was compared to ' . print_r($expected, TRUE));
784 }
785
0f643fb2
TO
786 /**
787 * A stub for the API interface. This can be overriden by subclasses to change how the API is called.
788 *
789 * @param $entity
790 * @param $action
791 * @param $params
792 * @return array|int
793 */
794 function civicrm_api($entity, $action, $params) {
795 return civicrm_api($entity, $action, $params);
796 }
797
54bd1003 798 /**
799 * This function exists to wrap api functions
791c263c 800 * so we can ensure they succeed & throw exceptions without litterering the test with checks
77b97be7 801 *
791c263c 802 * @param string $entity
803 * @param string $action
804 * @param array $params
a86d27fc 805 * @param mixed $checkAgainst optional value to check result against, implemented for getvalue,
806 * getcount, getsingle. Note that for getvalue the type is checked rather than the value
807 * for getsingle the array is compared against an array passed in - the id is not compared (for
808 * better or worse )
77b97be7
EM
809 *
810 * @return array|int
791c263c 811 */
f6722559 812 function callAPISuccess($entity, $action, $params, $checkAgainst = NULL) {
fbda92d3 813 $params = array_merge(array(
f6722559 814 'version' => $this->_apiversion,
fbda92d3 815 'debug' => 1,
816 ),
817 $params
9443c775 818 );
f6722559 819 switch (strtolower($action)) {
820 case 'getvalue' :
821 return $this->callAPISuccessGetValue($entity, $params, $checkAgainst);
822 case 'getsingle' :
823 return $this->callAPISuccessGetSingle($entity, $params, $checkAgainst);
824 case 'getcount' :
825 return $this->callAPISuccessGetCount($entity, $params, $checkAgainst);
826 }
0f643fb2 827 $result = $this->civicrm_api($entity, $action, $params);
54bd1003 828 $this->assertAPISuccess($result, "Failure in api call for $entity $action");
829 return $result;
830 }
831
fbda92d3 832 /**
833 * This function exists to wrap api getValue function & check the result
834 * so we can ensure they succeed & throw exceptions without litterering the test with checks
835 * There is a type check in this
77b97be7 836 *
fbda92d3 837 * @param string $entity
838 * @param array $params
839 * @param string $type - per http://php.net/manual/en/function.gettype.php possible types
c8950569
KJ
840 * - boolean
841 * - integer
842 * - double
843 * - string
844 * - array
845 * - object
77b97be7
EM
846 *
847 * @return array|int
fbda92d3 848 */
849 function callAPISuccessGetValue($entity, $params, $type = NULL) {
850 $params += array(
f6722559 851 'version' => $this->_apiversion,
fbda92d3 852 'debug' => 1,
853 );
0f643fb2 854 $result = $this->civicrm_api($entity, 'getvalue', $params);
fbda92d3 855 if($type){
856 if($type == 'integer'){
857 // api seems to return integers as strings
858 $this->assertTrue(is_numeric($result), "expected a numeric value but got " . print_r($result, 1));
859 }
860 else{
861 $this->assertType($type, $result, "returned result should have been of type $type but was " );
862 }
863 }
864 return $result;
865 }
c8950569 866
f6722559 867 /**
868 * This function exists to wrap api getsingle function & check the result
869 * so we can ensure they succeed & throw exceptions without litterering the test with checks
8deefe64 870 *
f6722559 871 * @param string $entity
872 * @param array $params
873 * @param array $checkAgainst - array to compare result against
874 * - boolean
875 * - integer
876 * - double
877 * - string
878 * - array
879 * - object
8deefe64 880 *
cbdcc634 881 * @throws Exception
8deefe64 882 * @return array|int
f6722559 883 */
884 function callAPISuccessGetSingle($entity, $params, $checkAgainst = NULL) {
885 $params += array(
886 'version' => $this->_apiversion,
887 'debug' => 1,
888 );
0f643fb2 889 $result = $this->civicrm_api($entity, 'getsingle', $params);
f6722559 890 if(!is_array($result) || !empty($result['is_error']) || isset($result['values'])) {
891 throw new Exception('Invalid getsingle result' . print_r($result, TRUE));
892 }
893 if($checkAgainst){
894 // @todo - have gone with the fn that unsets id? should we check id?
895 $this->checkArrayEquals($result, $checkAgainst);
896 }
897 return $result;
898 }
2a6da8d7 899
f6722559 900 /**
901 * This function exists to wrap api getValue function & check the result
902 * so we can ensure they succeed & throw exceptions without litterering the test with checks
903 * There is a type check in this
904 * @param string $entity
905 * @param array $params
2a6da8d7
EM
906 * @param null $count
907 * @throws Exception
908 * @return array|int
909 * @internal param string $type - per http://php.net/manual/en/function.gettype.php possible types
f6722559 910 * - boolean
911 * - integer
912 * - double
913 * - string
914 * - array
915 * - object
916 */
917 function callAPISuccessGetCount($entity, $params, $count = NULL) {
918 $params += array(
919 'version' => $this->_apiversion,
920 'debug' => 1,
921 );
0f643fb2 922 $result = $this->civicrm_api($entity, 'getcount', $params);
f6722559 923 if(!is_integer($result) || !empty($result['is_error']) || isset($result['values'])) {
924 throw new Exception('Invalid getcount result : ' . print_r($result, TRUE) . " type :" . gettype($result));
925 }
926 if(is_int($count)){
927 $this->assertEquals($count, $result, "incorect count returned from $entity getcount");
928 }
929 return $result;
930 }
69f028bc 931
54bd1003 932 /**
933 * This function exists to wrap api functions
934 * so we can ensure they succeed, generate and example & throw exceptions without litterering the test with checks
935 *
936 * @param string $entity
937 * @param string $action
938 * @param array $params
939 * @param string $function - pass this in to create a generated example
940 * @param string $file - pass this in to create a generated example
69f028bc
CW
941 * @param string $description
942 * @param string|null $subfile
943 * @param string|null $actionName
944 * @return array|int
54bd1003 945 */
9443c775 946 function callAPIAndDocument($entity, $action, $params, $function, $file, $description = "", $subfile = NULL, $actionName = NULL){
f6722559 947 $params['version'] = $this->_apiversion;
17400ace 948 $result = $this->callAPISuccess($entity, $action, $params);
9443c775 949 $this->documentMe($params, $result, $function, $file, $description, $subfile, $actionName);
54bd1003 950 return $result;
951 }
952
953 /**
954 * This function exists to wrap api functions
955 * so we can ensure they fail where expected & throw exceptions without litterering the test with checks
956 * @param string $entity
957 * @param string $action
958 * @param array $params
64fe97da 959 * @param string $expectedErrorMessage error
2a6da8d7
EM
960 * @param null $extraOutput
961 * @return array|int
54bd1003 962 */
64fe97da 963 function callAPIFailure($entity, $action, $params, $expectedErrorMessage = NULL, $extraOutput = NULL) {
9443c775
CW
964 if (is_array($params)) {
965 $params += array(
f6722559 966 'version' => $this->_apiversion,
9443c775
CW
967 );
968 }
0f643fb2 969 $result = $this->civicrm_api($entity, $action, $params);
54bd1003 970 $this->assertAPIFailure($result, "We expected a failure for $entity $action but got a success");
791c263c 971 return $result;
972 }
9443c775 973
fbda92d3 974 /**
975 * Create required data based on $this->entity & $this->params
976 * This is just a way to set up the test data for delete & get functions
977 * so the distinction between set
978 * up & tested functions is clearer
979 *
980 * @return array api Result
981 */
982 public function createTestEntity(){
983 return $entity = $this->callAPISuccess($this->entity, 'create', $this->params);
984 }
985
6a488035
TO
986 /**
987 * Generic function to create Organisation, to be used in test cases
988 *
989 * @param array parameters for civicrm_contact_add api function call
990 *
991 * @return int id of Organisation created
992 */
993 function organizationCreate($params = array()) {
994 if (!$params) {
995 $params = array();
996 }
997 $orgParams = array(
998 'organization_name' => 'Unit Test Organization',
999 'contact_type' => 'Organization',
6a488035
TO
1000 );
1001 return $this->_contactCreate(array_merge($orgParams, $params));
1002 }
1003
1004 /**
1005 * Generic function to create Individual, to be used in test cases
1006 *
1007 * @param array parameters for civicrm_contact_add api function call
1008 *
1009 * @return int id of Individual created
1010 */
04ee2e0e 1011 function individualCreate($params = array()) {
1012 $params = array_merge(array(
6a488035
TO
1013 'first_name' => 'Anthony',
1014 'middle_name' => 'J.',
1015 'last_name' => 'Anderson',
1016 'prefix_id' => 3,
1017 'suffix_id' => 3,
1018 'email' => 'anthony_anderson@civicrm.org',
1019 'contact_type' => 'Individual',
e0efd2d0 1020 ), $params);
04ee2e0e 1021
6a488035
TO
1022 return $this->_contactCreate($params);
1023 }
1024
1025 /**
1026 * Generic function to create Household, to be used in test cases
1027 *
1028 * @param array parameters for civicrm_contact_add api function call
1029 *
1030 * @return int id of Household created
1031 */
405f289b 1032 function householdCreate($params = array()) {
1033 $params = array_merge(array(
6a488035
TO
1034 'household_name' => 'Unit Test household',
1035 'contact_type' => 'Household',
405f289b 1036 ), $params);
6a488035
TO
1037 return $this->_contactCreate($params);
1038 }
1039
1040 /**
1041 * Private helper function for calling civicrm_contact_add
1042 *
9da2e77c
E
1043 * @param $params
1044 *
1045 * @throws Exception
1046 * @internal param \parameters $array for civicrm_contact_add api function call
6a488035
TO
1047 *
1048 * @return int id of Household created
1049 */
1050 private function _contactCreate($params) {
4732bb2f 1051 $result = $this->callAPISuccess('contact', 'create', $params);
8cc574cf 1052 if (!empty($result['is_error']) || empty($result['id'])) {
ace01fda 1053 throw new Exception('Could not create test contact, with message: ' . CRM_Utils_Array::value('error_message', $result) . "\nBacktrace:" . CRM_Utils_Array::value('trace', $result));
6a488035
TO
1054 }
1055 return $result['id'];
1056 }
1057
4cbe18b8
EM
1058 /**
1059 * @param $contactID
1060 *
1061 * @return array|int
1062 */
6a488035 1063 function contactDelete($contactID) {
ace01fda
CW
1064 $params = array(
1065 'id' => $contactID,
ace01fda
CW
1066 'skip_undelete' => 1,
1067 'debug' => 1,
1068 );
6a488035
TO
1069 $domain = new CRM_Core_BAO_Domain;
1070 $domain->contact_id = $contactID;
1071 if ($domain->find(TRUE)) {
1072 // we are finding tests trying to delete the domain contact in cleanup
1073 //since this is mainly for cleanup lets put a safeguard here
1074 return;
1075 }
f6722559 1076 $result = $this->callAPISuccess('contact', 'delete', $params);
1077 return $result;
6a488035
TO
1078 }
1079
4cbe18b8
EM
1080 /**
1081 * @param $contactTypeId
1082 *
1083 * @throws Exception
1084 */
6a488035
TO
1085 function contactTypeDelete($contactTypeId) {
1086 require_once 'CRM/Contact/BAO/ContactType.php';
1087 $result = CRM_Contact_BAO_ContactType::del($contactTypeId);
1088 if (!$result) {
1089 throw new Exception('Could not delete contact type');
1090 }
1091 }
1092
4cbe18b8
EM
1093 /**
1094 * @param array $params
1095 *
1096 * @return mixed
1097 */
75638074 1098 function membershipTypeCreate($params = array()) {
6a488035
TO
1099 CRM_Member_PseudoConstant::flush('membershipType');
1100 CRM_Core_Config::clearDBCache();
0090e3d2 1101 $memberOfOrganization = $this->organizationCreate();
75638074 1102 $params = array_merge(array(
6a488035
TO
1103 'name' => 'General',
1104 'duration_unit' => 'year',
1105 'duration_interval' => 1,
1106 'period_type' => 'rolling',
0090e3d2 1107 'member_of_contact_id' => $memberOfOrganization,
6a488035 1108 'domain_id' => 1,
75638074 1109 'financial_type_id' => 1,
6a488035 1110 'is_active' => 1,
6a488035 1111 'sequential' => 1,
eacf220c 1112 'visibility' => 'Public',
75638074 1113 ), $params);
1114
1115 $result = $this->callAPISuccess('MembershipType', 'Create', $params);
6a488035 1116
6a488035
TO
1117 CRM_Member_PseudoConstant::flush('membershipType');
1118 CRM_Utils_Cache::singleton()->flush();
6a488035
TO
1119
1120 return $result['id'];
1121 }
1122
4cbe18b8
EM
1123 /**
1124 * @param $params
1125 *
1126 * @return mixed
1127 */
6a488035
TO
1128 function contactMembershipCreate($params) {
1129 $pre = array(
1130 'join_date' => '2007-01-21',
1131 'start_date' => '2007-01-21',
1132 'end_date' => '2007-12-21',
1133 'source' => 'Payment',
6a488035
TO
1134 );
1135
1136 foreach ($pre as $key => $val) {
1137 if (!isset($params[$key])) {
1138 $params[$key] = $val;
1139 }
1140 }
1141
f6722559 1142 $result = $this->callAPISuccess('Membership', 'create', $params);
6a488035
TO
1143 return $result['id'];
1144 }
1145
1146 /**
1147 * Function to delete Membership Type
1148 *
2a6da8d7
EM
1149 * @param $params
1150 * @internal param int $membershipTypeID
6a488035
TO
1151 */
1152 function membershipTypeDelete($params) {
cab024d4 1153 $this->callAPISuccess('MembershipType', 'Delete', $params);
6a488035
TO
1154 }
1155
4cbe18b8
EM
1156 /**
1157 * @param $membershipID
1158 */
6a488035 1159 function membershipDelete($membershipID) {
f6722559 1160 $deleteParams = array('id' => $membershipID);
1161 $result = $this->callAPISuccess('Membership', 'Delete', $deleteParams);
6a488035
TO
1162 return;
1163 }
1164
4cbe18b8
EM
1165 /**
1166 * @param string $name
1167 *
1168 * @return mixed
1169 */
6a488035
TO
1170 function membershipStatusCreate($name = 'test member status') {
1171 $params['name'] = $name;
1172 $params['start_event'] = 'start_date';
1173 $params['end_event'] = 'end_date';
1174 $params['is_current_member'] = 1;
1175 $params['is_active'] = 1;
6a488035 1176
f6722559 1177 $result = $this->callAPISuccess('MembershipStatus', 'Create', $params);
6a488035 1178 CRM_Member_PseudoConstant::flush('membershipStatus');
6a488035
TO
1179 return $result['id'];
1180 }
1181
4cbe18b8
EM
1182 /**
1183 * @param $membershipStatusID
1184 */
6a488035
TO
1185 function membershipStatusDelete($membershipStatusID) {
1186 if (!$membershipStatusID) {
1187 return;
1188 }
4732bb2f 1189 $result = $this->callAPISuccess('MembershipStatus', 'Delete', array('id' => $membershipStatusID));
6a488035
TO
1190 return;
1191 }
1192
4cbe18b8
EM
1193 /**
1194 * @param array $params
1195 *
1196 * @return mixed
1197 */
75638074 1198 function relationshipTypeCreate($params = array()) {
1199 $params = array_merge(array(
6a488035
TO
1200 'name_a_b' => 'Relation 1 for relationship type create',
1201 'name_b_a' => 'Relation 2 for relationship type create',
1202 'contact_type_a' => 'Individual',
1203 'contact_type_b' => 'Organization',
1204 'is_reserved' => 1,
1205 'is_active' => 1,
75638074 1206 ),
1207 $params
1208 );
6a488035 1209
f6722559 1210 $result = $this->callAPISuccess('relationship_type', 'create', $params);
6a488035
TO
1211 CRM_Core_PseudoConstant::flush('relationshipType');
1212
1213 return $result['id'];
1214 }
1215
1216 /**
1217 * Function to delete Relatinship Type
1218 *
1219 * @param int $relationshipTypeID
1220 */
1221 function relationshipTypeDelete($relationshipTypeID) {
1222 $params['id'] = $relationshipTypeID;
f6722559 1223 $this->callAPISuccess('relationship_type', 'delete', $params);
6a488035
TO
1224 }
1225
4cbe18b8
EM
1226 /**
1227 * @param null $params
1228 *
1229 * @return mixed
1230 */
6a488035
TO
1231 function paymentProcessorTypeCreate($params = NULL) {
1232 if (is_null($params)) {
1233 $params = array(
1234 'name' => 'API_Test_PP',
1235 'title' => 'API Test Payment Processor',
1236 'class_name' => 'CRM_Core_Payment_APITest',
1237 'billing_mode' => 'form',
1238 'is_recur' => 0,
1239 'is_reserved' => 1,
1240 'is_active' => 1,
1241 );
1242 }
f6722559 1243 $result = $this->callAPISuccess('payment_processor_type', 'create', $params);
6a488035 1244
6a488035
TO
1245 CRM_Core_PseudoConstant::flush('paymentProcessorType');
1246
1247 return $result['id'];
1248 }
1249
1250 /**
1251 * Function to create Participant
1252 *
1253 * @param array $params array of contact id and event id values
1254 *
1255 * @return int $id of participant created
1256 */
1257 function participantCreate($params) {
94692f2d 1258 if(empty($params['contact_id'])){
1259 $params['contact_id'] = $this->individualCreate();
1260 }
1261 if(empty($params['event_id'])){
1262 $event = $this->eventCreate();
1263 $params['event_id'] = $event['id'];
1264 }
6a488035 1265 $defaults = array(
6a488035
TO
1266 'status_id' => 2,
1267 'role_id' => 1,
1268 'register_date' => 20070219,
1269 'source' => 'Wimbeldon',
1270 'event_level' => 'Payment',
94692f2d 1271 'debug' => 1,
6a488035
TO
1272 );
1273
1274 $params = array_merge($defaults, $params);
f6722559 1275 $result = $this->callAPISuccess('Participant', 'create', $params);
6a488035
TO
1276 return $result['id'];
1277 }
1278
1279 /**
1280 * Function to create Payment Processor
1281 *
1282 * @return object of Payment Processsor
1283 */
1284 function processorCreate() {
1285 $processorParams = array(
1286 'domain_id' => 1,
1287 'name' => 'Dummy',
1288 'payment_processor_type_id' => 10,
1289 'financial_account_id' => 12,
1290 'is_active' => 1,
1291 'user_name' => '',
1292 'url_site' => 'http://dummy.com',
1293 'url_recur' => 'http://dummy.com',
1294 'billing_mode' => 1,
1295 );
1296 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::create($processorParams);
1297 return $paymentProcessor;
1298 }
1299
1300 /**
1301 * Function to create contribution page
1302 *
2a6da8d7 1303 * @param $params
6a488035
TO
1304 * @return object of contribution page
1305 */
1306 function contributionPageCreate($params) {
1307 $this->_pageParams = array(
6a488035
TO
1308 'title' => 'Test Contribution Page',
1309 'financial_type_id' => 1,
1310 'currency' => 'USD',
1311 'financial_account_id' => 1,
1312 'payment_processor' => $params['processor_id'],
1313 'is_active' => 1,
1314 'is_allow_other_amount' => 1,
1315 'min_amount' => 10,
1316 'max_amount' => 1000,
1317 );
f6722559 1318 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
6a488035
TO
1319 return $contributionPage;
1320 }
1321
6a488035
TO
1322 /**
1323 * Function to create Tag
1324 *
2a6da8d7 1325 * @param array $params
fb32de45 1326 * @return array result of created tag
6a488035 1327 */
fb32de45 1328 function tagCreate($params = array()) {
1329 $defaults = array(
1330 'name' => 'New Tag3',
1331 'description' => 'This is description for Our New Tag ',
1332 'domain_id' => '1',
1333 );
1334 $params = array_merge($defaults, $params);
1335 $result = $this->callAPISuccess('Tag', 'create', $params);
1336 return $result['values'][$result['id']];
6a488035
TO
1337 }
1338
1339 /**
1340 * Function to delete Tag
1341 *
1342 * @param int $tagId id of the tag to be deleted
1343 */
1344 function tagDelete($tagId) {
1345 require_once 'api/api.php';
1346 $params = array(
1347 'tag_id' => $tagId,
6a488035 1348 );
f6722559 1349 $result = $this->callAPISuccess('Tag', 'delete', $params);
6a488035
TO
1350 return $result['id'];
1351 }
1352
1353 /**
1354 * Add entity(s) to the tag
1355 *
77b97be7
EM
1356 * @param array $params
1357 *
1358 * @return bool
6a488035
TO
1359 */
1360 function entityTagAdd($params) {
f6722559 1361 $result = $this->callAPISuccess('entity_tag', 'create', $params);
6a488035
TO
1362 return TRUE;
1363 }
1364
1365 /**
1366 * Function to create contribution
1367 *
77b97be7
EM
1368 * @param int $cID contact_id
1369 *
1370 * @internal param int $cTypeID id of financial type
6a488035
TO
1371 *
1372 * @return int id of created contribution
1373 */
1374 function pledgeCreate($cID) {
1375 $params = array(
1376 'contact_id' => $cID,
1377 'pledge_create_date' => date('Ymd'),
1378 'start_date' => date('Ymd'),
1379 'scheduled_date' => date('Ymd'),
1380 'amount' => 100.00,
1381 'pledge_status_id' => '2',
1382 'financial_type_id' => '1',
1383 'pledge_original_installment_amount' => 20,
1384 'frequency_interval' => 5,
1385 'frequency_unit' => 'year',
1386 'frequency_day' => 15,
1387 'installments' => 5,
6a488035
TO
1388 );
1389
f6722559 1390 $result = $this->callAPISuccess('Pledge', 'create', $params);
6a488035
TO
1391 return $result['id'];
1392 }
1393
1394 /**
1395 * Function to delete contribution
1396 *
2a6da8d7
EM
1397 * @param $pledgeId
1398 * @internal param int $contributionId
6a488035
TO
1399 */
1400 function pledgeDelete($pledgeId) {
1401 $params = array(
1402 'pledge_id' => $pledgeId,
6a488035 1403 );
f6722559 1404 $this->callAPISuccess('Pledge', 'delete', $params);
6a488035
TO
1405 }
1406
1407 /**
1408 * Function to create contribution
1409 *
2a6da8d7
EM
1410 * @param int $cID contact_id
1411 * @param int $cTypeID id of financial type
6a488035 1412 *
2a6da8d7
EM
1413 * @param int $invoiceID
1414 * @param int $trxnID
1415 * @param int $paymentInstrumentID
1416 * @param bool $isFee
6a488035
TO
1417 * @return int id of created contribution
1418 */
1419 function contributionCreate($cID, $cTypeID = 1, $invoiceID = 67890, $trxnID = 12345, $paymentInstrumentID = 1, $isFee = TRUE) {
1420 $params = array(
1421 'domain_id' => 1,
1422 'contact_id' => $cID,
1423 'receive_date' => date('Ymd'),
1424 'total_amount' => 100.00,
1425 'financial_type_id' => empty($cTypeID) ? 1 : $cTypeID,
1426 'payment_instrument_id' => empty($paymentInstrumentID) ? 1 : $paymentInstrumentID,
1427 'non_deductible_amount' => 10.00,
1428 'trxn_id' => $trxnID,
1429 'invoice_id' => $invoiceID,
1430 'source' => 'SSF',
6a488035
TO
1431 'contribution_status_id' => 1,
1432 // 'note' => 'Donating for Nobel Cause', *Fixme
1433 );
1434
1435 if ($isFee) {
1436 $params['fee_amount'] = 5.00;
1437 $params['net_amount'] = 95.00;
1438 }
1439
f6722559 1440 $result = $this->callAPISuccess('contribution', 'create', $params);
6a488035
TO
1441 return $result['id'];
1442 }
1443
1444 /**
1445 * Function to create online contribution
1446 *
2a6da8d7
EM
1447 * @param $params
1448 * @param int $financialType id of financial type
6a488035 1449 *
2a6da8d7
EM
1450 * @param int $invoiceID
1451 * @param int $trxnID
6a488035
TO
1452 * @return int id of created contribution
1453 */
1454 function onlineContributionCreate($params, $financialType, $invoiceID = 67890, $trxnID = 12345) {
1455 $contribParams = array(
1456 'contact_id' => $params['contact_id'],
1457 'receive_date' => date('Ymd'),
1458 'total_amount' => 100.00,
1459 'financial_type_id' => $financialType,
1460 'contribution_page_id' => $params['contribution_page_id'],
1461 'trxn_id' => 12345,
1462 'invoice_id' => 67890,
1463 'source' => 'SSF',
6a488035 1464 );
f6722559 1465 $contribParams = array_merge($contribParams, $params);
1466 $result = $this->callAPISuccess('contribution', 'create', $contribParams);
6a488035
TO
1467
1468 return $result['id'];
1469 }
1470
1471 /**
1472 * Function to delete contribution
1473 *
1474 * @param int $contributionId
8deefe64
EM
1475 *
1476 * @return array|int
6a488035
TO
1477 */
1478 function contributionDelete($contributionId) {
1479 $params = array(
1480 'contribution_id' => $contributionId,
6a488035 1481 );
f6722559 1482 $result = $this->callAPISuccess('contribution', 'delete', $params);
6a488035
TO
1483 return $result;
1484 }
1485
1486 /**
1487 * Function to create an Event
1488 *
1489 * @param array $params name-value pair for an event
1490 *
1491 * @return array $event
1492 */
1493 function eventCreate($params = array()) {
1494 // if no contact was passed, make up a dummy event creator
1495 if (!isset($params['contact_id'])) {
1496 $params['contact_id'] = $this->_contactCreate(array(
1497 'contact_type' => 'Individual',
1498 'first_name' => 'Event',
1499 'last_name' => 'Creator',
6a488035
TO
1500 ));
1501 }
1502
1503 // set defaults for missing params
1504 $params = array_merge(array(
1505 'title' => 'Annual CiviCRM meet',
1506 'summary' => 'If you have any CiviCRM related issues or want to track where CiviCRM is heading, Sign up now',
1507 'description' => 'This event is intended to give brief idea about progess of CiviCRM and giving solutions to common user issues',
1508 'event_type_id' => 1,
1509 'is_public' => 1,
1510 'start_date' => 20081021,
1511 'end_date' => 20081023,
1512 'is_online_registration' => 1,
1513 'registration_start_date' => 20080601,
1514 'registration_end_date' => 20081015,
1515 'max_participants' => 100,
1516 'event_full_text' => 'Sorry! We are already full',
1517 'is_monetory' => 0,
1518 'is_active' => 1,
6a488035
TO
1519 'is_show_location' => 0,
1520 ), $params);
1521
8cba5814 1522 return $this->callAPISuccess('Event', 'create', $params);
6a488035
TO
1523 }
1524
1525 /**
1526 * Function to delete event
1527 *
8deefe64
EM
1528 * @param int $id ID of the event
1529 *
1530 * @return array|int
6a488035
TO
1531 */
1532 function eventDelete($id) {
1533 $params = array(
1534 'event_id' => $id,
6a488035 1535 );
8cba5814 1536 return $this->callAPISuccess('event', 'delete', $params);
6a488035
TO
1537 }
1538
1539 /**
1540 * Function to delete participant
1541 *
1542 * @param int $participantID
8deefe64
EM
1543 *
1544 * @return array|int
6a488035
TO
1545 */
1546 function participantDelete($participantID) {
1547 $params = array(
1548 'id' => $participantID,
6a488035 1549 );
8cba5814 1550 return $this->callAPISuccess('Participant', 'delete', $params);
6a488035
TO
1551 }
1552
1553 /**
1554 * Function to create participant payment
1555 *
2a6da8d7
EM
1556 * @param $participantID
1557 * @param null $contributionID
6a488035
TO
1558 * @return int $id of created payment
1559 */
1560 function participantPaymentCreate($participantID, $contributionID = NULL) {
1561 //Create Participant Payment record With Values
1562 $params = array(
1563 'participant_id' => $participantID,
1564 'contribution_id' => $contributionID,
6a488035
TO
1565 );
1566
f6722559 1567 $result = $this->callAPISuccess('participant_payment', 'create', $params);
6a488035
TO
1568 return $result['id'];
1569 }
1570
1571 /**
1572 * Function to delete participant payment
1573 *
1574 * @param int $paymentID
1575 */
1576 function participantPaymentDelete($paymentID) {
1577 $params = array(
1578 'id' => $paymentID,
6a488035 1579 );
f6722559 1580 $result = $this->callAPISuccess('participant_payment', 'delete', $params);
6a488035
TO
1581 }
1582
1583 /**
1584 * Function to add a Location
1585 *
2a6da8d7 1586 * @param $contactID
6a488035
TO
1587 * @return int location id of created location
1588 */
1589 function locationAdd($contactID) {
1590 $address = array(
1591 1 => array(
1592 'location_type' => 'New Location Type',
1593 'is_primary' => 1,
1594 'name' => 'Saint Helier St',
1595 'county' => 'Marin',
1596 'country' => 'United States',
1597 'state_province' => 'Michigan',
1598 'supplemental_address_1' => 'Hallmark Ct',
1599 'supplemental_address_2' => 'Jersey Village',
1600 )
1601 );
1602
1603 $params = array(
1604 'contact_id' => $contactID,
1605 'address' => $address,
6a488035
TO
1606 'location_format' => '2.0',
1607 'location_type' => 'New Location Type',
1608 );
1609
f6722559 1610 $result = $this->callAPISuccess('Location', 'create', $params);
6a488035
TO
1611 return $result;
1612 }
1613
1614 /**
1615 * Function to delete Locations of contact
1616 *
1617 * @params array $pamars parameters
1618 */
1619 function locationDelete($params) {
f6722559 1620 $result = $this->callAPISuccess('Location', 'delete', $params);
6a488035
TO
1621 }
1622
1623 /**
1624 * Function to add a Location Type
1625 *
2a6da8d7 1626 * @param null $params
6a488035
TO
1627 * @return int location id of created location
1628 */
1629 function locationTypeCreate($params = NULL) {
1630 if ($params === NULL) {
1631 $params = array(
1632 'name' => 'New Location Type',
1633 'vcard_name' => 'New Location Type',
1634 'description' => 'Location Type for Delete',
1635 'is_active' => 1,
1636 );
1637 }
1638
6a488035
TO
1639 $locationType = new CRM_Core_DAO_LocationType();
1640 $locationType->copyValues($params);
1641 $locationType->save();
1642 // clear getfields cache
2683ce94 1643 CRM_Core_PseudoConstant::flush();
f6722559 1644 $this->callAPISuccess('phone', 'getfields', array('version' => 3, 'cache_clear' => 1));
6a488035
TO
1645 return $locationType;
1646 }
1647
1648 /**
1649 * Function to delete a Location Type
1650 *
1651 * @param int location type id
1652 */
1653 function locationTypeDelete($locationTypeId) {
6a488035
TO
1654 $locationType = new CRM_Core_DAO_LocationType();
1655 $locationType->id = $locationTypeId;
1656 $locationType->delete();
1657 }
1658
1659 /**
1660 * Function to add a Group
1661 *
1662 * @params array to add group
1663 *
2a6da8d7 1664 * @param array $params
6a488035 1665 * @return int groupId of created group
6a488035 1666 */
fadb804f
EM
1667 function groupCreate($params = array()) {
1668 $params = array_merge(array(
6a488035
TO
1669 'name' => 'Test Group 1',
1670 'domain_id' => 1,
1671 'title' => 'New Test Group Created',
1672 'description' => 'New Test Group Created',
1673 'is_active' => 1,
1674 'visibility' => 'Public Pages',
1675 'group_type' => array(
1676 '1' => 1,
1677 '2' => 1,
1678 ),
fadb804f 1679 ), $params);
6a488035 1680
f6722559 1681 $result = $this->callAPISuccess('Group', 'create', $params);
1682 return $result['id'];
6a488035
TO
1683 }
1684
1685 /**
1686 * Function to delete a Group
1687 *
2a6da8d7
EM
1688 * @param $gid
1689 * @internal param int $id
6a488035
TO
1690 */
1691 function groupDelete($gid) {
1692
1693 $params = array(
1694 'id' => $gid,
6a488035
TO
1695 );
1696
f6722559 1697 $this->callAPISuccess('Group', 'delete', $params);
6a488035
TO
1698 }
1699
5c496c74 1700 /**
1701 * Create a UFField
1702 * @param array $params
1703 */
1704 function uFFieldCreate($params = array()) {
1705 $params = array_merge(array(
1706 'uf_group_id' => 1,
1707 'field_name' => 'first_name',
1708 'is_active' => 1,
1709 'is_required' => 1,
1710 'visibility' => 'Public Pages and Listings',
1711 'is_searchable' => '1',
1712 'label' => 'first_name',
1713 'field_type' => 'Individual',
1714 'weight' => 1,
1715 ), $params);
1716 $this->callAPISuccess('uf_field', 'create', $params);
1717 }
2a6da8d7 1718
6a488035
TO
1719 /**
1720 * Function to add a UF Join Entry
1721 *
2a6da8d7 1722 * @param null $params
6a488035
TO
1723 * @return int $id of created UF Join
1724 */
1725 function ufjoinCreate($params = NULL) {
1726 if ($params === NULL) {
1727 $params = array(
1728 'is_active' => 1,
1729 'module' => 'CiviEvent',
1730 'entity_table' => 'civicrm_event',
1731 'entity_id' => 3,
1732 'weight' => 1,
1733 'uf_group_id' => 1,
1734 );
1735 }
f6722559 1736 $result = $this->callAPISuccess('uf_join', 'create', $params);
6a488035
TO
1737 return $result;
1738 }
1739
1740 /**
1741 * Function to delete a UF Join Entry
1742 *
1743 * @param array with missing uf_group_id
1744 */
1745 function ufjoinDelete($params = NULL) {
1746 if ($params === NULL) {
1747 $params = array(
1748 'is_active' => 1,
1749 'module' => 'CiviEvent',
1750 'entity_table' => 'civicrm_event',
1751 'entity_id' => 3,
1752 'weight' => 1,
1753 'uf_group_id' => '',
1754 );
1755 }
1756
1757 crm_add_uf_join($params);
1758 }
1759
1760 /**
1761 * Function to create Group for a contact
1762 *
1763 * @param int $contactId
1764 */
1765 function contactGroupCreate($contactId) {
1766 $params = array(
1767 'contact_id.1' => $contactId,
1768 'group_id' => 1,
1769 );
1770
f6722559 1771 $this->callAPISuccess('GroupContact', 'Create', $params);
6a488035
TO
1772 }
1773
1774 /**
1775 * Function to delete Group for a contact
1776 *
2a6da8d7
EM
1777 * @param $contactId
1778 * @internal param array $params
6a488035
TO
1779 */
1780 function contactGroupDelete($contactId) {
1781 $params = array(
1782 'contact_id.1' => $contactId,
1783 'group_id' => 1,
1784 );
0f643fb2 1785 $this->civicrm_api('GroupContact', 'Delete', $params);
6a488035
TO
1786 }
1787
1788 /**
1789 * Function to create Activity
1790 *
2a6da8d7
EM
1791 * @param null $params
1792 * @return array|int
1793 * @internal param int $contactId
6a488035
TO
1794 */
1795 function activityCreate($params = NULL) {
1796
1797 if ($params === NULL) {
e4d5f1e2 1798 $individualSourceID = $this->individualCreate();
6a488035
TO
1799
1800 $contactParams = array(
1801 'first_name' => 'Julia',
1802 'Last_name' => 'Anderson',
1803 'prefix' => 'Ms.',
1804 'email' => 'julia_anderson@civicrm.org',
1805 'contact_type' => 'Individual',
6a488035
TO
1806 );
1807
1808 $individualTargetID = $this->individualCreate($contactParams);
1809
1810 $params = array(
1811 'source_contact_id' => $individualSourceID,
1812 'target_contact_id' => array($individualTargetID),
1813 'assignee_contact_id' => array($individualTargetID),
1814 'subject' => 'Discussion on warm beer',
1815 'activity_date_time' => date('Ymd'),
1816 'duration_hours' => 30,
1817 'duration_minutes' => 20,
1818 'location' => 'Baker Street',
1819 'details' => 'Lets schedule a meeting',
1820 'status_id' => 1,
1821 'activity_name' => 'Meeting',
6a488035
TO
1822 );
1823 }
1824
f6722559 1825 $result = $this->callAPISuccess('Activity', 'create', $params);
6a488035
TO
1826
1827 $result['target_contact_id'] = $individualTargetID;
1828 $result['assignee_contact_id'] = $individualTargetID;
1829 return $result;
1830 }
1831
1832 /**
1833 * Function to create an activity type
1834 *
1835 * @params array $params parameters
1836 */
1837 function activityTypeCreate($params) {
f6722559 1838 $result = $this->callAPISuccess('ActivityType', 'create', $params);
6a488035
TO
1839 return $result;
1840 }
1841
1842 /**
1843 * Function to delete activity type
1844 *
1845 * @params Integer $activityTypeId id of the activity type
1846 */
1847 function activityTypeDelete($activityTypeId) {
1848 $params['activity_type_id'] = $activityTypeId;
f6722559 1849 $result = $this->callAPISuccess('ActivityType', 'delete', $params);
6a488035
TO
1850 return $result;
1851 }
1852
1853 /**
1854 * Function to create custom group
1855 *
2a6da8d7
EM
1856 * @param array $params
1857 * @return array|int
1858 * @internal param string $className
1859 * @internal param string $title name of custom group
6a488035 1860 */
f6722559 1861 function customGroupCreate($params = array()) {
1862 $defaults = array(
1863 'title' => 'new custom group',
1864 'extends' => 'Contact',
1865 'domain_id' => 1,
1866 'style' => 'Inline',
1867 'is_active' => 1,
1868 );
6a488035 1869
f6722559 1870 $params = array_merge($defaults, $params);
1871
1872 if (strlen($params['title']) > 13) {
1873 $params['title'] = substr($params['title'], 0, 13);
6a488035 1874 }
6a488035 1875
f6722559 1876 //have a crack @ deleting it first in the hope this will prevent derailing our tests
1877 $check = $this->callAPISuccess('custom_group', 'get', array('title' => $params['title'], array('api.custom_group.delete' => 1)));
6a488035 1878
f6722559 1879 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1880 }
1881
1882 /**
1883 * existing function doesn't allow params to be over-ridden so need a new one
1884 * this one allows you to only pass in the params you want to change
1885 */
1886 function CustomGroupCreateByParams($params = array()) {
1887 $defaults = array(
1888 'title' => "API Custom Group",
1889 'extends' => 'Contact',
1890 'domain_id' => 1,
1891 'style' => 'Inline',
1892 'is_active' => 1,
6a488035
TO
1893 );
1894 $params = array_merge($defaults, $params);
f6722559 1895 return $this->callAPISuccess('custom_group', 'create', $params);
6a488035
TO
1896 }
1897
1898 /**
1899 * Create custom group with multi fields
1900 */
1901 function CustomGroupMultipleCreateByParams($params = array()) {
1902 $defaults = array(
1903 'style' => 'Tab',
1904 'is_multiple' => 1,
1905 );
1906 $params = array_merge($defaults, $params);
f6722559 1907 return $this->CustomGroupCreateByParams($params);
6a488035
TO
1908 }
1909
1910 /**
1911 * Create custom group with multi fields
1912 */
1913 function CustomGroupMultipleCreateWithFields($params = array()) {
1914 // also need to pass on $params['custom_field'] if not set but not in place yet
1915 $ids = array();
1916 $customGroup = $this->CustomGroupMultipleCreateByParams($params);
1917 $ids['custom_group_id'] = $customGroup['id'];
6a488035 1918
b422b715 1919 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'label' => 'field_1' . $ids['custom_group_id']));
6a488035
TO
1920
1921 $ids['custom_field_id'][] = $customField['id'];
f6722559 1922
b422b715 1923 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_2' . $ids['custom_group_id']));
6a488035 1924 $ids['custom_field_id'][] = $customField['id'];
f6722559 1925
b422b715 1926 $customField = $this->customFieldCreate(array('custom_group_id' => $ids['custom_group_id'], 'default_value' => '', 'label' => 'field_3' . $ids['custom_group_id']));
6a488035 1927 $ids['custom_field_id'][] = $customField['id'];
f6722559 1928
6a488035
TO
1929 return $ids;
1930 }
1931
1932 /**
1933 * Create a custom group with a single text custom field. See
1934 * participant:testCreateWithCustom for how to use this
1935 *
1936 * @param string $function __FUNCTION__
2a6da8d7
EM
1937 * @param $filename
1938 * @internal param string $file __FILE__
6a488035
TO
1939 *
1940 * @return array $ids ids of created objects
6a488035
TO
1941 */
1942 function entityCustomGroupWithSingleFieldCreate($function, $filename) {
f6722559 1943 $params = array('title' => $function);
6a488035 1944 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
f6722559 1945 $params['extends'] = $entity ? $entity : 'Contact';
1946 $customGroup = $this->CustomGroupCreate($params);
b422b715 1947 $customField = $this->customFieldCreate(array('custom_group_id' => $customGroup['id'], 'label' => $function));
80085473 1948 CRM_Core_PseudoConstant::flush();
6a488035
TO
1949
1950 return array('custom_group_id' => $customGroup['id'], 'custom_field_id' => $customField['id']);
1951 }
1952
1953 /**
1954 * Function to delete custom group
1955 *
8deefe64
EM
1956 * @param int $customGroupID
1957 *
1958 * @return array|int
6a488035
TO
1959 */
1960 function customGroupDelete($customGroupID) {
6a488035 1961 $params['id'] = $customGroupID;
f6722559 1962 return $this->callAPISuccess('custom_group', 'delete', $params);
6a488035
TO
1963 }
1964
1965 /**
1966 * Function to create custom field
1967 *
b422b715 1968 * @param array $params (custom_group_id) is required
2a6da8d7
EM
1969 * @return array|int
1970 * @internal param string $name name of custom field
1971 * @internal param int $apiversion API version to use
6a488035 1972 */
b422b715 1973 function customFieldCreate($params) {
1974 $params = array_merge(array(
1975 'label' => 'Custom Field',
6a488035
TO
1976 'data_type' => 'String',
1977 'html_type' => 'Text',
1978 'is_searchable' => 1,
1979 'is_active' => 1,
5c496c74 1980 'default_value' => 'defaultValue',
b422b715 1981 ), $params);
6a488035 1982
5c496c74 1983 $result = $this->callAPISuccess('custom_field', 'create', $params);
6a488035
TO
1984
1985 if ($result['is_error'] == 0 && isset($result['id'])) {
1986 CRM_Core_BAO_CustomField::getTableColumnGroup($result['id'], 1);
1987 // force reset of enabled components to help grab custom fields
1988 CRM_Core_Component::getEnabledComponents(1);
1989 return $result;
1990 }
6a488035
TO
1991 }
1992
1993 /**
1994 * Function to delete custom field
1995 *
1996 * @param int $customFieldID
8deefe64
EM
1997 *
1998 * @return array|int
6a488035
TO
1999 */
2000 function customFieldDelete($customFieldID) {
2001
2002 $params['id'] = $customFieldID;
f6722559 2003 return $this->callAPISuccess('custom_field', 'delete', $params);
6a488035
TO
2004 }
2005
2006 /**
2007 * Function to create note
2008 *
2009 * @params array $params name-value pair for an event
2010 *
2a6da8d7 2011 * @param $cId
6a488035
TO
2012 * @return array $note
2013 */
2014 function noteCreate($cId) {
2015 $params = array(
2016 'entity_table' => 'civicrm_contact',
2017 'entity_id' => $cId,
2018 'note' => 'hello I am testing Note',
2019 'contact_id' => $cId,
2020 'modified_date' => date('Ymd'),
2021 'subject' => 'Test Note',
6a488035
TO
2022 );
2023
f6722559 2024 return $this->callAPISuccess('Note', 'create', $params);
6a488035
TO
2025 }
2026
07fd63f5
E
2027 /**
2028 * Enable CiviCampaign Component
2029 */
2030 function enableCiviCampaign() {
2031 CRM_Core_BAO_ConfigSetting::enableComponent('CiviCampaign');
2032 // force reload of config object
2033 $config = CRM_Core_Config::singleton(TRUE, TRUE);
2034 //flush cache by calling with reset
2035 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, TRUE, 'name', TRUE);
2036 }
2037
6a488035
TO
2038 /**
2039 * Create test generated example in api/v3/examples.
2040 * To turn this off (e.g. on the server) set
2041 * define(DONT_DOCUMENT_TEST_CONFIG ,1);
2042 * in your settings file
2043 * @param array $params array as passed to civicrm_api function
2044 * @param array $result array as received from the civicrm_api function
2045 * @param string $function calling function - generally __FUNCTION__
2046 * @param string $filename called from file - generally __FILE__
2047 * @param string $description descriptive text for the example file
2048 * @param string $subfile name for subfile - if this is completed the example will be put in a subfolder (named by the entity)
2049 * @param string $action - optional action - otherwise taken from function name
2050 */
2051 function documentMe($params, $result, $function, $filename, $description = "", $subfile = NULL, $action = NULL) {
2052 if (defined('DONT_DOCUMENT_TEST_CONFIG')) {
2053 return;
2054 }
2055 $entity = substr(basename($filename), 0, strlen(basename($filename)) - 8);
2056 //todo - this is a bit cludgey
2057 if (empty($action)) {
2058 if (strstr($function, 'Create')) {
2059 $action = empty($action) ? 'create' : $action;
2060 $entityAction = 'Create';
2061 }
2062 elseif (strstr($function, 'GetSingle')) {
2063 $action = empty($action) ? 'getsingle' : $action;
2064 $entityAction = 'GetSingle';
2065 }
2066 elseif (strstr($function, 'GetValue')) {
2067 $action = empty($action) ? 'getvalue' : $action;
2068 $entityAction = 'GetValue';
2069 }
2070 elseif (strstr($function, 'GetCount')) {
2071 $action = empty($action) ? 'getcount' : $action;
2072 $entityAction = 'GetCount';
2073 }
5c496c74 2074 elseif (strstr($function, 'GetFields')) {
2075 $action = empty($action) ? 'getfields' : $action;
2076 $entityAction = 'GetFields';
2077 }
76ec9ca7
CW
2078 elseif (strstr($function, 'GetList')) {
2079 $action = empty($action) ? 'getlist' : $action;
2080 $entityAction = 'GetList';
2081 }
6a488035
TO
2082 elseif (strstr($function, 'Get')) {
2083 $action = empty($action) ? 'get' : $action;
2084 $entityAction = 'Get';
2085 }
2086 elseif (strstr($function, 'Delete')) {
2087 $action = empty($action) ? 'delete' : $action;
2088 $entityAction = 'Delete';
2089 }
2090 elseif (strstr($function, 'Update')) {
2091 $action = empty($action) ? 'update' : $action;
2092 $entityAction = 'Update';
2093 }
2094 elseif (strstr($function, 'Subscribe')) {
2095 $action = empty($action) ? 'subscribe' : $action;
2096 $entityAction = 'Subscribe';
2097 }
5c496c74 2098 elseif (strstr($function, 'Submit')) {
2099 $action = empty($action) ? 'submit' : $action;
2100 $entityAction = 'Submit';
6a488035
TO
2101 }
2102 elseif (strstr($function, 'Apply')) {
2103 $action = empty($action) ? 'apply' : $action;
2104 $entityAction = 'Apply';
2105 }
2106 elseif (strstr($function, 'Replace')) {
2107 $action = empty($action) ? 'replace' : $action;
2108 $entityAction = 'Replace';
2109 }
2110 }
2111 else {
2112 $entityAction = ucwords($action);
2113 }
2114
fdd48527 2115 $this->tidyExampleResult($result);
fb32de45 2116 if(isset($params['version'])) {
2117 unset($params['version']);
2118 }
6a488035
TO
2119 // a cleverer person than me would do it in a single regex
2120 if (strstr($entity, 'UF')) {
2121 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)(?<=UF)[A-Z]/', '_$0', $entity));
2122 }
2123 else {
2124 $fnPrefix = strtolower(preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $entity));
2125 }
2126 $smarty = CRM_Core_Smarty::singleton();
2127 $smarty->assign('testfunction', $function);
2128 $function = $fnPrefix . "_" . strtolower($action);
2129 $smarty->assign('function', $function);
2130 $smarty->assign('fnPrefix', $fnPrefix);
2131 $smarty->assign('params', $params);
2132 $smarty->assign('entity', $entity);
2133 $smarty->assign('filename', basename($filename));
2134 $smarty->assign('description', $description);
2135 $smarty->assign('result', $result);
2136
2137 $smarty->assign('action', $action);
2138 if (empty($subfile)) {
3ec6e38d 2139 $subfile = $entityAction;
6a488035 2140 }
3ec6e38d
CW
2141 if (file_exists('../tests/templates/documentFunction.tpl')) {
2142 if (!is_dir("../api/v3/examples/$entity")) {
2143 mkdir("../api/v3/examples/$entity");
6a488035 2144 }
3ec6e38d
CW
2145 $f = fopen("../api/v3/examples/$entity/$subfile.php", "w+b");
2146 fwrite($f, $smarty->fetch('../tests/templates/documentFunction.tpl'));
2147 fclose($f);
6a488035
TO
2148 }
2149 }
2150
fdd48527 2151 /**
2152 * Tidy up examples array so that fields that change often ..don't
2153 * and debug related fields are unset
2a6da8d7
EM
2154 *
2155 * @param $result
2156 *
2157 * @internal param array $params
fdd48527 2158 */
2159 function tidyExampleResult(&$result){
2160 if(!is_array($result)) {
2161 return;
2162 }
2163 $fieldsToChange = array(
2164 'hash' => '67eac7789eaee00',
2165 'modified_date' => '2012-11-14 16:02:35',
f27f2724 2166 'created_date' => '2013-07-28 08:49:19',
fdd48527 2167 'create_date' => '20120130621222105',
f27f2724 2168 'application_received_date' => '20130728084957',
2169 'in_date' => '2013-07-28 08:50:19',
2170 'scheduled_date' => '20130728085413',
2171 'approval_date' => '20130728085413',
2172 'pledge_start_date_high' => '20130726090416',
9f1b81e0 2173 'start_date' => '2013-07-29 00:00:00',
2174 'event_start_date' => '2013-07-29 00:00:00',
2175 'end_date' => '2013-08-04 00:00:00',
2176 'event_end_date' => '2013-08-04 00:00:00',
2177 'decision_date' => '20130805000000',
fdd48527 2178 );
2179
fb32de45 2180 $keysToUnset = array('xdebug', 'undefined_fields',);
fdd48527 2181 foreach ($keysToUnset as $unwantedKey) {
2182 if(isset($result[$unwantedKey])) {
2183 unset($result[$unwantedKey]);
2184 }
2185 }
9f1b81e0 2186 if (isset($result['values'])) {
2187 if(!is_array($result['values'])) {
2188 return;
2189 }
2190 $resultArray = &$result['values'];
2191 }
2192 elseif(is_array($result)) {
2193 $resultArray = &$result;
2194 }
2195 else {
2196 return;
2197 }
fdd48527 2198
9f1b81e0 2199 foreach ($resultArray as $index => &$values) {
f505e36c 2200 if(!is_array($values)) {
2201 continue;
2202 }
fdd48527 2203 foreach($values as $key => &$value) {
2204 if(substr($key, 0, 3) == 'api' && is_array($value)) {
2205 if(isset($value['is_error'])) {
2206 // we have a std nested result format
2207 $this->tidyExampleResult($value);
2208 }
2209 else{
2210 foreach ($value as &$nestedResult) {
2211 // this is an alternative syntax for nested results a keyed array of results
2212 $this->tidyExampleResult($nestedResult);
2213 }
2214 }
2215 }
2216 if(in_array($key, $keysToUnset)) {
2217 unset($values[$key]);
b25fe59a 2218 break;
fdd48527 2219 }
9f1b81e0 2220 if(array_key_exists($key, $fieldsToChange) && !empty($value)) {
fdd48527 2221 $value = $fieldsToChange[$key];
2222 }
b25fe59a
E
2223 if(is_string($value)) {
2224 $value = addslashes($value);
2225 }
fdd48527 2226 }
fdd48527 2227 }
2228 }
2229
6a488035
TO
2230 /**
2231 * Function to delete note
2232 *
2233 * @params int $noteID
2234 *
2235 */
2236 function noteDelete($params) {
f6722559 2237 return $this->callAPISuccess('Note', 'delete', $params);
6a488035
TO
2238 }
2239
2240 /**
2241 * Function to create custom field with Option Values
2242 *
77b97be7
EM
2243 * @param array $customGroup
2244 * @param string $name name of custom field
2245 *
2246 * @return array|int
6a488035
TO
2247 */
2248 function customFieldOptionValueCreate($customGroup, $name) {
2249 $fieldParams = array(
2250 'custom_group_id' => $customGroup['id'],
2251 'name' => 'test_custom_group',
2252 'label' => 'Country',
2253 'html_type' => 'Select',
2254 'data_type' => 'String',
2255 'weight' => 4,
2256 'is_required' => 1,
2257 'is_searchable' => 0,
2258 'is_active' => 1,
6a488035
TO
2259 );
2260
2261 $optionGroup = array(
2262 'domain_id' => 1,
2263 'name' => 'option_group1',
2264 'label' => 'option_group_label1',
2265 );
2266
2267 $optionValue = array(
2268 'option_label' => array('Label1', 'Label2'),
2269 'option_value' => array('value1', 'value2'),
2270 'option_name' => array($name . '_1', $name . '_2'),
2271 'option_weight' => array(1, 2),
2272 'option_status' => 1,
2273 );
2274
2275 $params = array_merge($fieldParams, $optionGroup, $optionValue);
2276
f6722559 2277 return $this->callAPISuccess('custom_field', 'create', $params);
6a488035
TO
2278 }
2279
4cbe18b8
EM
2280 /**
2281 * @param $entities
2282 *
2283 * @return bool
2284 */
6a488035
TO
2285 function confirmEntitiesDeleted($entities) {
2286 foreach ($entities as $entity) {
2287
f6722559 2288 $result = $this->callAPISuccess($entity, 'Get', array());
6a488035
TO
2289 if ($result['error'] == 1 || $result['count'] > 0) {
2290 // > than $entity[0] to allow a value to be passed in? e.g. domain?
2291 return TRUE;
2292 }
2293 }
2294 }
2295
4cbe18b8
EM
2296 /**
2297 * @param $tablesToTruncate
2298 * @param bool $dropCustomValueTables
2299 */
6a488035
TO
2300 function quickCleanup($tablesToTruncate, $dropCustomValueTables = FALSE) {
2301 if ($dropCustomValueTables) {
2302 $tablesToTruncate[] = 'civicrm_custom_group';
2303 $tablesToTruncate[] = 'civicrm_custom_field';
2304 }
2305
0b6f58fa
ARW
2306 $tablesToTruncate = array_unique(array_merge($this->_tablesToTruncate, $tablesToTruncate));
2307
6a488035
TO
2308 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 0;");
2309 foreach ($tablesToTruncate as $table) {
2310 $sql = "TRUNCATE TABLE $table";
2311 CRM_Core_DAO::executeQuery($sql);
2312 }
2313 CRM_Core_DAO::executeQuery("SET FOREIGN_KEY_CHECKS = 1;");
2314
2315 if ($dropCustomValueTables) {
2316 $dbName = self::getDBName();
2317 $query = "
2318SELECT TABLE_NAME as tableName
2319FROM INFORMATION_SCHEMA.TABLES
2320WHERE TABLE_SCHEMA = '{$dbName}'
2321AND ( TABLE_NAME LIKE 'civicrm_value_%' )
2322";
2323
2324 $tableDAO = CRM_Core_DAO::executeQuery($query);
2325 while ($tableDAO->fetch()) {
2326 $sql = "DROP TABLE {$tableDAO->tableName}";
2327 CRM_Core_DAO::executeQuery($sql);
2328 }
2329 }
2330 }
2331
b38530f2
EM
2332 /**
2333 * Clean up financial entities after financial tests (so we remember to get all the tables :-))
2334 */
2335 function quickCleanUpFinancialEntities() {
2336 $tablesToTruncate = array(
2337 'civicrm_contribution',
2338 'civicrm_financial_trxn',
2339 'civicrm_contribution_recur',
2340 'civicrm_line_item',
2341 'civicrm_contribution_page',
2342 'civicrm_payment_processor',
2343 'civicrm_entity_financial_trxn',
2344 'civicrm_membership',
2345 'civicrm_membership_type',
2346 'civicrm_membership_payment',
cab024d4 2347 'civicrm_membership_log',
b38530f2
EM
2348 'civicrm_membership_status',
2349 'civicrm_event',
2350 'civicrm_participant',
2351 'civicrm_participant_payment',
2352 'civicrm_pledge',
2353 );
2354 $this->quickCleanup($tablesToTruncate);
2355 }
6a488035
TO
2356 /*
2357 * Function does a 'Get' on the entity & compares the fields in the Params with those returned
2358 * Default behaviour is to also delete the entity
2359 * @param array $params params array to check agains
2360 * @param int $id id of the entity concerned
2361 * @param string $entity name of entity concerned (e.g. membership)
2362 * @param bool $delete should the entity be deleted as part of this check
2363 * @param string $errorText text to print on error
2364 *
2365 */
4cbe18b8
EM
2366 /**
2367 * @param $params
2368 * @param $id
2369 * @param $entity
2370 * @param int $delete
2371 * @param string $errorText
2372 *
2373 * @throws Exception
2374 */
6a488035
TO
2375 function getAndCheck($params, $id, $entity, $delete = 1, $errorText = '') {
2376
f6722559 2377 $result = $this->callAPISuccessGetSingle($entity, array(
6a488035 2378 'id' => $id,
6a488035
TO
2379 ));
2380
2381 if ($delete) {
f6722559 2382 $this->callAPISuccess($entity, 'Delete', array(
6a488035 2383 'id' => $id,
6a488035
TO
2384 ));
2385 }
b0aaad8c 2386 $dateFields = $keys = $dateTimeFields = array();
f6722559 2387 $fields = $this->callAPISuccess($entity, 'getfields', array('version' => 3, 'action' => 'get'));
6a488035
TO
2388 foreach ($fields['values'] as $field => $settings) {
2389 if (array_key_exists($field, $result)) {
2390 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = $field;
2391 }
2392 else {
2393 $keys[CRM_Utils_Array::Value('name', $settings, $field)] = CRM_Utils_Array::value('name', $settings, $field);
2394 }
afd404ea 2395 $type = CRM_Utils_Array::value('type', $settings);
2396 if ($type == CRM_Utils_Type::T_DATE) {
2397 $dateFields[] = $settings['name'];
2398 // we should identify both real names & unique names as dates
2399 if($field != $settings['name']) {
2400 $dateFields[] = $field;
2401 }
2402 }
2403 if($type == CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME) {
2404 $dateTimeFields[] = $settings['name'];
2405 // we should identify both real names & unique names as dates
2406 if($field != $settings['name']) {
2407 $dateTimeFields[] = $field;
2408 }
6a488035
TO
2409 }
2410 }
2411
2412 if (strtolower($entity) == 'contribution') {
2413 $params['receive_date'] = date('Y-m-d', strtotime($params['receive_date']));
2414 // this is not returned in id format
2415 unset($params['payment_instrument_id']);
2416 $params['contribution_source'] = $params['source'];
2417 unset($params['source']);
2418 }
2419
2420 foreach ($params as $key => $value) {
afd404ea 2421 if ($key == 'version' || substr($key, 0, 3) == 'api' || !array_key_exists($keys[$key], $result)) {
6a488035
TO
2422 continue;
2423 }
2424 if (in_array($key, $dateFields)) {
2425 $value = date('Y-m-d', strtotime($value));
2426 $result[$key] = date('Y-m-d', strtotime($result[$key]));
2427 }
afd404ea 2428 if (in_array($key, $dateTimeFields)) {
2429 $value = date('Y-m-d H:i:s', strtotime($value));
a72cec08 2430 $result[$keys[$key]] = date('Y-m-d H:i:s', strtotime(CRM_Utils_Array::value($keys[$key], $result, CRM_Utils_Array::value($key, $result))));
afd404ea 2431 }
2432 $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);
6a488035
TO
2433 }
2434 }
2435
2436 /**
2437 * Function to get formatted values in the actual and expected result
2438 * @param array $actual actual calculated values
2439 * @param array $expected expected values
2440 *
2441 */
2442 function checkArrayEquals(&$actual, &$expected) {
2443 self::unsetId($actual);
2444 self::unsetId($expected);
2445 $this->assertEquals($actual, $expected);
2446 }
2447
2448 /**
2449 * Function to unset the key 'id' from the array
2450 * @param array $unformattedArray The array from which the 'id' has to be unset
2451 *
2452 */
2453 static function unsetId(&$unformattedArray) {
2454 $formattedArray = array();
2455 if (array_key_exists('id', $unformattedArray)) {
2456 unset($unformattedArray['id']);
2457 }
a7488080 2458 if (!empty($unformattedArray['values']) && is_array($unformattedArray['values'])) {
6a488035
TO
2459 foreach ($unformattedArray['values'] as $key => $value) {
2460 if (is_Array($value)) {
2461 foreach ($value as $k => $v) {
2462 if ($k == 'id') {
2463 unset($value[$k]);
2464 }
2465 }
2466 }
2467 elseif ($key == 'id') {
2468 $unformattedArray[$key];
2469 }
2470 $formattedArray = array($value);
2471 }
2472 $unformattedArray['values'] = $formattedArray;
2473 }
2474 }
2475
2476 /**
2477 * Helper to enable/disable custom directory support
2478 *
2479 * @param array $customDirs with members:
2480 * 'php_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2481 * 'template_path' Set to TRUE to use the default, FALSE or "" to disable support, or a string path to use another path
2482 */
2483 function customDirectories($customDirs) {
2484 require_once 'CRM/Core/Config.php';
2485 $config = CRM_Core_Config::singleton();
2486
2487 if (empty($customDirs['php_path']) || $customDirs['php_path'] === FALSE) {
2488 unset($config->customPHPPathDir);
2489 }
2490 elseif ($customDirs['php_path'] === TRUE) {
2491 $config->customPHPPathDir = dirname(dirname(__FILE__)) . '/custom_directories/php/';
2492 }
2493 else {
2494 $config->customPHPPathDir = $php_path;
2495 }
2496
2497 if (empty($customDirs['template_path']) || $customDirs['template_path'] === FALSE) {
2498 unset($config->customTemplateDir);
2499 }
2500 elseif ($customDirs['template_path'] === TRUE) {
2501 $config->customTemplateDir = dirname(dirname(__FILE__)) . '/custom_directories/templates/';
2502 }
2503 else {
2504 $config->customTemplateDir = $template_path;
2505 }
2506 }
2507
2508 /**
2509 * Generate a temporary folder
2510 *
2a6da8d7
EM
2511 * @param string $prefix
2512 * @return string $string
6a488035
TO
2513 */
2514 function createTempDir($prefix = 'test-') {
2515 $tempDir = CRM_Utils_File::tempdir($prefix);
2516 $this->tempDirs[] = $tempDir;
2517 return $tempDir;
2518 }
2519
2520 function cleanTempDirs() {
2521 if (!is_array($this->tempDirs)) {
2522 // fix test errors where this is not set
2523 return;
2524 }
2525 foreach ($this->tempDirs as $tempDir) {
2526 if (is_dir($tempDir)) {
2527 CRM_Utils_File::cleanDir($tempDir, TRUE, FALSE);
2528 }
2529 }
2530 }
2531
2532 /**
2533 * Temporarily replace the singleton extension with a different one
2534 */
2535 function setExtensionSystem(CRM_Extension_System $system) {
2536 if ($this->origExtensionSystem == NULL) {
2537 $this->origExtensionSystem = CRM_Extension_System::singleton();
2538 }
2539 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2540 }
2541
2542 function unsetExtensionSystem() {
2543 if ($this->origExtensionSystem !== NULL) {
2544 CRM_Extension_System::setSingleton($this->origExtensionSystem);
2545 $this->origExtensionSystem = NULL;
2546 }
2547 }
f17d75bb 2548
076d8c82
TO
2549 /**
2550 * Temporarily alter the settings-metadata to add a mock setting.
2551 *
2552 * WARNING: The setting metadata will disappear on the next cache-clear.
2553 *
2554 * @param $extras
2555 * @return void
2556 */
2557 function setMockSettingsMetaData($extras) {
2558 CRM_Core_BAO_Setting::$_cache = array();
2559 $this->callAPISuccess('system','flush', array());
2560 CRM_Core_BAO_Setting::$_cache = array();
2561
2562 CRM_Utils_Hook::singleton()->setHook('civicrm_alterSettingsMetaData', function (&$metadata, $domainId, $profile) use ($extras) {
2563 $metadata = array_merge($metadata, $extras);
2564 });
2565
2566 $fields = $this->callAPISuccess('setting', 'getfields', array());
2567 foreach ($extras as $key => $spec) {
2568 $this->assertNotEmpty($spec['title']);
2569 $this->assertEquals($spec['title'], $fields['values'][$key]['title']);
2570 }
2571 }
2572
4cbe18b8
EM
2573 /**
2574 * @param $name
2575 */
f17d75bb
PN
2576 function financialAccountDelete($name) {
2577 $financialAccount = new CRM_Financial_DAO_FinancialAccount();
2578 $financialAccount->name = $name;
2579 if($financialAccount->find(TRUE)) {
2580 $entityFinancialType = new CRM_Financial_DAO_EntityFinancialAccount();
2581 $entityFinancialType->financial_account_id = $financialAccount->id;
2582 $entityFinancialType->delete();
2583 $financialAccount->delete();
2584 }
2585 }
fb32de45 2586
2587 /**
2588 * Use $ids as an instruction to do test cleanup
2589 */
2590 function deleteFromIDSArray() {
2591 foreach ($this->ids as $entity => $ids) {
2592 foreach ($ids as $id) {
2593 $this->callAPISuccess($entity, 'delete', array('id' => $id));
2594 }
2595 }
2596 }
5c2e58ae 2597
2b7d3f8a 2598 /**
2599 * FIXME: something NULLs $GLOBALS['_HTML_QuickForm_registered_rules'] when the tests are ran all together
2600 * (NB unclear if this is still required)
2601 */
2602 function _sethtmlGlobals() {
2603 $GLOBALS['_HTML_QuickForm_registered_rules'] = array(
2604 'required' => array(
2605 'html_quickform_rule_required',
2606 'HTML/QuickForm/Rule/Required.php'
2607 ),
2608 'maxlength' => array(
2609 'html_quickform_rule_range',
2610 'HTML/QuickForm/Rule/Range.php'
2611 ),
2612 'minlength' => array(
2613 'html_quickform_rule_range',
2614 'HTML/QuickForm/Rule/Range.php'
2615 ),
2616 'rangelength' => array(
2617 'html_quickform_rule_range',
2618 'HTML/QuickForm/Rule/Range.php'
2619 ),
2620 'email' => array(
2621 'html_quickform_rule_email',
2622 'HTML/QuickForm/Rule/Email.php'
2623 ),
2624 'regex' => array(
2625 'html_quickform_rule_regex',
2626 'HTML/QuickForm/Rule/Regex.php'
2627 ),
2628 'lettersonly' => array(
2629 'html_quickform_rule_regex',
2630 'HTML/QuickForm/Rule/Regex.php'
2631 ),
2632 'alphanumeric' => array(
2633 'html_quickform_rule_regex',
2634 'HTML/QuickForm/Rule/Regex.php'
2635 ),
2636 'numeric' => array(
2637 'html_quickform_rule_regex',
2638 'HTML/QuickForm/Rule/Regex.php'
2639 ),
2640 'nopunctuation' => array(
2641 'html_quickform_rule_regex',
2642 'HTML/QuickForm/Rule/Regex.php'
2643 ),
2644 'nonzero' => array(
2645 'html_quickform_rule_regex',
2646 'HTML/QuickForm/Rule/Regex.php'
2647 ),
2648 'callback' => array(
2649 'html_quickform_rule_callback',
2650 'HTML/QuickForm/Rule/Callback.php'
2651 ),
2652 'compare' => array(
2653 'html_quickform_rule_compare',
2654 'HTML/QuickForm/Rule/Compare.php'
2655 )
2656 );
2657 // FIXME: …ditto for $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']
2658 $GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES'] = array(
2659 'group' => array(
2660 'HTML/QuickForm/group.php',
2661 'HTML_QuickForm_group'
2662 ),
2663 'hidden' => array(
2664 'HTML/QuickForm/hidden.php',
2665 'HTML_QuickForm_hidden'
2666 ),
2667 'reset' => array(
2668 'HTML/QuickForm/reset.php',
2669 'HTML_QuickForm_reset'
2670 ),
2671 'checkbox' => array(
2672 'HTML/QuickForm/checkbox.php',
2673 'HTML_QuickForm_checkbox'
2674 ),
2675 'file' => array(
2676 'HTML/QuickForm/file.php',
2677 'HTML_QuickForm_file'
2678 ),
2679 'image' => array(
2680 'HTML/QuickForm/image.php',
2681 'HTML_QuickForm_image'
2682 ),
2683 'password' => array(
2684 'HTML/QuickForm/password.php',
2685 'HTML_QuickForm_password'
2686 ),
2687 'radio' => array(
2688 'HTML/QuickForm/radio.php',
2689 'HTML_QuickForm_radio'
2690 ),
2691 'button' => array(
2692 'HTML/QuickForm/button.php',
2693 'HTML_QuickForm_button'
2694 ),
2695 'submit' => array(
2696 'HTML/QuickForm/submit.php',
2697 'HTML_QuickForm_submit'
2698 ),
2699 'select' => array(
2700 'HTML/QuickForm/select.php',
2701 'HTML_QuickForm_select'
2702 ),
2703 'hiddenselect' => array(
2704 'HTML/QuickForm/hiddenselect.php',
2705 'HTML_QuickForm_hiddenselect'
2706 ),
2707 'text' => array(
2708 'HTML/QuickForm/text.php',
2709 'HTML_QuickForm_text'
2710 ),
2711 'textarea' => array(
2712 'HTML/QuickForm/textarea.php',
2713 'HTML_QuickForm_textarea'
2714 ),
2715 'fckeditor' => array(
2716 'HTML/QuickForm/fckeditor.php',
2717 'HTML_QuickForm_FCKEditor'
2718 ),
2719 'tinymce' => array(
2720 'HTML/QuickForm/tinymce.php',
2721 'HTML_QuickForm_TinyMCE'
2722 ),
2723 'dojoeditor' => array(
2724 'HTML/QuickForm/dojoeditor.php',
2725 'HTML_QuickForm_dojoeditor'
2726 ),
2727 'link' => array(
2728 'HTML/QuickForm/link.php',
2729 'HTML_QuickForm_link'
2730 ),
2731 'advcheckbox' => array(
2732 'HTML/QuickForm/advcheckbox.php',
2733 'HTML_QuickForm_advcheckbox'
2734 ),
2735 'date' => array(
2736 'HTML/QuickForm/date.php',
2737 'HTML_QuickForm_date'
2738 ),
2739 'static' => array(
2740 'HTML/QuickForm/static.php',
2741 'HTML_QuickForm_static'
2742 ),
2743 'header' => array(
2744 'HTML/QuickForm/header.php',
2745 'HTML_QuickForm_header'
2746 ),
2747 'html' => array(
2748 'HTML/QuickForm/html.php',
2749 'HTML_QuickForm_html'
2750 ),
2751 'hierselect' => array(
2752 'HTML/QuickForm/hierselect.php',
2753 'HTML_QuickForm_hierselect'
2754 ),
2755 'autocomplete' => array(
2756 'HTML/QuickForm/autocomplete.php',
2757 'HTML_QuickForm_autocomplete'
2758 ),
2759 'xbutton' => array(
2760 'HTML/QuickForm/xbutton.php',
2761 'HTML_QuickForm_xbutton'
2762 ),
2763 'advmultiselect' => array(
2764 'HTML/QuickForm/advmultiselect.php',
2765 'HTML_QuickForm_advmultiselect'
2766 )
2767 );
2768 }
2769
48e399ac
EM
2770 /**
2771 * Set up an acl allowing contact to see 2 specified groups
2772 * - $this->_permissionedGroup & $this->_permissionedDisbaledGroup
2773 *
2774 * You need to have precreated these groups & created the user e.g
2775 * $this->createLoggedInUser();
2776 * $this->_permissionedDisabledGroup = $this->groupCreate(array('title' => 'pick-me-disabled', 'is_active' => 0, 'name' => 'pick-me-disabled'));
2777 * $this->_permissionedGroup = $this->groupCreate(array('title' => 'pick-me-active', 'is_active' => 1, 'name' => 'pick-me-active'));
2778 *
2779 */
2780 function setupACL() {
aaac0e0b
EM
2781 global $_REQUEST;
2782 $_REQUEST = $this->_params;
48e399ac
EM
2783 CRM_Core_Config::singleton()->userPermissionClass->permissions = array('access CiviCRM');
2784 $optionGroupID = $this->callAPISuccessGetValue('option_group', array('return' => 'id', 'name' => 'acl_role'));
2785 $optionValue = $this->callAPISuccess('option_value', 'create', array('option_group_id' => $optionGroupID,
2786 'label' => 'pick me',
2787 'value' => 55,
2788 ));
2789
2790
2791 CRM_Core_DAO::executeQuery("
2792 TRUNCATE civicrm_acl_cache
2793 ");
2794
2795 CRM_Core_DAO::executeQuery("
2796 TRUNCATE civicrm_acl_contact_cache
2797 ");
2798
2799
2800 CRM_Core_DAO::executeQuery("
2801 INSERT INTO civicrm_acl_entity_role (
2802 `acl_role_id`, `entity_table`, `entity_id`
2803 ) VALUES (55, 'civicrm_group', {$this->_permissionedGroup});
2804 ");
2805
2806 CRM_Core_DAO::executeQuery("
2807 INSERT INTO civicrm_acl (
2808 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2809 )
2810 VALUES (
2811 'view picked', 'civicrm_group', $this->_permissionedGroup , 'Edit', 'civicrm_saved_search', {$this->_permissionedGroup}, 1
2812 );
2813 ");
2814
2815 CRM_Core_DAO::executeQuery("
2816 INSERT INTO civicrm_acl (
2817 `name`, `entity_table`, `entity_id`, `operation`, `object_table`, `object_id`, `is_active`
2818 )
2819 VALUES (
2820 'view picked', 'civicrm_group', $this->_permissionedGroup, 'Edit', 'civicrm_saved_search', {$this->_permissionedDisabledGroup}, 1
2821 );
2822 ");
2823 $this->_loggedInUser = CRM_Core_Session::singleton()->get('userID');
2824 $this->callAPISuccess('group_contact', 'create', array(
2825 'group_id' => $this->_permissionedGroup,
2826 'contact_id' => $this->_loggedInUser,
2827 ));
2828 //flush cache
2829 CRM_ACL_BAO_Cache::resetCache();
aaac0e0b
EM
2830 CRM_Contact_BAO_Group::getPermissionClause(TRUE);
2831 CRM_ACL_API::groupPermission('whatever', 9999, NULL, 'civicrm_saved_search', NULL, NULL, TRUE);
48e399ac
EM
2832 }
2833
cab024d4
EM
2834 /**
2835 * alter default price set so that the field numbers are not all 1 (hiding errors)
2836 */
2837 function offsetDefaultPriceSet() {
2838 $contributionPriceSet = $this->callAPISuccess('price_set', 'getsingle', array('name' => 'default_contribution_amount'));
2839 $firstID = $contributionPriceSet['id'];
2840 $this->callAPISuccess('price_set', 'create', array('id' => $contributionPriceSet['id'], 'is_active' => 0, 'name' => 'old'));
2841 unset($contributionPriceSet['id']);
2842 $newPriceSet = $this->callAPISuccess('price_set', 'create', $contributionPriceSet);
2843 $priceField = $this->callAPISuccess('price_field', 'getsingle', array('price_set_id' => $firstID, 'options' => array('limit' => 1)));
2844 unset($priceField['id']);
2845 $priceField['price_set_id'] = $newPriceSet['id'];
2846 $newPriceField = $this->callAPISuccess('price_field', 'create', $priceField);
2847 $priceFieldValue = $this->callAPISuccess('price_field_value', 'getsingle', array('price_set_id' => $firstID, 'sequential' => 1, 'options' => array('limit' => 1)));
2848
2849 unset($priceFieldValue['id']);
2850 //create some padding to use up ids
2851 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2852 $this->callAPISuccess('price_field_value', 'create', $priceFieldValue);
2853 $this->callAPISuccess('price_field_value', 'create', array_merge($priceFieldValue, array('price_field_id' => $newPriceField['id'])));
2854
2855 }
2856
a86d27fc 2857/**
2858 * Create an instance of the paypal processor
2859 * @todo this isn't a great place to put it - but really it belongs on a class that extends
2860 * this parent class & we don't have a structure for that yet
2861 * There is another function to this effect on the PaypalPro test but it appears to be silently failing
2862 * & the best protection agains that is the functions this class affords
2863 */
2864 function paymentProcessorCreate($params = array()) {
2865 $params = array_merge(array(
2866 'name' => 'demo',
2867 'domain_id' => CRM_Core_Config::domainID(),
2868 'payment_processor_type_id' => 'PayPal',
2869 'is_active' => 1,
2870 'is_default' => 0,
2871 'is_test' => 1,
2872 'user_name' => 'sunil._1183377782_biz_api1.webaccess.co.in',
2873 'password' => '1183377788',
2874 'signature' => 'APixCoQ-Zsaj-u3IH7mD5Do-7HUqA9loGnLSzsZga9Zr-aNmaJa3WGPH',
2875 'url_site' => 'https://www.sandbox.paypal.com/',
2876 'url_api' => 'https://api-3t.sandbox.paypal.com/',
2877 'url_button' => 'https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif',
2878 'class_name' => 'Payment_PayPalImpl',
2879 'billing_mode' => 3,
2880 'financial_type_id' => 1,
2881 ),
2882 $params);
2883 if(!is_numeric($params['payment_processor_type_id'])) {
2884 // really the api should handle this through getoptions but it's not exactly api call so lets just sort it
2885 //here
2886 $params['payment_processor_type_id'] = $this->callAPISuccess('payment_processor_type', 'getvalue', array(
2887 'name' => $params['payment_processor_type_id'],
2888 'return' => 'id',
2889 ), 'integer');
2890 }
2891 $result = $this->callAPISuccess('payment_processor', 'create', $params);
2892 return $result['id'];
2893 }
2894
6a488035 2895
4cbe18b8
EM
2896 /**
2897 * @param $message
2898 *
2899 * @throws Exception
2900 */function CiviUnitTestCase_fatalErrorHandler($message) {
6a488035
TO
2901 throw new Exception("{$message['message']}: {$message['code']}");
2902}
a86d27fc 2903}