public static function forgetAllCaches() { RedBeanModelsCache::forgetAll(); RedBeansCache::forgetAll(); PermissionsCache::forgetAll(); RightsCache::forgetAll(); PoliciesCache::forgetAll(); GeneralCache::forgetAll(); BeanModelCache::forgetAll(); Currency::resetCaches(); //php only cache }
public function testCaching() { $a = new A(); $a->a = 1; $a->uniqueRequiredEmail = '*****@*****.**'; $this->assertTrue($a->save()); $originalAHash = spl_object_hash($a); $id = $a->id; unset($a); $a = A::getById($id); $fromPhpAHash = spl_object_hash($a); unset($a); RedBeanModelsCache::forgetAll(true); $a = A::getById($id); $this->assertEquals(1, $a->a); $this->assertEquals('*****@*****.**', $a->uniqueRequiredEmail); $fromMemcacheAHash = spl_object_hash($a); $this->assertEquals($fromPhpAHash, $originalAHash); $this->assertNotEquals($fromMemcacheAHash, $originalAHash); }
/** * Use this method to clear the current user and login a new user for a walkthrough. */ protected function logoutCurrentUserLoginNewUserAndGetByUsername($username) { //clear states does not log the user out. //todo: actually log user out and then back in. Yii::app()->user->clearStates(); //reset session. Yii::app()->language = Yii::app()->getConfigLanguageValue(); Yii::app()->timeZoneHelper->setTimeZone(Yii::app()->getConfigTimeZoneValue()); $user = User::getByUsername($username); //todo: actually run login? Yii::app()->user->userModel = $user; //Mimic page request to page request behavior where the php cache would be reset. RedBeanModelsCache::forgetAll(true); //todo: maybe call GeneralCache forgetAllPHPCache and also expand PermissionsCache //to have flags for php cache forgetting only. //todo: can we somehow use behavior to do these type of loads like languageHelper->load()? //this way we can utilize the same process as the normal production run of the application. Yii::app()->languageHelper->load(); Yii::app()->timeZoneHelper->load(); return $user; }
public function disabled_testMemcachingAccountsDirectly() { Yii::app()->user->userModel = User::getByUsername('super'); $count = 50; $memcache = new Memcache(); $memcache->connect('localhost', 11211); for ($i = 0; $i < $count; $i++) { $account = self::createRandomAccount($i); $this->assertTrue($account->save()); // So that it has everything it should, // particularly its createdByUser. $this->assertTrue($memcache->set("M:{$i}", serialize($account))); } RedBeanModelsCache::forgetAll(true); RedBeansCache::forgetAll(); Yii::app()->user->userModel = User::getByUsername('super'); $memoryBefore = memory_get_usage(true); for ($i = 0; $i < $count; $i++) { $data = $memcache->get("M:{$i}"); $this->assertTrue($data !== false); $account = unserialize($data); $this->assertTrue($account instanceof Account); $this->assertEquals("Account#{$i}", $account->name); $this->assertEquals("http://www.account{$i}.com", $account->website); $this->assertTrue($account->owner instanceof User); $this->assertEquals('super', $account->owner->username); $this->assertTrue($account->owner === Yii::app()->user->userModel); $this->assertTrue($account->createdByUser === Yii::app()->user->userModel); $this->assertTrue($account->modifiedByUser === Yii::app()->user->userModel); unset($account); } $memoryAfter = memory_get_usage(true); $this->assertWithinPercentage($memoryBefore, $memoryAfter, 10); }
/** * Creates an instance of the extending model wrapping the given * bean. For use only by models. Beans are never used by the * application directly. * @param $bean A <a href="http://www.redbeanphp.com/">RedBean</a> * bean. * @param $modelClassName Pass only when getting it at runtime * gets the wrong name. * @return An instance of the type of the extending model. */ public static function makeModel(RedBean_OODBBean $bean, $modelClassName = null) { assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""'); if ($modelClassName === null) { $modelClassName = get_called_class(); } $modelIdentifier = $modelClassName . strval($bean->id); try { $model = RedBeanModelsCache::getModel($modelIdentifier); $model->constructIncomplete($bean, false); return $model; } catch (NotFoundException $e) { return new $modelClassName(false, $bean); //return new $modelClassName(true, $bean, $forceTreatAsCreation); //no need to set defaults here and force creation since it is always false and the bean already exists } }
public function testFileContentModelNotBeingCached() { $fileContent = new FileContent(); $fileContent->content = str_repeat('a', 1000); $this->assertTrue($fileContent->save()); $modelIdentifier = $fileContent->getModelIdentifier(); RedBeanModelsCache::cacheModel($fileContent); try { RedBeanModelsCache::getModel($modelIdentifier); } catch (NotFoundException $e) { $this->fail('NotFoundException exception is thrown.'); } $prefix = RedBeanModelsCache::getCachePrefix($modelIdentifier, RedBeanModelsCache::$cacheType); $cachedData = false; if (isset(Yii::app()->cache)) { $cachedData = Yii::app()->cache->get($prefix . $modelIdentifier); } $this->assertFalse($cachedData); }
/** * Used for testing purposes if you need to clear out just the php caching. */ public static function forgetAllModelIdentifiersToModels() { self::$modelIdentifiersToModels = array(); }
/** * @depends testRequiredAttributesAreMissingFromLayout */ public function testMakingAlreadyPlacedNonrequiredStandardAttributeRequiredAndThenMakingItUnrequired() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default/create'); $this->assertNotContains('There are required fields missing from the following layout', $content); //Now make industry required. $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName(new Account(), 'industry'); $this->assertFalse($attributeForm->isRequired); $attributeForm->isRequired = true; $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData(); $adapter = new $modelAttributesAdapterClassName(new Account()); try { $adapter->setAttributeMetadataFromForm($attributeForm); } catch (FailedDatabaseSchemaChangeException $e) { echo $e->getMessage(); $this->fail(); } RequiredAttributesValidViewUtil::resolveToSetAsMissingRequiredAttributesByModelClassName('Account', 'industry'); RedBeanModelsCache::forgetAll(); $content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default/create'); $this->assertNotContains('There are required fields missing from the following layout', $content); //Now make industry unrequired. $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName(new Account(), 'industry'); $this->assertTrue($attributeForm->isRequired); $attributeForm->isRequired = false; $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData(); $adapter = new $modelAttributesAdapterClassName(new Account()); try { $adapter->setAttributeMetadataFromForm($attributeForm); } catch (FailedDatabaseSchemaChangeException $e) { echo $e->getMessage(); $this->fail(); } RequiredAttributesValidViewUtil::resolveToRemoveAttributeAsMissingRequiredAttribute('Account', 'industry'); RedBeanModelsCache::forgetAll(); //Confirm industry is truly unrequired. $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName(new Account(), 'industry'); $this->assertFalse($attributeForm->isRequired); //Now the layout should not show an error message. $content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default/create'); $this->assertNotContains('There are required fields missing from the following layout', $content); }
/** * @depends testExistingModelsShowCustomFieldDataCorrectlyWhenAttributeIsAddedAsDatabaseColumn */ public function testStandardAttributeThatBecomesRequiredCanStillBeChangedToBeUnrequired() { Yii::app()->user->userModel = User::getByUsername('super'); $account = new Account(); //Name for example, is required by default. $adapter = new ModelAttributesAdapter($account); $this->assertTrue($adapter->isStandardAttributeRequiredByDefault('name')); //Industry is not required by default. $adapter = new DropDownModelAttributesAdapter($account); $this->assertFalse($adapter->isStandardAttributeRequiredByDefault('industry')); $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName($account, 'industry'); $this->assertFalse($attributeForm->isRequired); $this->assertTrue($attributeForm->canUpdateAttributeProperty('isRequired')); //Now make industry required. $attributeForm->isRequired = true; $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData(); $adapter = new $modelAttributesAdapterClassName(new Account()); try { $adapter->setAttributeMetadataFromForm($attributeForm); } catch (FailedDatabaseSchemaChangeException $e) { echo $e->getMessage(); $this->fail(); } RedBeanModelsCache::forgetAll(); $account = new Account(); $adapter = new DropDownModelAttributesAdapter($account); $this->assertFalse($adapter->isStandardAttributeRequiredByDefault('industry')); $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName($account, 'industry'); $this->assertTrue($attributeForm->isRequired); $this->assertTrue($attributeForm->canUpdateAttributeProperty('isRequired')); }
/** * @depends testUserAddedToRoleWhereUserIsMemberOfGroupWithChildrenGroups_Slide19 */ public function testUserAddedToRoleWhereUserIsMemberOfGroupWithChildrenGroups_Slide20() { $u1 = User::getByUsername('u1.'); $u99 = User::getByUsername('u99.'); Yii::app()->user->userModel = $u99; $u1->role = null; $this->assertTrue($u1->save()); $g1 = Group::getByName('G1.'); $g2 = Group::getByName('G2.'); $g3 = Group::getByName('G3.'); $g1->groups->add($g2); $this->assertTrue($g1->save()); $g2->groups->add($g3); $this->assertTrue($g2->save()); $g3->users->add($u1); $this->assertTrue($g3->save()); $u1->forget(); //Forget the user, so the user knows what groups it is part of. $u1 = User::getByUsername('u1.'); $r1 = Role::getByName('R1.'); $r2 = Role::getByName('R2.'); $r3 = Role::getByName('R3.'); $a1 = new Account(); $a1->name = 'A1.'; $a1->addPermissions($g1, Permission::READ); $this->assertTrue($a1->save()); //Called in OwnedSecurableItem::afterSave(); //ReadPermissionsOptimizationUtil::ownedSecurableItemCreated($a1); $a2 = new Account(); $a2->name = 'A2.'; $a2->addPermissions($g2, Permission::READ); $this->assertTrue($a2->save()); //Called in OwnedSecurableItem::afterSave(); //ReadPermissionsOptimizationUtil::ownedSecurableItemCreated($a2); $a3 = new Account(); $a3->name = 'A3.'; $a3->addPermissions($g3, Permission::READ); $this->assertTrue($a3->save()); //Called in OwnedSecurableItem::afterSave(); //ReadPermissionsOptimizationUtil::ownedSecurableItemCreated($a3); ReadPermissionsOptimizationUtil::securableItemGivenPermissionsForGroup($a1, $g1); ReadPermissionsOptimizationUtil::securableItemGivenPermissionsForGroup($a2, $g2); ReadPermissionsOptimizationUtil::securableItemGivenPermissionsForGroup($a3, $g3); $u1->role = $r1; $this->assertTrue($u1->save()); //Called in $u1->afterSave(); //ReadPermissionsOptimizationUtil::userAddedToRole($u1); $r1->forget(); //Forget R1 so when it is utilized below, it will know that u1 is a member. $this->assertEquals(array(array('A1', 'G1', 1), array('A1', 'G2', 1), array('A1', 'G3', 1), array('A1', 'R2', 1), array('A1', 'R3', 1), array('A2', 'G2', 1), array('A2', 'G3', 1), array('A2', 'R2', 1), array('A2', 'R3', 1), array('A3', 'G3', 1), array('A3', 'R2', 1), array('A3', 'R3', 1)), self::getAccountMungeRows()); $this->assertTrue(self::accountMungeDoesntChangeWhenRebuilt()); $u1->forget(); //Forget the user, so the user knows what groups it is part of. $u1 = User::getByUsername('u1.'); $u1->role = null; $this->assertTrue($u1->save()); RedBeanModelsCache::forgetAll(); RedBeansCache::forgetAll(); $this->assertEquals(array(array('A1', 'G1', 1), array('A1', 'G2', 1), array('A1', 'G3', 1), array('A2', 'G2', 1), array('A2', 'G3', 1), array('A3', 'G3', 1)), self::getAccountMungeRows()); $this->assertTrue(self::accountMungeDoesntChangeWhenRebuilt()); $a1->delete(); $a2->delete(); $a3->delete(); $g1->group = null; $this->assertTrue($g1->save()); $g2->group = null; $this->assertTrue($g2->save()); $g3->forget(); $g3 = Group::getByName('G3.'); $g3->group = null; $g3->users->removeAll(); $this->assertTrue($g3->save()); $r1 = Role::getByName('R1.'); $u1->role = $r1; $this->assertTrue($u1->save()); }
/** * Test sending an email that should go out as a processing that this job would typically do. * Also tests that item does not get trashed when deleting the WorkflowMessageInQueue. * Also tests that if there is more than one emailmessage against the workflow, that it does not send * to all of them * @depends testWorkflowMessageInQueueProperlySavesWithoutTrashingRelatedModelItem */ public function testRun() { Yii::app()->user->userModel = User::getByUsername('super'); $emailTemplate = new EmailTemplate(); $emailTemplate->builtType = EmailTemplate::BUILT_TYPE_PASTED_HTML; $emailTemplate->name = 'the name'; $emailTemplate->modelClassName = 'Account'; $emailTemplate->type = 2; $emailTemplate->subject = 'subject'; $emailTemplate->textContent = 'sample text content'; $saved = $emailTemplate->save(); $this->assertTrue($saved); $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount()); $model = ContactTestHelper::createContactByNameForOwner('Jason', Yii::app()->user->userModel); $model->primaryEmail->emailAddress = '*****@*****.**'; $saved = $model->save(); $this->assertTrue($saved); $modelId = $model->id; $model->forget(); $model = Contact::getById($modelId); $trigger = array('attributeIndexOrDerivedType' => 'firstName', 'operator' => OperatorRules::TYPE_EQUALS, 'durationInterval' => '333'); $actions = array(array('type' => ActionForWorkflowForm::TYPE_UPDATE_SELF, ActionForWorkflowForm::ACTION_ATTRIBUTES => array('description' => array('shouldSetValue' => '1', 'type' => WorkflowActionAttributeForm::TYPE_STATIC, 'value' => 'some new description')))); $emailMessages = array(); $emailMessages[0]['emailTemplateId'] = $emailTemplate->id; $emailMessages[0]['sendFromType'] = EmailMessageForWorkflowForm::SEND_FROM_TYPE_DEFAULT; $emailMessages[0]['sendAfterDurationSeconds'] = '0'; $emailMessages[0][EmailMessageForWorkflowForm::EMAIL_MESSAGE_RECIPIENTS] = array(array('type' => WorkflowEmailMessageRecipientForm::TYPE_DYNAMIC_TRIGGERED_MODEL, 'audienceType' => EmailMessageRecipient::TYPE_TO)); $emailMessages[1]['emailTemplateId'] = $emailTemplate->id; $emailMessages[1]['sendFromType'] = EmailMessageForWorkflowForm::SEND_FROM_TYPE_DEFAULT; $emailMessages[1]['sendAfterDurationSeconds'] = '10000'; $emailMessages[1][EmailMessageForWorkflowForm::EMAIL_MESSAGE_RECIPIENTS] = array(array('type' => WorkflowEmailMessageRecipientForm::TYPE_DYNAMIC_TRIGGERED_MODEL, 'audienceType' => EmailMessageRecipient::TYPE_TO)); $savedWorkflow = new SavedWorkflow(); $savedWorkflow->name = 'some workflow'; $savedWorkflow->description = 'description'; $savedWorkflow->moduleClassName = 'ContactsModule'; $savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW_AND_EXISTING; $savedWorkflow->type = Workflow::TYPE_ON_SAVE; $data[ComponentForWorkflowForm::TYPE_TRIGGERS] = array($trigger); $data[ComponentForWorkflowForm::TYPE_ACTIONS] = $actions; $data[ComponentForWorkflowForm::TYPE_EMAIL_MESSAGES] = $emailMessages; $savedWorkflow->serializedData = serialize($data); $savedWorkflow->isActive = true; $saved = $savedWorkflow->save(); $this->assertTrue($saved); WorkflowTestHelper::createExpiredWorkflowMessageInQueue($model, $savedWorkflow, serialize(array($emailMessages[1]))); RedBeanModelsCache::forgetAll(true); //simulates page change, required to confirm Item does not get trashed $this->assertEquals(1, WorkflowMessageInQueue::getCount()); $job = new WorkflowMessageInQueueJob(); $this->assertTrue($job->run()); $this->assertEquals(0, WorkflowMessageInQueue::getCount()); RedBeanModelsCache::forgetAll(true); //simulates page change, required to confirm Item does not get trashed $this->assertEquals(1, Yii::app()->emailHelper->getQueuedCount()); }
/** * Creates an instance of the extending model wrapping the given * bean. For use only by models. Beans are never used by the * application directly. * @param $bean A <a href="http://www.redbeanphp.com/">RedBean</a> * bean. * @param $modelClassName Pass only when getting it at runtime * gets the wrong name. * @return An instance of the type of the extending model. */ public static function makeModel(RedBean_OODBBean $bean, $modelClassName = null, $forceTreatAsCreation = false) { assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""'); if ($modelClassName === null) { $modelClassName = get_called_class(); } $modelIdentifier = $modelClassName . strval($bean->id); try { $model = RedBeanModelsCache::getModel($modelIdentifier); $model->constructIncomplete($bean, false); return $model; } catch (NotFoundException $e) { return new $modelClassName(true, $bean, $forceTreatAsCreation); } }
protected function actionAttributeSave($attributeForm, $model) { assert('!empty($_GET["moduleClassName"])'); $wasRequired = $attributeForm->isRequired; $attributeForm->setAttributes($_POST[get_class($attributeForm)]); $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData(); $adapter = new $modelAttributesAdapterClassName($model); $adapter->setAttributeMetadataFromForm($attributeForm); if ($attributeForm->isRequired && !$wasRequired) { RequiredAttributesValidViewUtil::resolveToSetAsMissingRequiredAttributesByModelClassName(get_class($model), $attributeForm->attributeName); } elseif (!$attributeForm->isRequired && $wasRequired) { RequiredAttributesValidViewUtil::resolveToRemoveAttributeAsMissingRequiredAttribute(get_class($model), $attributeForm->attributeName); } RedBeanModelsCache::forgetAll(); //Ensures existing models that are cached see the new dropdown. $routeParams = array_merge(array('default/attributesList'), $_GET); $this->redirect($routeParams); }
protected function forgetModelsWithForgottenValidators() { foreach ($this->modelIdentifiersForForgottenValidators as $modelIdentifier => $notUsed) { RedBeanModelsCache::forgetModelByIdentifier($modelIdentifier); } }
public function testMixedInPersonInUser() { $user = new User(); $user->username = '******'; $user->lastName = 'Dude'; $this->assertTrue($user->save()); $this->assertTrue($user->isAttribute('id')); // From RedBeanModel. $this->assertTrue($user->isAttribute('createdDateTime')); // From Item. $this->assertTrue($user->isAttribute('firstName')); // From Person. $this->assertTrue($user->isAttribute('username')); // From User. $this->assertTrue($user->isRelation('createdByUser')); // From Item. $this->assertTrue($user->isRelation('rights')); // From Permitable. $this->assertTrue($user->isRelation('title')); // From Person. $this->assertTrue($user->isRelation('manager')); // From User. unset($user); $user = User::getByUsername('dude'); $this->assertTrue($user->isAttribute('id')); // From RedBeanModel. $this->assertTrue($user->isAttribute('createdDateTime')); // From Item. $this->assertTrue($user->isAttribute('firstName')); // From Person. $this->assertTrue($user->isAttribute('username')); // From User. $this->assertTrue($user->isRelation('createdByUser')); // From Item. $this->assertTrue($user->isRelation('rights')); // From Permitable. $this->assertTrue($user->isRelation('title')); // From Person. $this->assertTrue($user->isRelation('manager')); // From User. RedBeanModelsCache::cacheModel($user); $modelIdentifier = $user->getModelIdentifier(); unset($user); RedBeanModelsCache::forgetAll(true); // Forget it at the php level. RedBeansCache::forgetAll(); if (MEMCACHE_ON) { $user = RedBeanModelsCache::getModel($modelIdentifier); $this->assertTrue($user->isAttribute('id')); // From RedBeanModel. $this->assertTrue($user->isAttribute('createdDateTime')); // From Item. $this->assertTrue($user->isAttribute('firstName')); // From Person. $this->assertTrue($user->isAttribute('username')); // From User. $this->assertTrue($user->isRelation('createdByUser')); // From Item. $this->assertTrue($user->isRelation('rights')); // From Permitable. $this->assertTrue($user->isRelation('title')); // From Person. $this->assertTrue($user->isRelation('manager')); // From User. } }
protected static function accountMungeDoesntChangeWhenRebuilt() { //Need to forget all since sometimes the related information is cached from //before something occurred during a test. RedBeanModelsCache::forgetAll(); RedBeansCache::forgetAll(); $beforeRows = self::getAccountMungeRows(); ReadPermissionsOptimizationUtil::rebuild(); $afterRows = self::getAccountMungeRows(); if ($beforeRows != $afterRows) { echo "Before and after rebuild munge doesn't match.\n"; self::echoRows($beforeRows); self::echoRows($afterRows); } return $beforeRows == $afterRows; }
public function testForgetAll() { $a = new A(); $a->a = 1; $a->uniqueRequiredEmail = '*****@*****.**'; $this->assertTrue($a->save()); $modelIdentifier = $a->getModelIdentifier(); $modelFromCache = RedBeanModelsCache::getModel($modelIdentifier); $this->assertEquals(1, $modelFromCache->a); $this->assertEquals('*****@*****.**', $modelFromCache->uniqueRequiredEmail); // Set some GeneralCache, which should stay in cache after cleanup GeneralCache::cacheEntry('somethingForTesting', 34); $value = GeneralCache::getEntry('somethingForTesting'); $this->assertEquals(34, $value); RedBeanModelsCache::forgetAll(); try { RedBeanModelsCache::getModel($modelIdentifier); $this->fail('NotFoundException exception is not thrown.'); } catch (NotFoundException $e) { // Data from generalCache should still be in cache $value = GeneralCache::getEntry('somethingForTesting'); $this->assertEquals(34, $value); } }