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 'SugarTestEmailAddressUtilities.php';
106 require_once 'SugarTestLangPackCreator.php';
107 require_once 'SugarTestThemeUtilities.php';
108 require_once 'SugarTestContactUtilities.php';
109 require_once 'SugarTestEmailUtilities.php';
110 require_once 'SugarTestCampaignUtilities.php';
111 require_once 'SugarTestLeadUtilities.php';
112 require_once 'SugarTestStudioUtilities.php';
113 require_once 'SugarTestMeetingUtilities.php';
114 require_once 'SugarTestCallUtilities.php';
115 require_once 'SugarTestAccountUtilities.php';
116 require_once 'SugarTestTrackerUtility.php';
117 require_once 'SugarTestImportUtilities.php';
118 require_once 'SugarTestMergeUtilities.php';
119 require_once 'SugarTestTaskUtilities.php';
120 require_once 'SugarTestOpportunityUtilities.php';
121 require_once 'SugarTestRelationshipUtilities.php';
122 require_once 'SugarTestSugarEmailAddressUtilities.php';
124 $GLOBALS['db']->commit();
126 // define our testcase subclass
127 class Sugar_PHPUnit_Framework_TestCase extends PHPUnit_Framework_TestCase
129 protected $backupGlobals = FALSE;
131 protected $useOutputBuffering = true;
133 protected function assertPreConditions()
135 if(isset($GLOBALS['log'])) {
136 $GLOBALS['log']->info("START TEST: {$this->getName(false)}");
138 SugarCache::instance()->flush();
141 protected function assertPostConditions() {
142 if(!empty($_REQUEST)) {
143 foreach(array_keys($_REQUEST) as $k) {
144 unset($_REQUEST[$k]);
149 foreach(array_keys($_POST) as $k) {
155 foreach(array_keys($_GET) as $k) {
159 if(isset($GLOBALS['log'])) {
160 $GLOBALS['log']->info("DONE TEST: {$this->getName(false)}");
162 // reset error handler in case somebody set it
163 restore_error_handler();
166 public static function tearDownAfterClass()
168 unset($GLOBALS['disable_date_format']);
169 unset($GLOBALS['saving_relationships']);
170 unset($GLOBALS['updating_relationships']);
171 $GLOBALS['timedate']->clearCache();
175 // define output testcase subclass
176 class Sugar_PHPUnit_Framework_OutputTestCase extends PHPUnit_Extensions_OutputTestCase
178 protected $backupGlobals = FALSE;
180 protected $_notRegex;
181 protected $_outputCheck;
183 protected function assertPreConditions()
185 if(isset($GLOBALS['log'])) {
186 $GLOBALS['log']->info("START TEST: {$this->getName(false)}");
188 SugarCache::instance()->flush();
191 protected function assertPostConditions() {
192 if(!empty($_REQUEST)) {
193 foreach(array_keys($_REQUEST) as $k) {
194 unset($_REQUEST[$k]);
199 foreach(array_keys($_POST) as $k) {
205 foreach(array_keys($_GET) as $k) {
209 if(isset($GLOBALS['log'])) {
210 $GLOBALS['log']->info("DONE TEST: {$this->getName(false)}");
214 protected function NotRegexCallback($output)
216 if(empty($this->_notRegex)) {
219 $this->assertNotRegExp($this->_notRegex, $output);
223 public function setOutputCheck($callback)
225 if (!is_callable($callback)) {
226 throw new PHPUnit_Framework_Exception;
229 $this->_outputCheck = $callback;
232 protected function runTest()
234 $testResult = parent::runTest();
235 if($this->_outputCheck) {
236 $this->assertTrue(call_user_func($this->_outputCheck, $this->output));
241 public function expectOutputNotRegex($expectedRegex)
243 if (is_string($expectedRegex) || is_null($expectedRegex)) {
244 $this->_notRegex = $expectedRegex;
247 $this->setOutputCheck(array($this, "NotRegexCallback"));
252 // define a mock logger interface; used for capturing logging messages emited
254 class SugarMockLogger
256 private $_messages = array();
258 public function __call($method, $message)
260 $this->messages[] = strtoupper($method) . ': ' . $message[0];
263 public function getLastMessage()
265 return end($this->messages);
268 public function getMessageCount()
270 return count($this->messages);
274 require_once('ModuleInstall/ModuleInstaller.php');
277 * Own exception for SugarTestHelper class
279 * @author mgusev@sugarcrm.com
281 class SugarTestHelperException extends PHPUnit_Framework_Exception
287 * Helper for initialization of global variables of SugarCRM
289 * @author mgusev@sugarcrm.com
291 class SugarTestHelper
294 * @var array array of registered vars. It allows helper to unregister them on tearDown
296 protected static $registeredVars = array();
299 * @var array array of global vars. They are storing on init one time and restoring in global scope each tearDown
301 protected static $initVars = array(
306 * @var array of system preference of SugarCRM as theme etc. They are storing on init one time and restoring each tearDown
308 protected static $systemVars = array();
311 * @var array of modules which we should refresh on tearDown.
313 protected static $cleanModules = array();
316 * @var bool is SugarTestHelper inited or not. Just to skip initialization on the second and others call of init method
318 protected static $isInited = false;
321 * All methods are static because of it we disable constructor
323 private function __construct()
328 * All methods are static because of it we disable clone
330 private function __clone()
335 * Initialization of main variables of SugarCRM in global scope
339 public static function init()
341 if (self::$isInited == true)
346 // initialization & backup of sugar_config
347 self::$initVars['GLOBALS']['sugar_config'] = null;
348 if ($GLOBALS['sugar_config'])
350 self::$initVars['GLOBALS']['sugar_config'] = $GLOBALS['sugar_config'];
352 if (self::$initVars['GLOBALS']['sugar_config'] == false)
354 global $sugar_config;
355 if (is_file('config.php'))
357 require_once('config.php');
359 if (is_file('config_override.php'))
361 require_once('config_override.php');
363 self::$initVars['GLOBALS']['sugar_config'] = $GLOBALS['sugar_config'];
366 // backup of current_language
367 self::$initVars['GLOBALS']['current_language'] = 'en_us';
368 if (isset($sugar_config['current_language']))
370 self::$initVars['GLOBALS']['current_language'] = $sugar_config['current_language'];
372 if (isset($GLOBALS['current_language']))
374 self::$initVars['GLOBALS']['current_language'] = $GLOBALS['current_language'];
376 $GLOBALS['current_language'] = self::$initVars['GLOBALS']['current_language'];
378 // backup of reload_vardefs
379 self::$initVars['GLOBALS']['reload_vardefs'] = null;
380 if (isset($GLOBALS['reload_vardefs']))
382 self::$initVars['GLOBALS']['reload_vardefs'] = $GLOBALS['reload_vardefs'];
386 self::$initVars['GLOBALS']['locale'] = null;
387 if (isset($GLOBALS['locale']))
389 self::$initVars['GLOBALS']['locale'] = $GLOBALS['locale'];
391 if (self::$initVars['GLOBALS']['locale'] == false)
393 self::$initVars['GLOBALS']['locale'] = new Localization();
396 // backup of service_object
397 self::$initVars['GLOBALS']['service_object'] = null;
398 if (isset($GLOBALS['service_object']))
400 self::$initVars['GLOBALS']['service_object'] = $GLOBALS['service_object'];
403 // backup of SugarThemeRegistry
404 self::$systemVars['SugarThemeRegistry'] = SugarThemeRegistry::current();
406 self::$isInited = true;
410 * Checking is there helper for variable or not
413 * @param string $varName name of global variable of SugarCRM
414 * @return bool is there helper for a variable or not
415 * @throws SugarTestHelperException fired when there is no implementation of helper for a variable
417 protected static function checkHelper($varName)
419 if (method_exists(__CLASS__, 'setUp_' . $varName) == false)
421 throw new SugarTestHelperException('setUp for $' . $varName . ' is not implemented. ' . __CLASS__ . '::setUp_' . $varName);
426 * Entry point for setup of global variable
429 * @param string $varName name of global variable of SugarCRM
430 * @param array $params some parameters for helper. For example for $mod_strings or $current_user
431 * @return bool is variable setuped or not
433 public static function setUp($varName, $params = array())
436 self::checkHelper($varName);
437 return call_user_func(__CLASS__ . '::setUp_' . $varName, $params);
441 * Clean up all registered variables and restore $initVars and $systemVars
443 * @return bool status of tearDown
445 public static function tearDown()
448 foreach(self::$registeredVars as $varName => $isCalled)
452 unset(self::$registeredVars[$varName]);
453 if (method_exists(__CLASS__, 'tearDown_' . $varName))
455 call_user_func(__CLASS__ . '::tearDown_' . $varName, array());
457 elseif (isset($GLOBALS[$varName]))
459 unset($GLOBALS[$varName]);
464 // Restoring of system variables
465 foreach(self::$initVars as $scope => $vars)
467 foreach ($vars as $name => $value)
469 $GLOBALS[$scope][$name] = $value;
473 // Restoring of theme
474 SugarThemeRegistry::set(self::$systemVars['SugarThemeRegistry']->dirName);
475 SugarCache::$isCacheReset = false;
480 * Registration of $current_user in global scope
483 * @param array $params parameters for SugarTestUserUtilities::createAnonymousUser method
484 * @return bool is variable setuped or not
486 protected static function setUp_current_user(array $params)
488 self::$registeredVars['current_user'] = true;
489 $GLOBALS['current_user'] = call_user_func_array('SugarTestUserUtilities::createAnonymousUser', $params);
494 * Removal of $current_user from global scope
497 * @return bool is variable removed or not
499 protected static function tearDown_current_user()
501 SugarTestUserUtilities::removeAllCreatedAnonymousUsers();
502 unset($GLOBALS['current_user']);
507 * Registration of $beanList in global scope
510 * @return bool is variable setuped or not
512 protected static function setUp_beanList()
514 self::$registeredVars['beanList'] = true;
516 require('include/modules.php');
521 * Registration of $beanFiles in global scope
524 * @return bool is variable setuped or not
526 protected static function setUp_beanFiles()
528 self::$registeredVars['beanFiles'] = true;
530 require('include/modules.php');
535 * Registration of $moduleList in global scope
538 * @return bool is variable setuped or not
540 protected static function setUp_moduleList()
542 self::$registeredVars['moduleList'] = true;
544 require('include/modules.php');
549 * Reinitialization of $moduleList in global scope because we can't unset that variable
552 * @return bool is variable setuped or not
554 protected static function tearDown_moduleList()
556 return self::setUp_moduleList();
560 * Registration of $modListHeader in global scope
563 * @return bool is variable setuped or not
565 protected static function setUp_modListHeader()
567 self::$registeredVars['modListHeader'] = true;
568 if (isset($GLOBALS['current_user']) == false)
570 self::setUp_current_user(array(
575 $GLOBALS['modListHeader'] = query_module_access_list($GLOBALS['current_user']);
580 * Registration of $app_strings in global scope
583 * @return bool is variable setuped or not
585 protected static function setUp_app_strings()
587 self::$registeredVars['app_strings'] = true;
588 $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']);
593 * Registration of $app_list_strings in global scope
596 * @return bool is variable setuped or not
598 protected static function setUp_app_list_strings()
600 self::$registeredVars['app_list_strings'] = true;
601 $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']);
606 * Registration of $timedate in global scope
609 * @return bool is variable setuped or not
611 protected static function setUp_timedate()
613 self::$registeredVars['timedate'] = true;
614 $GLOBALS['timedate'] = TimeDate::getInstance();
619 * Removal of $timedate from global scope
622 * @return bool is variable removed or not
624 protected static function tearDown_timedate()
626 $GLOBALS['timedate']->clearCache();
631 * Registration of $mod_strings in global scope
634 * @param array $params parameters for return_module_language function
635 * @return bool is variable setuped or not
637 protected static function setUp_mod_strings(array $params)
639 self::$registeredVars['mod_strings'] = true;
640 $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], $params[0]);
645 * Registration of $dictionary in global scope
648 * @return bool is variable setuped or not
650 protected static function setUp_dictionary()
652 self::setUp('beanFiles');
653 self::setUp('beanList');
654 self::$registeredVars['dictionary'] = true;
657 $dictionary = array();
658 $moduleInstaller = new ModuleInstaller();
659 $moduleInstaller->silent = true;
660 $moduleInstaller->rebuild_tabledictionary();
661 require 'modules/TableDictionary.php';
663 foreach($GLOBALS['beanList'] as $k => $v)
665 VardefManager::loadVardef($k, $v);
671 * Reinitialization of $dictionary in global scope because we can't unset that variable
674 * @return bool is variable setuped or not
676 protected static function tearDown_dictionary()
678 return self::setUp_dictionary();
682 * Cleaning caches and refreshing vardefs
685 * @param string $lhs_module left module from relation
686 * @param string $rhs_module right module from relation
687 * @return bool are caches refreshed or not
689 protected static function setUp_relation(array $params)
691 if (empty($params[0]) || empty($params[1]))
693 throw new SugarTestHelperException('setUp("relation") requires two parameters');
695 list($lhs_module, $rhs_module) = $params;
696 self::$registeredVars['relation'] = true;
697 self::$cleanModules[] = $lhs_module;
699 LanguageManager::clearLanguageCache($lhs_module);
700 if ($lhs_module != $rhs_module)
702 self::$cleanModules[] = $rhs_module;
703 LanguageManager::clearLanguageCache($rhs_module);
706 self::setUp('dictionary');
708 VardefManager::$linkFields = array();
709 VardefManager::clearVardef();
710 VardefManager::refreshVardefs($lhs_module, BeanFactory::getObjectName($lhs_module));
711 if ($lhs_module != $rhs_module)
713 VardefManager::refreshVardefs($rhs_module, BeanFactory::getObjectName($rhs_module));
715 SugarRelationshipFactory::rebuildCache();
721 * Doing the same things like setUp but for initialized list of modules
724 * @return bool are caches refreshed or not
726 protected static function tearDown_relation()
728 SugarRelationshipFactory::deleteCache();
730 $modules = array_unique(self::$cleanModules);
731 foreach ($modules as $module)
733 LanguageManager::clearLanguageCache($module);
736 self::tearDown('dictionary');
738 VardefManager::$linkFields = array();
739 VardefManager::clearVardef();
740 foreach($modules as $module)
742 VardefManager::refreshVardefs($module, BeanFactory::getBeanName($module));
744 SugarRelationshipFactory::rebuildCache();
746 self::$cleanModules = array();