public function teardown()
 {
     if ($this->freeze) {
         RedBeanDatabase::freeze();
     }
     parent::teardown();
 }
 public function testSaveModelFromPostSuccessfulSave()
 {
     //Unfreeze since the test model is not part of the standard schema.
     $freezeWhenComplete = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freezeWhenComplete = true;
     }
     Yii::app()->user->userModel = User::getByUsername('super');
     $savedSuccessfully = false;
     $modelToStringValue = null;
     $postData = array('member' => 'abc');
     $model = new OwnedSecurableTestItem();
     $this->assertFalse($model->hasErrors());
     $controllerUtil = new ZurmoControllerUtil();
     $model = $controllerUtil->saveModelFromPost($postData, $model, $savedSuccessfully, $modelToStringValue);
     $this->assertTrue($savedSuccessfully);
     $this->assertEquals('abc', $modelToStringValue);
     $this->assertFalse($model->hasErrors());
     $this->assertTrue($model->id > 0);
     //Re-freeze if needed.
     if ($freezeWhenComplete) {
         RedBeanDatabase::freeze();
     }
 }
Exemple #3
0
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     global $freeze;
     if ($freeze) {
         $schemaFile = sys_get_temp_dir() . '/autobuilt.sql';
         $success = preg_match("/;dbname=([^;]+)/", Yii::app()->db->connectionString, $matches);
         // Not Coding Standard
         assert('$success == 1');
         // Not Coding Standard
         $databaseName = $matches[1];
         if (file_exists($schemaFile) && filesize($schemaFile) > 0) {
             system('mysql -u' . Yii::app()->db->username . ' -p' . Yii::app()->db->password . ' ' . $databaseName . " < {$schemaFile}");
         }
     }
     RedBeanDatabase::setup(Yii::app()->db->connectionString, Yii::app()->db->username, Yii::app()->db->password);
     assert('RedBeanDatabase::isSetup()');
     // Not Coding Standard
     GeneralCache::forgetAll();
     if ($freeze) {
         RedBeanDatabase::freeze();
         TestDatabaseUtil::deleteRowsFromAllTablesExceptLog();
     } else {
         TestDatabaseUtil::deleteAllTablesExceptLog();
     }
     Yii::app()->user->userModel = null;
     Yii::app()->user->clearStates();
     //reset session.
     Yii::app()->language = Yii::app()->getConfigLanguageValue();
     Yii::app()->timeZoneHelper->setTimeZone(Yii::app()->getConfigTimeZoneValue());
     Yii::app()->timeZoneHelper->load();
     //resets timezone
     Yii::app()->languageHelper->flushModuleLabelTranslationParameters();
 }
