2 /*********************************************************************************
3 * SugarCRM Community Edition is a customer relationship management program developed by
4 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
6 * This program is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU Affero General Public License version 3 as published by the
8 * Free Software Foundation with the addition of the following permission added
9 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
18 * You should have received a copy of the GNU Affero General Public License along with
19 * this program; if not, see http://www.gnu.org/licenses or write to the Free
20 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26 * The interactive user interfaces in modified source and object code versions
27 * of this program must display Appropriate Legal Notices, as required under
28 * Section 5 of the GNU Affero General Public License version 3.
30 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31 * these Appropriate Legal Notices must retain the display of the "Powered by
32 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33 * technical reasons, the Appropriate Legal Notices must display the words
34 * "Powered by SugarCRM".
35 ********************************************************************************/
38 if(!defined('sugarEntry')) define('sugarEntry', true);
41 dirname(__FILE__) . PATH_SEPARATOR .
42 dirname(__FILE__) . '/..' . PATH_SEPARATOR .
46 // constant to indicate that we are running tests
47 if (!defined('SUGAR_PHPUNIT_RUNNER'))
48 define('SUGAR_PHPUNIT_RUNNER', true);
50 // initialize the various globals we use
51 global $sugar_config, $db, $fileName, $current_user, $locale, $current_language;
53 if ( !isset($_SERVER['HTTP_USER_AGENT']) )
54 // we are probably running tests from the command line
55 $_SERVER['HTTP_USER_AGENT'] = 'cli';
57 // move current working directory
58 chdir(dirname(__FILE__) . '/..');
60 require_once('include/entryPoint.php');
62 require_once('include/utils/layout_utils.php');
64 $GLOBALS['db'] = DBManagerFactory::getInstance();
66 $current_language = $sugar_config['default_language'];
67 // disable the SugarLogger
68 $sugar_config['logger']['level'] = 'fatal';
70 $GLOBALS['sugar_config']['default_permissions'] = array (
77 $GLOBALS['js_version_key'] = 'testrunner';
79 if ( !isset($_SERVER['SERVER_SOFTWARE']) )
80 $_SERVER["SERVER_SOFTWARE"] = 'PHPUnit';
82 // helps silence the license checking when running unit tests.
83 $_SESSION['VALIDATION_EXPIRES_IN'] = 'valid';
85 $GLOBALS['startTime'] = microtime(true);
87 // clean out the cache directory
88 require_once('modules/Administration/QuickRepairAndRebuild.php');
89 $repair = new RepairAndClear();
90 $repair->module_list = array();
91 $repair->show_output = false;
92 $repair->clearJsLangFiles();
93 $repair->clearJsFiles();
95 // mark that we got by the admin wizard already
96 $focus = new Administration();
97 $focus->retrieveSettings();
98 $focus->saveSetting('system','adminwizard',1);
100 // include the other test tools
101 require_once 'SugarTestObjectUtilities.php';
102 require_once 'SugarTestProjectUtilities.php';
103 require_once 'SugarTestProjectTaskUtilities.php';
104 require_once 'SugarTestUserUtilities.php';
105 require_once 'SugarTestLangPackCreator.php';
106 require_once 'SugarTestThemeUtilities.php';
107 require_once 'SugarTestContactUtilities.php';
108 require_once 'SugarTestEmailUtilities.php';
109 require_once 'SugarTestCampaignUtilities.php';
110 require_once 'SugarTestLeadUtilities.php';
111 require_once 'SugarTestStudioUtilities.php';
112 require_once 'SugarTestMeetingUtilities.php';
113 require_once 'SugarTestCallUtilities.php';
114 require_once 'SugarTestAccountUtilities.php';
115 require_once 'SugarTestTrackerUtility.php';
116 require_once 'SugarTestImportUtilities.php';
117 require_once 'SugarTestMergeUtilities.php';
118 require_once 'SugarTestTaskUtilities.php';
119 require_once 'SugarTestOpportunityUtilities.php';
120 require_once 'SugarTestRelationshipUtilities.php';
121 require_once 'SugarTestSugarEmailAddressUtilities.php';
123 $GLOBALS['db']->commit();
125 // define our testcase subclass
126 class Sugar_PHPUnit_Framework_TestCase extends PHPUnit_Framework_TestCase
128 protected $backupGlobals = FALSE;
130 protected $useOutputBuffering = true;
132 protected function assertPreConditions()
134 if(isset($GLOBALS['log'])) {
135 $GLOBALS['log']->info("START TEST: {$this->getName(false)}");
137 SugarCache::instance()->flush();
140 protected function assertPostConditions() {
141 if(!empty($_REQUEST)) {
142 foreach(array_keys($_REQUEST) as $k) {
143 unset($_REQUEST[$k]);
148 foreach(array_keys($_POST) as $k) {
154 foreach(array_keys($_GET) as $k) {
158 if(isset($GLOBALS['log'])) {
159 $GLOBALS['log']->info("DONE TEST: {$this->getName(false)}");
161 // reset error handler in case somebody set it
162 restore_error_handler();
165 public static function tearDownAfterClass()
167 unset($GLOBALS['disable_date_format']);
168 unset($GLOBALS['saving_relationships']);
169 unset($GLOBALS['updating_relationships']);
170 $GLOBALS['timedate']->clearCache();
174 // define output testcase subclass
175 class Sugar_PHPUnit_Framework_OutputTestCase extends PHPUnit_Extensions_OutputTestCase
177 protected $backupGlobals = FALSE;
179 protected $_notRegex;
180 protected $_outputCheck;
182 protected function assertPreConditions()
184 if(isset($GLOBALS['log'])) {
185 $GLOBALS['log']->info("START TEST: {$this->getName(false)}");
187 SugarCache::instance()->flush();
190 protected function assertPostConditions() {
191 if(!empty($_REQUEST)) {
192 foreach(array_keys($_REQUEST) as $k) {
193 unset($_REQUEST[$k]);
198 foreach(array_keys($_POST) as $k) {
204 foreach(array_keys($_GET) as $k) {
208 if(isset($GLOBALS['log'])) {
209 $GLOBALS['log']->info("DONE TEST: {$this->getName(false)}");
213 protected function NotRegexCallback($output)
215 if(empty($this->_notRegex)) {
218 $this->assertNotRegExp($this->_notRegex, $output);
222 public function setOutputCheck($callback)
224 if (!is_callable($callback)) {
225 throw new PHPUnit_Framework_Exception;
228 $this->_outputCheck = $callback;
231 protected function runTest()
233 $testResult = parent::runTest();
234 if($this->_outputCheck) {
235 $this->assertTrue(call_user_func($this->_outputCheck, $this->output));
240 public function expectOutputNotRegex($expectedRegex)
242 if (is_string($expectedRegex) || is_null($expectedRegex)) {
243 $this->_notRegex = $expectedRegex;
246 $this->setOutputCheck(array($this, "NotRegexCallback"));
251 // define a mock logger interface; used for capturing logging messages emited
253 class SugarMockLogger
255 private $_messages = array();
257 public function __call($method, $message)
259 $this->messages[] = strtoupper($method) . ': ' . $message[0];
262 public function getLastMessage()
264 return end($this->messages);
267 public function getMessageCount()
269 return count($this->messages);
273 require_once('ModuleInstall/ModuleInstaller.php');
276 * Own exception for SugarTestHelper class
278 * @author mgusev@sugarcrm.com
280 class SugarTestHelperException extends PHPUnit_Framework_Exception
286 * Helper for initialization of global variables of SugarCRM
288 * @author mgusev@sugarcrm.com
290 class SugarTestHelper
293 * @var array array of registered vars. It allows helper to unregister them on tearDown
295 protected static $registeredVars = array();
298 * @var array array of global vars. They are storing on init one time and restoring in global scope each tearDown
300 protected static $initVars = array(
305 * @var array of system preference of SugarCRM as theme etc. They are storing on init one time and restoring each tearDown
307 protected static $systemVars = array();
310 * @var array of modules which we should refresh on tearDown.
312 protected static $cleanModules = array();
315 * @var bool is SugarTestHelper inited or not. Just to skip initialization on the second and others call of init method
317 protected static $isInited = false;
320 * All methods are static because of it we disable constructor
322 private function __construct()
327 * All methods are static because of it we disable clone
329 private function __clone()
334 * Initialization of main variables of SugarCRM in global scope
338 public static function init()
340 if (self::$isInited == true)
345 // initialization & backup of sugar_config
346 self::$initVars['GLOBALS']['sugar_config'] = null;
347 if ($GLOBALS['sugar_config'])
349 self::$initVars['GLOBALS']['sugar_config'] = $GLOBALS['sugar_config'];
351 if (self::$initVars['GLOBALS']['sugar_config'] == false)
353 global $sugar_config;
354 if (is_file('config.php'))
356 require_once('config.php');
358 if (is_file('config_override.php'))
360 require_once('config_override.php');
362 self::$initVars['GLOBALS']['sugar_config'] = $GLOBALS['sugar_config'];
365 // backup of current_language
366 self::$initVars['GLOBALS']['current_language'] = 'en_us';
367 if (isset($sugar_config['current_language']))
369 self::$initVars['GLOBALS']['current_language'] = $sugar_config['current_language'];
371 if (isset($GLOBALS['current_language']))
373 self::$initVars['GLOBALS']['current_language'] = $GLOBALS['current_language'];
375 $GLOBALS['current_language'] = self::$initVars['GLOBALS']['current_language'];
377 // backup of reload_vardefs
378 self::$initVars['GLOBALS']['reload_vardefs'] = null;
379 if (isset($GLOBALS['reload_vardefs']))
381 self::$initVars['GLOBALS']['reload_vardefs'] = $GLOBALS['reload_vardefs'];
385 self::$initVars['GLOBALS']['locale'] = null;
386 if (isset($GLOBALS['locale']))
388 self::$initVars['GLOBALS']['locale'] = $GLOBALS['locale'];
390 if (self::$initVars['GLOBALS']['locale'] == false)
392 self::$initVars['GLOBALS']['locale'] = new Localization();
395 // backup of service_object
396 self::$initVars['GLOBALS']['service_object'] = null;
397 if (isset($GLOBALS['service_object']))
399 self::$initVars['GLOBALS']['service_object'] = $GLOBALS['service_object'];
402 // backup of SugarThemeRegistry
403 self::$systemVars['SugarThemeRegistry'] = SugarThemeRegistry::current();
405 self::$isInited = true;
409 * Checking is there helper for variable or not
412 * @param string $varName name of global variable of SugarCRM
413 * @return bool is there helper for a variable or not
414 * @throws SugarTestHelperException fired when there is no implementation of helper for a variable
416 protected static function checkHelper($varName)
418 if (method_exists(__CLASS__, 'setUp_' . $varName) == false)
420 throw new SugarTestHelperException('setUp for $' . $varName . ' is not implemented. ' . __CLASS__ . '::setUp_' . $varName);
425 * Entry point for setup of global variable
428 * @param string $varName name of global variable of SugarCRM
429 * @param array $params some parameters for helper. For example for $mod_strings or $current_user
430 * @return bool is variable setuped or not
432 public static function setUp($varName, $params = array())
435 self::checkHelper($varName);
436 return call_user_func(__CLASS__ . '::setUp_' . $varName, $params);
440 * Clean up all registered variables and restore $initVars and $systemVars
442 * @return bool status of tearDown
444 public static function tearDown()
447 foreach(self::$registeredVars as $varName => $isCalled)
451 unset(self::$registeredVars[$varName]);
452 if (method_exists(__CLASS__, 'tearDown_' . $varName))
454 call_user_func(__CLASS__ . '::tearDown_' . $varName, array());
456 elseif (isset($GLOBALS[$varName]))
458 unset($GLOBALS[$varName]);
463 // Restoring of system variables
464 foreach(self::$initVars as $scope => $vars)
466 foreach ($vars as $name => $value)
468 $GLOBALS[$scope][$name] = $value;
472 // Restoring of theme
473 SugarThemeRegistry::set(self::$systemVars['SugarThemeRegistry']->dirName);
474 SugarCache::$isCacheReset = false;
479 * Registration of $current_user in global scope
482 * @param array $params parameters for SugarTestUserUtilities::createAnonymousUser method
483 * @return bool is variable setuped or not
485 protected static function setUp_current_user(array $params)
487 self::$registeredVars['current_user'] = true;
488 $GLOBALS['current_user'] = call_user_func_array('SugarTestUserUtilities::createAnonymousUser', $params);
493 * Removal of $current_user from global scope
496 * @return bool is variable removed or not
498 protected static function tearDown_current_user()
500 SugarTestUserUtilities::removeAllCreatedAnonymousUsers();
501 unset($GLOBALS['current_user']);
506 * Registration of $beanList in global scope
509 * @return bool is variable setuped or not
511 protected static function setUp_beanList()
513 self::$registeredVars['beanList'] = true;
515 require('include/modules.php');
520 * Registration of $beanFiles in global scope
523 * @return bool is variable setuped or not
525 protected static function setUp_beanFiles()
527 self::$registeredVars['beanFiles'] = true;
529 require('include/modules.php');
534 * Registration of $moduleList in global scope
537 * @return bool is variable setuped or not
539 protected static function setUp_moduleList()
541 self::$registeredVars['moduleList'] = true;
543 require('include/modules.php');
548 * Reinitialization of $moduleList in global scope because we can't unset that variable
551 * @return bool is variable setuped or not
553 protected static function tearDown_moduleList()
555 return self::setUp_moduleList();
559 * Registration of $modListHeader in global scope
562 * @return bool is variable setuped or not
564 protected static function setUp_modListHeader()
566 self::$registeredVars['modListHeader'] = true;
567 if (isset($GLOBALS['current_user']) == false)
569 self::setUp_current_user(array(
574 $GLOBALS['modListHeader'] = query_module_access_list($GLOBALS['current_user']);
579 * Registration of $app_strings in global scope
582 * @return bool is variable setuped or not
584 protected static function setUp_app_strings()
586 self::$registeredVars['app_strings'] = true;
587 $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
592 * Registration of $app_list_strings in global scope
595 * @return bool is variable setuped or not
597 protected static function setUp_app_list_strings()
599 self::$registeredVars['app_list_strings'] = true;
600 $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
605 * Registration of $timedate in global scope
608 * @return bool is variable setuped or not
610 protected static function setUp_timedate()
612 self::$registeredVars['timedate'] = true;
613 $GLOBALS['timedate'] = TimeDate::getInstance();
618 * Removal of $timedate from global scope
621 * @return bool is variable removed or not
623 protected static function tearDown_timedate()
625 $GLOBALS['timedate']->clearCache();
630 * Registration of $mod_strings in global scope
633 * @param array $params parameters for return_module_language function
634 * @return bool is variable setuped or not
636 protected static function setUp_mod_strings(array $params)
638 self::$registeredVars['mod_strings'] = true;
639 $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], $params[0]);
644 * Registration of $dictionary in global scope
647 * @return bool is variable setuped or not
649 protected static function setUp_dictionary()
651 self::setUp('beanFiles');
652 self::setUp('beanList');
653 self::$registeredVars['dictionary'] = true;
656 $dictionary = array();
657 $moduleInstaller = new ModuleInstaller();
658 $moduleInstaller->silent = true;
659 $moduleInstaller->rebuild_tabledictionary();
660 require 'modules/TableDictionary.php';
662 foreach($GLOBALS['beanList'] as $k => $v)
664 VardefManager::loadVardef($k, $v);
670 * Reinitialization of $dictionary in global scope because we can't unset that variable
673 * @return bool is variable setuped or not
675 protected static function tearDown_dictionary()
677 return self::setUp_dictionary();
681 * Cleaning caches and refreshing vardefs
684 * @param string $lhs_module left module from relation
685 * @param string $rhs_module right module from relation
686 * @return bool are caches refreshed or not
688 protected static function setUp_relation(array $params)
690 if (empty($params[0]) || empty($params[1]))
692 throw new SugarTestHelperException('setUp("relation") requires two parameters');
694 list($lhs_module, $rhs_module) = $params;
695 self::$registeredVars['relation'] = true;
696 self::$cleanModules[] = $lhs_module;
698 LanguageManager::clearLanguageCache($lhs_module);
699 if ($lhs_module != $rhs_module)
701 self::$cleanModules[] = $rhs_module;
702 LanguageManager::clearLanguageCache($rhs_module);
705 self::setUp('dictionary');
707 VardefManager::$linkFields = array();
708 VardefManager::clearVardef();
709 VardefManager::refreshVardefs($lhs_module, BeanFactory::getObjectName($lhs_module));
710 if ($lhs_module != $rhs_module)
712 VardefManager::refreshVardefs($rhs_module, BeanFactory::getObjectName($rhs_module));
714 SugarRelationshipFactory::rebuildCache();
720 * Doing the same things like setUp but for initialized list of modules
723 * @return bool are caches refreshed or not
725 protected static function tearDown_relation()
727 SugarRelationshipFactory::deleteCache();
729 $modules = array_unique(self::$cleanModules);
730 foreach ($modules as $module)
732 LanguageManager::clearLanguageCache($module);
735 self::tearDown('dictionary');
737 VardefManager::$linkFields = array();
738 VardefManager::clearVardef();
739 foreach($modules as $module)
741 VardefManager::refreshVardefs($module, BeanFactory::getBeanName($module));
743 SugarRelationshipFactory::rebuildCache();
745 self::$cleanModules = array();