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