Exemple #4
0
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     global $freeze;
     RedBeanDatabase::setup(Yii::app()->db->connectionString, Yii::app()->db->username, Yii::app()->db->password);
     assert('RedBeanDatabase::isSetup()');
     // Not Coding Standard
     if ($freeze) {
         $schemaFile = sys_get_temp_dir() . '/autobuilt.sql';
         $success = preg_match("/;dbname=([^;]+)/", Yii::app()->db->connectionString, $matches);
         // Not Coding Standard
         assert('$success == 1');
         // Not Coding Standard
         $databaseName = $matches[1];
         if (is_readable($schemaFile) && filesize($schemaFile) > 0) {
             $systemOutput = system('mysql -u' . Yii::app()->db->username . ' -p' . Yii::app()->db->password . ' ' . $databaseName . " < {$schemaFile}");
             if ($systemOutput != null) {
                 echo 'Loading schema using system command. Output: ' . $systemOutput . "\n\n";
             }
         } else {
             echo "The schema file is not readable: {$schemaFile}. \n\n";
             exit;
         }
     }
     CustomFieldData::forgetAllPhpCache();
     GeneralCache::forgetAll();
     BeanModelCache::forgetAll();
     if ($freeze) {
         RedBeanDatabase::freeze();
         TestDatabaseUtil::deleteRowsFromAllTablesExceptLog();
     } else {
         TestDatabaseUtil::deleteAllTablesExceptLog();
     }
     Yii::app()->user->userModel = null;
     Yii::app()->user->clearStates();
     //reset session.
     Yii::app()->language = Yii::app()->getConfigLanguageValue();
     Yii::app()->timeZoneHelper->setTimeZone(Yii::app()->getConfigTimeZoneValue());
     Yii::app()->timeZoneHelper->load();
     //resets timezone
     Yii::app()->languageHelper->flushModuleLabelTranslationParameters();
     if (static::$activateDefaultLanguages) {
         Yii::app()->languageHelper->load();
         Yii::app()->languageHelper->activateLanguagesForTesting();
         Yii::app()->languageHelper->importMessagesForTesting();
     }
 }
 /**
  * Given a file resource, convert the file into a database table based on the table name provided.
  * Assumes the file is a csv.
  * @param resource $fileHandle
  * @param string $tableName
  * @return true on success.
  */
 public static function makeDatabaseTableByFileHandleAndTableName($fileHandle, $tableName, $delimiter = ',', $enclosure = "'")
 {
     assert('gettype($fileHandle) == "resource"');
     assert('is_string($tableName)');
     assert('$tableName == strtolower($tableName)');
     assert('$delimiter != null && is_string($delimiter)');
     assert('$enclosure != null && is_string($enclosure)');
     $freezeWhenComplete = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freezeWhenComplete = true;
     }
     R::exec("drop table if exists {$tableName}");
     $columns = self::optimizeTableImportColumnsAndGetColumnNames($fileHandle, $tableName, $delimiter, $enclosure);
     rewind($fileHandle);
     self::convertCsvIntoRowsInTable($fileHandle, $tableName, $delimiter, $enclosure, $columns);
     self::optimizeTableNonImportColumns($tableName);
     if ($freezeWhenComplete) {
         RedBeanDatabase::freeze();
     }
     return true;
 }
 public static function tearDownAfterClass()
 {
     if (self::$freeze) {
         RedBeanDatabase::freeze();
     }
     parent::tearDownAfterClass();
 }
 public function disabled_testAShootLoadOfAccounts()
 {
     $freezeAfterFirst20 = false;
     $super = User::getByUsername('super');
     foreach (array(20, 50, 100, 200, 500, 1000, 10000, 100000, 200000) as $shootLoad) {
         echo "\nNuking existing accounts...\n";
         Yii::app()->user->userModel = $super;
         $this->nukeExistingAccounts();
         echo "Creating {$shootLoad} accounts...\n";
         echo " - Giving every 10th to Betty, giving Benny read\n";
         echo "   on overy 8th, and giving Sales Staff read on\n";
         echo "   every 12th.\n";
         list($time, $countThatBennyCanRead, $accountIdsThatBennyCanRead) = $this->createAccounts($shootLoad);
         echo 'Created accounts in ' . round($time, 1) . " seconds.\n";
         echo "Benny can read {$countThatBennyCanRead} of them.\n";
         echo 'The first few... ';
         for ($i = 0; $i < 10 && $i < count($accountIdsThatBennyCanRead); $i++) {
             echo "{$accountIdsThatBennyCanRead[$i]}|";
         }
         echo "\n";
         $startTime = microtime(true);
         ReadPermissionsOptimizationUtil::rebuild(true);
         $endTime = microtime(true);
         if ($this->isDebug()) {
             echo 'Rebuilt the munge in php in ' . round($endTime - $startTime, 1) . ' seconds, ' . self::getAccountMungeRowCount() . " rows.\n";
         }
         $phpRows = R::getAll('select munge_id, securableitem_id, count from account_read order by munge_id, securableitem_id, count');
         // If $securityOptimized is false in debug.php the second one will just do the php again.
         $startTime = microtime(true);
         ReadPermissionsOptimizationUtil::rebuild();
         $endTime = microtime(true);
         if ($this->isDebug()) {
             echo 'Rebuilt the munge ' . (SECURITY_OPTIMIZED ? 'optimized' : 'in php') . ' in ' . round($endTime - $startTime, 1) . ' seconds, ' . self::getAccountMungeRowCount() . " rows.\n";
         }
         $otherRows = R::getAll('select munge_id, securableitem_id, count from account_read order by munge_id, securableitem_id, count');
         if (count(array_diff($phpRows, $otherRows)) > 0) {
             echo "PHP & optimized munges don't match.\n";
             echo "--------\n";
             foreach ($phpRows as $row) {
                 echo join(', ', array_values($row)) . "\n";
             }
             echo "--------\n";
             foreach ($otherRows as $row) {
                 echo join(', ', array_values($row)) . "\n";
             }
             echo "--------\n";
         }
         $this->assertEquals(count($phpRows), count($otherRows));
         $this->assertEquals($phpRows, $otherRows);
         Yii::app()->user->userModel = User::getByUsername('benny');
         $count = Account::getCount();
         $startTime = microtime(true);
         $accounts = Account::getSubset(null, 0, 20);
         $endTime = microtime(true);
         echo 'As Benny retrieved 1 - ' . count($accounts) . " of {$count} in " . round($endTime - $startTime, 2) . " seconds.\n";
         unset($accounts);
         $offset = intval($count * 0.75);
         $startTime = microtime(true);
         $accounts = Account::getSubset(null, $offset, 20);
         $endTime = microtime(true);
         echo "As Benny retrieved {$offset} - " . ($offset + count($accounts)) . " of {$count} in " . round($endTime - $startTime, 3) . " seconds.\n";
         unset($accounts);
         echo "Done.\n";
         echo "\n-------------------------------\n";
         if ($freezeAfterFirst20 && !RedBeanDatabase::isFrozen()) {
             echo "Freezing database...\n";
             RedBeanDatabase::freeze();
         }
     }
 }
 public function handleSetupDatabaseConnection($event)
 {
     RedBeanDatabase::setup(Yii::app()->db->connectionString, Yii::app()->db->username, Yii::app()->db->password);
     if (Yii::app()->isApplicationInstalled()) {
         if (!FORCE_NO_FREEZE) {
             RedBeanDatabase::freeze();
         }
     } else {
         throw new NotSupportedException();
     }
 }
Exemple #9
0
 /**
  * From the command line, run the autobuild method which will effectively update
  * the database schema.
  */
 public static function runAutoBuildFromUpdateSchemaCommand($messageLogger)
 {
     assert('$messageLogger instanceof MessageLogger');
     ForgetAllCacheUtil::forgetAllCaches();
     $freezeWhenDone = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freezeWhenDone = true;
     }
     self::autoBuildDatabase($messageLogger);
     if ($freezeWhenDone) {
         RedBeanDatabase::freeze();
     }
     // Send notification to super admin to clean assets folder(optional).
     $message = new NotificationMessage();
     $message->textContent = Zurmo::t('InstallModule', 'Please delete all files from assets folder on server.');
     $rules = new ClearAssetsFolderNotificationRules();
     NotificationsUtil::submit($message, $rules);
     return true;
 }
 /**
  * @param array $modelClassNames
  * @param MessageLogger $messageLogger
  */
 public static function manageFrozenStateAndAutoBuildModels(array $modelClassNames, &$messageLogger)
 {
     RedBeanDatabase::unfreeze();
     self::autoBuildModels($modelClassNames, $messageLogger);
     RedBeanDatabase::freeze();
 }
Exemple #11
0
 /**
  * @depends testSimpleImportWithStringAndFullNameWhichAreRequiredAttributeOnImportTestModelItem
  */
 public function testSettingExplicitReadWriteModelPermissionsDuringImport()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $testModels = ImportModelTestItem::getAll();
     $this->assertEquals(0, count($testModels));
     //Add a read only user for import. Then all models should be readable by jim in addition to super.
     $explicitReadWriteModelPermissions = new ExplicitReadWriteModelPermissions();
     $explicitReadWriteModelPermissions->addReadOnlyPermitable(User::getByUsername('jim'));
     //Unfreeze since the test model is not part of the standard schema.
     $freezeWhenComplete = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freezeWhenComplete = true;
     }
     $testModels = ImportModelTestItem::getAll();
     $this->assertEquals(0, count($testModels));
     $import = new Import();
     $serializedData['importRulesType'] = 'ImportModelTestItem';
     $serializedData['firstRowIsHeaderRow'] = true;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import->getTempTableName());
     $this->assertEquals(13, ImportDatabaseUtil::getCount($import->getTempTableName()));
     // includes header rows.
     $mappingData = array('column_0' => array('attributeIndexOrDerivedType' => 'string', 'type' => 'importColumn', 'mappingRulesData' => array('DefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => null))), 'column_23' => array('attributeIndexOrDerivedType' => 'FullName', 'type' => 'importColumn', 'mappingRulesData' => array('FullNameDefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => null))));
     $importRules = ImportRulesUtil::makeImportRulesByType('ImportModelTestItem');
     $page = 0;
     $config = array('pagination' => array('pageSize' => 3));
     //This way all rows are processed.
     $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config);
     $dataProvider->getPagination()->setCurrentPage($page);
     $importResultsUtil = new ImportResultsUtil($import);
     $messageLogger = new ImportMessageLogger();
     ImportUtil::importByDataProvider($dataProvider, $importRules, $mappingData, $importResultsUtil, $explicitReadWriteModelPermissions, $messageLogger);
     $importResultsUtil->processStatusAndMessagesForEachRow();
     //Confirm that 3 models where created.
     $testModels = ImportModelTestItem::getAll();
     $this->assertEquals(3, count($testModels));
     $jim = User::getByUsername('jim');
     foreach ($testModels as $model) {
         $this->assertEquals(array(Permission::READ, Permission::NONE), $model->getExplicitActualPermissions($jim));
     }
     //Clear out data in table
     R::exec("delete from " . ImportModelTestItem::getTableName('ImportModelTestItem'));
     //Now test with read/write permissions being set.
     $explicitReadWriteModelPermissions = new ExplicitReadWriteModelPermissions();
     $explicitReadWriteModelPermissions->addReadWritePermitable(User::getByUsername('jim'));
     $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config);
     $dataProvider->getPagination()->setCurrentPage($page);
     $importResultsUtil = new ImportResultsUtil($import);
     $messageLogger = new ImportMessageLogger();
     ImportUtil::importByDataProvider($dataProvider, $importRules, $mappingData, $importResultsUtil, $explicitReadWriteModelPermissions, $messageLogger);
     $importResultsUtil->processStatusAndMessagesForEachRow();
     //Confirm that 3 models where created.
     $testModels = ImportModelTestItem::getAll();
     $this->assertEquals(3, count($testModels));
     $jim = User::getByUsername('jim');
     foreach ($testModels as $model) {
         $this->assertEquals(array(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, Permission::NONE), $model->getExplicitActualPermissions($jim));
     }
     //Re-freeze if needed.
     if ($freezeWhenComplete) {
         RedBeanDatabase::freeze();
     }
 }
Exemple #12
0
 public static function createImportModelTestItem4($name)
 {
     $freeze = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freeze = true;
     }
     $model = new ImportModelTestItem4();
     $model->name = $name;
     $saved = $model->save();
     assert('$saved');
     if ($freeze) {
         RedBeanDatabase::freeze();
     }
     return $model;
 }
Exemple #13
0
 protected function createImportTempTable($columnCount, $tableName)
 {
     $freezeWhenComplete = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freezeWhenComplete = true;
     }
     $newBean = R::dispense($tableName);
     for ($i = 0; $i < $columnCount; $i++) {
         $columnName = 'column_' . $i;
         $newBean->{$columnName} = str_repeat(' ', 50);
         $columns[] = $columnName;
     }
     R::store($newBean);
     R::trash($newBean);
     R::wipe($tableName);
     ImportDatabaseUtil::optimizeTableNonImportColumns($tableName);
     R::wipe($tableName);
     if ($freezeWhenComplete) {
         RedBeanDatabase::freeze();
     }
 }
 public function testSequentialProcessViewFactory()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $freezeWhenComplete = false;
     //Unfreeze since the test model is not part of the standard schema.
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $freezeWhenComplete = true;
     }
     $testModels = ImportModelTestItem::getAll();
     $this->assertEquals(0, count($testModels));
     $import = new Import();
     $mappingData = array('column_0' => array('attributeIndexOrDerivedType' => 'string', 'type' => 'importColumn', 'mappingRulesData' => array('DefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => null))), 'column_23' => array('attributeIndexOrDerivedType' => 'FullName', 'type' => 'importColumn', 'mappingRulesData' => array('FullNameDefaultValueModelAttributeMappingRuleForm' => array('defaultValue' => null))));
     $serializedData['importRulesType'] = 'ImportModelTestItem';
     $serializedData['mappingData'] = $mappingData;
     $serializedData['firstRowIsHeaderRow'] = true;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import->getTempTableName());
     $config = array('pagination' => array('pageSize' => 2));
     $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config);
     $sequentialProcess = new ImportCreateUpdateModelsSequentialProcess($import, $dataProvider);
     $sequentialProcess->run(null, null);
     $route = 'default/someAction';
     $view = SequentialProcessViewFactory::makeBySequentialProcess($sequentialProcess, $route);
     $content = $view->render();
     $this->assertNotNull($content);
     $this->assertEquals('SequentialProcessView', get_class($view));
     $this->assertEquals('processRows', $sequentialProcess->getNextStep());
     //Now process the first run. Will process page 0.
     $sequentialProcess = new ImportCreateUpdateModelsSequentialProcess($import, $dataProvider);
     $sequentialProcess->run('processRows', null);
     $route = 'default/someAction';
     $view = SequentialProcessViewFactory::makeBySequentialProcess($sequentialProcess, $route);
     $content = $view->render();
     $this->assertNotNull($content);
     $this->assertEquals('SequentialProcessView', get_class($view));
     $this->assertEquals(array('page' => 1), $sequentialProcess->getNextParams());
     //Confirm 2 models were successfully added.
     $testModels = ImportModelTestItem::getAll();
     $this->assertEquals(2, count($testModels));
     //Re-freeze if needed.
     if ($freezeWhenComplete) {
         RedBeanDatabase::freeze();
     }
 }