protected function clearAllCaches()
 {
     ForgetAllCacheUtil::forgetAllCaches();
     PermissionsCache::forgetAll(true);
     RightsCache::forgetAll(true);
     Role::forgetRoleIdToRoleCache();
 }
 /**
  * Clear cache directories. Optionally specify an array of paths to be cleared.
  * @param bool $forgetAllCaches
  * @param array $cacheDirectories
  */
 public static function clearCacheDirectories($forgetAllCaches = true, array $cacheDirectories = array())
 {
     if ($forgetAllCaches) {
         ForgetAllCacheUtil::forgetAllCaches();
     }
     if (empty($cacheDirectories)) {
         $cacheDirectories = static::resolveCacheDirectoryPaths();
     }
     foreach ($cacheDirectories as $cacheDirectory) {
         static::clearCacheDirectory($cacheDirectory);
     }
 }
 public function setup()
 {
     ForgetAllCacheUtil::forgetAllCaches();
     //Special situation to deal with email box and ensuring the user cache doesn't get corrupted
     parent::setup();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     if (EmailMessageTestHelper::isSetEmailAccountsTestConfiguration()) {
         $user = User::getByUsername('steve');
         $user->primaryEmail->emailAddress = Yii::app()->params['emailTestAccounts']['userImapSettings']['imapUsername'];
         $this->assertTrue($user->save());
     }
 }
 /**
  * Clear cache
  */
 protected static function clearCache()
 {
     ForgetAllCacheUtil::forgetAllCaches();
 }
    public function generateAndProcessCampaignItems($count)
    {
        $contacts = array();
        $emails = array();
        for ($i = 0; $i < $count; $i++) {
            $emails[$i] = new Email();
            $emails[$i]->emailAddress = "demo{$i}@zurmo.com";
            $account = AccountTestHelper::createAccountByNameForOwner('account ' . $i, $this->user);
            $contact = ContactTestHelper::createContactWithAccountByNameForOwner('contact ' . $i, $this->user, $account);
            $contact->primaryEmail = $emails[$i];
            $this->assertTrue($contact->save());
            $contacts[$i] = $contact;
        }
        $content = <<<MTG
[[COMPANY^NAME]]
[[CREATED^DATE^TIME]]
[[DEPARTMENT]]
[[DESCRIPTION]]
[[FIRST^NAME]]
[[GOOGLE^WEB^TRACKING^ID]]
[[INDUSTRY]]
[[JOB^TITLE]]
[[LAST^NAME]]
[[LATEST^ACTIVITY^DATE^TIME]]
[[MOBILE^PHONE]]
[[MODIFIED^DATE^TIME]]
[[OFFICE^FAX]]
[[OFFICE^PHONE]]
[[TITLE]]
[[SOURCE]]
[[STATE]]
[[WEBSITE]]
[[MODEL^URL]]
[[BASE^URL]]
[[APPLICATION^NAME]]
[[CURRENT^YEAR]]
[[LAST^YEAR]]
[[OWNERS^AVATAR^SMALL]]
[[OWNERS^AVATAR^MEDIUM]]
[[OWNERS^AVATAR^LARGE]]
[[OWNERS^EMAIL^SIGNATURE]]
[[UNSUBSCRIBE^URL]]
[[MANAGE^SUBSCRIPTIONS^URL]]
[[PRIMARY^EMAIL__EMAIL^ADDRESS]]
[[PRIMARY^EMAIL__EMAIL^ADDRESS]]
[[SECONDARY^ADDRESS__CITY]]
[[SECONDARY^ADDRESS__COUNTRY]]
[[SECONDARY^ADDRESS__INVALID]]
[[SECONDARY^ADDRESS__LATITUDE]]
[[SECONDARY^ADDRESS__LONGITUDE]]
[[SECONDARY^ADDRESS__POSTAL^CODE]]
[[SECONDARY^ADDRESS__STATE]]
[[SECONDARY^ADDRESS__STREET1]]
[[SECONDARY^ADDRESS__STREET2]]
[[OWNER__DEPARTMENT]]
[[OWNER__FIRST^NAME]]
[[OWNER__IS^ACTIVE]]
[[OWNER__MOBILE^PHONE]]
[[OWNER__LAST^LOGIN^DATE^TIME]]
[[OWNER__LAST^NAME]]
[[CREATED^BY^USER__FIRST^NAME]]
[[CREATED^BY^USER__LAST^NAME]]
[[CREATED^BY^USER__MOBILE^PHONE]]
[[CREATED^BY^USER__TITLE]]
[[CREATED^BY^USER__USERNAME]]
[[ACCOUNT__ANNUAL^REVENUE]]
[[ACCOUNT__INDUSTRY]]
[[ACCOUNT__NAME]]
[[ACCOUNT__WEBSITE]]
[[ACCOUNT__BILLING^ADDRESS__COUNTRY]]
[[ACCOUNT__BILLING^ADDRESS__CITY]]
[[ACCOUNT__OWNER__FIRST^NAME]]
 ' " ` " '
MTG;
        $marketingList = MarketingListTestHelper::createMarketingListByName('marketingList Test', 'description goes here', 'fromName', '*****@*****.**');
        $campaign = CampaignTestHelper::createCampaign('campaign Test', 'subject', $content, $content, null, null, null, Campaign::STATUS_PROCESSING, null, null, $marketingList, false);
        $fileNames = array('testImage.png', 'testZip.zip', 'testPDF.pdf');
        $files = array();
        foreach ($fileNames as $index => $fileName) {
            $file = ZurmoTestHelper::createFileModel($fileName);
            $files[$index]['name'] = $fileName;
            $files[$index]['type'] = $file->type;
            $files[$index]['size'] = $file->size;
            $files[$index]['contents'] = $file->fileContent->content;
            $campaign->files->add($file);
        }
        $this->assertTrue($campaign->save(false));
        $processed = 0;
        foreach ($contacts as $contact) {
            MarketingListMemberTestHelper::createMarketingListMember(0, $marketingList, $contact);
            CampaignItemTestHelper::createCampaignItem($processed, $campaign, $contact);
        }
        AutoresponderOrCampaignBatchSizeConfigUtil::setBatchSize($count);
        Yii::app()->jobQueue->deleteAll();
        ForgetAllCacheUtil::forgetAllCaches();
        $job = new CampaignQueueMessagesInOutboxJob();
        $this->assertCount(0, Yii::app()->jobQueue->getAll());
        $startedAt = microtime(true);
        $this->assertTrue($job->run());
        $timeTaken = microtime(true) - $startedAt;
        ForgetAllCacheUtil::forgetAllCaches();
        $campaignItemsCountExpected = $count;
        $campaignItemsCountAfter = CampaignItem::getCount();
        $this->assertEquals($campaignItemsCountExpected, $campaignItemsCountAfter);
        $campaignItemsProcessed = CampaignItem::getByProcessedAndCampaignId(1, $campaign->id);
        $this->assertCount($count, $campaignItemsProcessed);
        foreach ($campaignItemsProcessed as $i => $campaignItem) {
            $contact = $contacts[$i];
            $email = $emails[$i];
            $emailMessage = $campaignItem->emailMessage;
            $this->assertEquals($marketingList->owner->id, $emailMessage->owner->id);
            $marketingListPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($marketingList);
            $emailMessagePermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($emailMessage);
            $this->assertEquals($marketingListPermissions, $emailMessagePermissions);
            $this->assertEquals($campaign->subject, $emailMessage->subject);
            $this->assertNotEquals($campaign->textContent, $emailMessage->content->textContent);
            $this->assertNotEquals($campaign->htmlContent, $emailMessage->content->htmlContent);
            $this->assertEquals(2, substr_count($emailMessage->content->textContent, '/marketingLists/external/'));
            $this->assertContains('/marketingLists/external/', $emailMessage->content->htmlContent);
            $this->assertEquals(2, substr_count($emailMessage->content->htmlContent, '/marketingLists/external/'));
            $this->assertEquals('*****@*****.**', $emailMessage->sender->fromAddress);
            $this->assertEquals('Support Team', $emailMessage->sender->fromName);
            $this->assertEquals(1, $emailMessage->recipients->count());
            $recipients = $emailMessage->recipients;
            $this->assertEquals(strval($contact), $recipients[0]->toName);
            $this->assertEquals($email->emailAddress, $recipients[0]->toAddress);
            $this->assertEquals(EmailMessageRecipient::TYPE_TO, $recipients[0]->type);
            $this->assertNotEmpty($emailMessage->files);
            $this->assertCount(count($files), $emailMessage->files);
            foreach ($campaign->files as $index => $file) {
                $this->assertEquals($file->name, $emailMessage->files[$index]->name);
                $this->assertEquals($file->type, $emailMessage->files[$index]->type);
                $this->assertEquals($file->size, $emailMessage->files[$index]->size);
                //CampaingItem should share the Attachments content from Campaign
                $this->assertEquals($file->fileContent->content, $emailMessage->files[$index]->fileContent->content);
                $this->assertEquals($file->fileContent->id, $emailMessage->files[$index]->fileContent->id);
            }
            $headersArray = array('zurmoItemId' => $campaignItem->id, 'zurmoItemClass' => get_class($campaignItem), 'zurmoPersonId' => $contact->getClassId('Person'));
            $expectedHeaders = serialize($headersArray);
            $this->assertEquals($expectedHeaders, $emailMessage->headers);
        }
        return $timeTaken;
    }
 /**
  * @depends testRunWithContactContainingPrimaryEmailOptedOut
  */
 public function testRunWithMultipleRecipientsWithAttachments()
 {
     $campaignItemsCountBefore = CampaignItem::getCount();
     $job = new CampaignQueueMessagesInOutboxJob();
     $contacts = array();
     for ($i = 0; $i < 5; $i++) {
         $email = new Email();
         $email->emailAddress = "demo{$i}@zurmo.com";
         $contact = ContactTestHelper::createContactByNameForOwner('contact 0' . ($i + 8), $this->user);
         $contact->primaryEmail = $email;
         $this->assertTrue($contact->save());
         $contacts[] = $contact;
     }
     $marketingList = MarketingListTestHelper::createMarketingListByName('marketingList 09', 'description goes here', 'fromName', '*****@*****.**');
     $campaign = CampaignTestHelper::createCampaign('campaign 09', 'subject', '[[FIRST^NAME]]', '[[LAST^NAME]]', null, null, null, Campaign::STATUS_PROCESSING, null, null, $marketingList);
     $fileNames = array('testImage.png', 'testZip.zip', 'testPDF.pdf');
     $files = array();
     foreach ($fileNames as $index => $fileName) {
         $file = ZurmoTestHelper::createFileModel($fileName);
         $files[$index]['name'] = $fileName;
         $files[$index]['type'] = $file->type;
         $files[$index]['size'] = $file->size;
         $files[$index]['contents'] = $file->fileContent->content;
         $campaign->files->add($file);
     }
     $this->assertTrue($campaign->save());
     $processed = 0;
     foreach ($contacts as $contact) {
         MarketingListMemberTestHelper::createMarketingListMember(0, $marketingList, $contact);
         CampaignItemTestHelper::createCampaignItem($processed, $campaign, $contact);
     }
     $this->assertTrue($job->run());
     ForgetAllCacheUtil::forgetAllCaches();
     $campaignItemsCountExpected = $campaignItemsCountBefore + 5;
     $campaignItemsCountAfter = CampaignItem::getCount();
     $this->assertEquals($campaignItemsCountExpected, $campaignItemsCountAfter);
     $campaignItemsProcessed = CampaignItem::getByProcessedAndCampaignId(1, $campaign->id);
     $this->assertCount(5, $campaignItemsProcessed);
     foreach ($campaignItemsProcessed as $campaignItem) {
         $emailMessage = $campaignItem->emailMessage;
         $this->assertNotEmpty($emailMessage->files);
         $this->assertCount(count($files), $emailMessage->files);
         foreach ($files as $index => $file) {
             $this->assertEquals($files[$index]['name'], $emailMessage->files[$index]->name);
             $this->assertEquals($files[$index]['type'], $emailMessage->files[$index]->type);
             $this->assertEquals($files[$index]['size'], $emailMessage->files[$index]->size);
             $this->assertEquals($files[$index]['contents'], $emailMessage->files[$index]->fileContent->content);
         }
     }
 }
 /**
  * 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();
     static::autoBuildDatabase($messageLogger);
     // 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;
 }
 public function testRunAndProcessStuckJobs()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $emailAddress = new Email();
     $emailAddress->emailAddress = '*****@*****.**';
     Yii::app()->user->userModel->primaryEmail = $emailAddress;
     $saved = Yii::app()->user->userModel->save();
     $this->assertTrue($saved);
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $monitorJob = new MonitorJob();
     $this->assertEquals(0, JobInProcess::getCount());
     $this->assertEquals(0, StuckJob::getCount());
     $this->assertEquals(0, Notification::getCount());
     $this->assertEquals(0, EmailMessage::getCount());
     $jobInProcess = new JobInProcess();
     $jobInProcess->type = 'Test';
     $this->assertTrue($jobInProcess->save());
     //Should make createdDateTime long enough in past to trigger as stuck.
     $createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 10000);
     $sql = "Update item set createddatetime = '" . $createdDateTime . "' where id = " . $jobInProcess->getClassId('Item');
     ZurmoRedBean::exec($sql);
     $jobInProcess->forget();
     $monitorJob->run();
     $this->assertEquals(0, JobInProcess::getCount());
     //should still be 0 but the quantity should increase
     $this->assertEquals(0, Notification::getCount());
     //There should now be one stuck job with quantity 1
     $stuckJobs = StuckJob::getAll();
     $this->assertEquals(1, count($stuckJobs));
     $this->assertEquals('Test', $stuckJobs[0]->type);
     $this->assertEquals(1, $stuckJobs[0]->quantity);
     //Now it should increase to 2
     $jobInProcess = new JobInProcess();
     $jobInProcess->type = 'Test';
     $this->assertTrue($jobInProcess->save());
     //Should make createdDateTime long enough in past to trigger as stuck.
     $createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 10000);
     $sql = "Update item set createddatetime = '" . $createdDateTime . "' where id = " . $jobInProcess->getClassId('Item');
     ZurmoRedBean::exec($sql);
     $jobInProcess->forget();
     $monitorJob->run();
     $this->assertEquals(0, JobInProcess::getCount());
     //should still be 0 but the quantity should increase
     $this->assertEquals(0, Notification::getCount());
     //There should now be one stuck job with quantity 1
     $stuckJobs = StuckJob::getAll();
     $this->assertEquals(1, count($stuckJobs));
     $this->assertEquals('Test', $stuckJobs[0]->type);
     $this->assertEquals(2, $stuckJobs[0]->quantity);
     //Set quantity to 3, then run monitor again and notification should go out.
     $stuckJobs[0]->quantity = 3;
     $this->assertTrue($stuckJobs[0]->save());
     $jobInProcess = new JobInProcess();
     $jobInProcess->type = 'Test';
     $this->assertTrue($jobInProcess->save());
     //Should make createdDateTime long enough in past to trigger as stuck.
     $createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 10000);
     $sql = "Update item set createddatetime = '" . $createdDateTime . "' where id = " . $jobInProcess->getClassId('Item');
     ZurmoRedBean::exec($sql);
     $jobInProcess->forget();
     //Now the threshold of 4 should be reached and we should send a notification
     $monitorJob->run();
     ForgetAllCacheUtil::forgetAllCaches();
     $stuckJobs = StuckJob::getAll();
     $this->assertEquals(1, count($stuckJobs));
     $this->assertEquals('Test', $stuckJobs[0]->type);
     $this->assertEquals(4, $stuckJobs[0]->quantity);
     $this->assertEquals(1, Notification::getCount());
     //Confirm an email was sent
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(1, EmailMessage::getCount());
     $this->assertEquals(1, Yii::app()->emailHelper->getSentCount());
 }
 /**
  * Upgrade step two:
  */
 public function actionStepTwo()
 {
     // Upgrade process can take much time, because upgrade schema script.
     // Set timeout for upgrade to 12 hours.
     set_time_limit(12 * 60 * 60);
     Yii::app()->gameHelper->muteScoringModelsOnSave();
     $nextView = new UpgradeStepTwoCompleteView($this->getId(), $this->getModule()->getId());
     $view = new InstallPageView($nextView);
     echo $view->render();
     $template = ZurmoHtml::script("\$('#logging-table').prepend('{message}<br/>');");
     $messageStreamer = new MessageStreamer($template);
     $messageStreamer->setExtraRenderBytes(4096);
     $messageStreamer->add(Zurmo::t('InstallModule', 'Starting upgrade process.'));
     UpgradeUtil::runPart2($messageStreamer);
     ForgetAllCacheUtil::forgetAllCaches();
     echo ZurmoHtml::script('$("#progress-table").hide(); $("#upgrade-step-two").show();');
     Yii::app()->gameHelper->unmuteScoringModelsOnSave();
 }
 public function testCloneSetsRightPermissions()
 {
     // create users and groups.
     $everyoneGroup = Group::getByName(Group::EVERYONE_GROUP_NAME);
     $everyoneGroup->setRight('ReportsModule', ReportsModule::getAccessRight());
     $everyoneGroup->setRight('AccountsModule', AccountsModule::RIGHT_ACCESS_ACCOUNTS);
     $this->assertTrue($everyoneGroup->save());
     $everyoneGroup->forgetAll();
     $jim = UserTestHelper::createBasicUser('jim');
     $john = UserTestHelper::createBasicUser('john');
     $johnGroup = new Group();
     $johnGroup->name = 'John Group';
     $johnGroup->users->add($john);
     $this->assertTrue($johnGroup->save());
     $john->forgetAll();
     $johnGroup->forgetAll();
     $john = User::getByUsername('john');
     $johnGroup = Group::getByName('John Group');
     $basePostData = static::makeRowsAndColumnsReportPostDataForAccounts();
     $basePostData['save'] = 'save';
     $description = StringUtil::generateRandomString(40);
     // create a report with everyone group permission, ensure everyone can access it.
     // clone it, ensure everyone group can still access it.
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     SavedReport::deleteAll();
     $modelSpecificPostData = array('RowsAndColumnsReportWizardForm' => array('name' => 'Everyone Report 01', 'description' => $description, 'ownerId' => $super->id, 'ownerName' => strval($super), 'explicitReadWriteModelPermissions' => array('type' => ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_EVERYONE_GROUP, 'nonEveryoneGroup' => null)));
     $postData = CMap::mergeArray($basePostData, $modelSpecificPostData);
     $this->setGetArray(array('type' => 'RowsAndColumns'));
     $this->setPostArray($postData);
     $this->runControllerWithExitExceptionAndGetContent('/reports/default/save');
     ForgetAllCacheUtil::forgetAllCaches();
     $savedReports = SavedReport::getAll();
     $this->assertCount(1, $savedReports);
     $this->assertEquals(Permission::ALL, $savedReports[0]->getEffectivePermissions($super));
     $this->assertEquals(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, $savedReports[0]->getEffectivePermissions($everyoneGroup));
     $this->assertEquals(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, $savedReports[0]->getEffectivePermissions($jim));
     // ensure jim can access it.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername('jim');
     $this->resetPostArray();
     $this->resetGetArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/list');
     $this->assertContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->assertEquals(substr_count($content, $postData['RowsAndColumnsReportWizardForm']['name']), 1);
     $this->setGetArray(array('id' => $savedReports[0]->id));
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/details');
     $this->assertContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->assertEquals(substr_count($content, $postData['RowsAndColumnsReportWizardForm']['name']), 3);
     // clone the report.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $this->setGetArray(array('type' => 'RowsAndColumns', 'id' => $savedReports[0]->id, 'isBeingCopied' => '1'));
     $postData['RowsAndColumnsReportWizardForm']['name'] = 'Cloned ' . $postData['RowsAndColumnsReportWizardForm']['name'];
     $this->setPostArray($postData);
     $this->runControllerWithExitExceptionAndGetContent('/reports/default/save');
     ForgetAllCacheUtil::forgetAllCaches();
     $savedReports = SavedReport::getAll();
     $this->assertCount(2, $savedReports);
     $sourcePermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($savedReports[0]);
     $clonePermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($savedReports[1]);
     $this->assertEquals($sourcePermissions, $clonePermissions);
     $this->assertEquals(Permission::ALL, $savedReports[1]->getEffectivePermissions($super));
     $this->assertEquals(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, $savedReports[1]->getEffectivePermissions($everyoneGroup));
     $this->assertEquals(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, $savedReports[1]->getEffectivePermissions($jim));
     // ensure jim can access it.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername('jim');
     $this->resetPostArray();
     $this->resetGetArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/list');
     $this->assertContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->assertEquals(substr_count($content, $postData['RowsAndColumnsReportWizardForm']['name']), 1);
     $this->setGetArray(array('id' => $savedReports[1]->id));
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/details');
     $this->assertContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->assertEquals(substr_count($content, $postData['RowsAndColumnsReportWizardForm']['name']), 3);
     // create a report with specific group permissions, ensure only members of that group can access it.
     // clone it, ensure only that specific group members can access it.
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     SavedReport::deleteAll();
     $modelSpecificPostData = array('RowsAndColumnsReportWizardForm' => array('name' => 'Group Specific Report 01', 'description' => $description, 'ownerId' => $super->id, 'ownerName' => strval($super), 'explicitReadWriteModelPermissions' => array('type' => ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_NONEVERYONE_GROUP, 'nonEveryoneGroup' => $johnGroup->id)));
     $postData = CMap::mergeArray($basePostData, $modelSpecificPostData);
     $this->setGetArray(array('type' => 'RowsAndColumns'));
     $this->setPostArray($postData);
     $this->runControllerWithExitExceptionAndGetContent('/reports/default/save');
     ForgetAllCacheUtil::forgetAllCaches();
     $savedReports = SavedReport::getAll();
     $this->assertCount(1, $savedReports);
     $this->assertEquals(Permission::ALL, $savedReports[0]->getEffectivePermissions($super));
     $this->assertEquals(Permission::NONE, $savedReports[0]->getEffectivePermissions($everyoneGroup));
     $this->assertEquals(Permission::NONE, $savedReports[0]->getEffectivePermissions($jim));
     $this->assertEquals(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, $savedReports[0]->getEffectivePermissions($johnGroup));
     $this->assertEquals(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, $savedReports[0]->getEffectivePermissions($john));
     // ensure john can access it.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername('john');
     $this->resetPostArray();
     $this->resetGetArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/list');
     $this->assertContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->assertEquals(substr_count($content, $postData['RowsAndColumnsReportWizardForm']['name']), 1);
     $this->setGetArray(array('id' => $savedReports[0]->id));
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/details');
     $this->assertContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->assertEquals(substr_count($content, $postData['RowsAndColumnsReportWizardForm']['name']), 3);
     // ensure jim can not access it.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername('jim');
     $this->resetGetArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/list');
     $this->assertNotContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->setGetArray(array('id' => $savedReports[0]->id));
     $this->runControllerWithAccessDeniedSecurityExceptionAndGetContent('/reports/default/details');
     // clone the report.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $this->setGetArray(array('type' => 'RowsAndColumns', 'id' => $savedReports[0]->id, 'isBeingCopied' => '1'));
     $postData['RowsAndColumnsReportWizardForm']['name'] = 'Cloned ' . $postData['RowsAndColumnsReportWizardForm']['name'];
     $this->setPostArray($postData);
     $this->runControllerWithExitExceptionAndGetContent('/reports/default/save');
     ForgetAllCacheUtil::forgetAllCaches();
     $savedReports = SavedReport::getAll();
     $this->assertCount(2, $savedReports);
     $sourcePermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($savedReports[0]);
     $clonePermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($savedReports[1]);
     $this->assertEquals($sourcePermissions, $clonePermissions);
     $this->assertEquals(Permission::ALL, $savedReports[1]->getEffectivePermissions($super));
     $this->assertEquals(Permission::NONE, $savedReports[1]->getEffectivePermissions($everyoneGroup));
     $this->assertEquals(Permission::NONE, $savedReports[1]->getEffectivePermissions($jim));
     $this->assertEquals(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, $savedReports[1]->getEffectivePermissions($johnGroup));
     $this->assertEquals(Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER, $savedReports[1]->getEffectivePermissions($john));
     // ensure john can access it.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername('john');
     $this->resetPostArray();
     $this->resetGetArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/list');
     $this->assertContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->assertEquals(substr_count($content, $postData['RowsAndColumnsReportWizardForm']['name']), 1);
     $this->setGetArray(array('id' => $savedReports[1]->id));
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/details');
     $this->assertContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->assertEquals(substr_count($content, $postData['RowsAndColumnsReportWizardForm']['name']), 3);
     // ensure jim can not access it.
     $this->logoutCurrentUserLoginNewUserAndGetByUsername('jim');
     $this->resetGetArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('/reports/default/list');
     $this->assertNotContains($postData['RowsAndColumnsReportWizardForm']['name'], $content);
     $this->setGetArray(array('id' => $savedReports[0]->id));
     $this->runControllerWithAccessDeniedSecurityExceptionAndGetContent('/reports/default/details');
 }
 /**
  * In the case where you have reloaded the database, some cached items might still exist.  This is a way
  * to clear that cache. Helpful during development and testing.
  */
 public function handleClearCache($event)
 {
     if (isset($_GET['clearCache']) && $_GET['clearCache'] == 1) {
         ForgetAllCacheUtil::forgetAllCaches();
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     // we are using some hardcoded Ids, we need fresh tables so these Ids are what we expect, rebuild:
     ForgetAllCacheUtil::forgetAllCaches();
     ZurmoRedBean::$writer->wipeAll();
     InstallUtil::autoBuildDatabase(new MessageLogger(), true);
     // This is setting up users and groups to match Jason's
     // powerpoint workings out of how the munge should look
     // after each operation. Things are set up in the order
     // that will give them the right ids to have munge ids
     // that match the document. The names are adjusted
     // to conform to the minimum lengths and casing in
     // the models. This the basic set up that is almost
     // right for many of the tests, and each test does
     // whatever it needs to to make the exactly what it
     // needs AND puts it back how it found it.
     $u1 = new User();
     $u1->username = '******';
     $u1->lastName = 'U1';
     $saved = $u1->save();
     assert('$saved');
     // Not Coding Standard
     assert('$u1->id == 1');
     // Not Coding Standard
     $u2 = new User();
     $u2->username = '******';
     $u2->lastName = 'U2';
     $saved = $u2->save();
     assert('$saved');
     // Not Coding Standard
     assert('$u2->id == 2');
     // Not Coding Standard
     $u3 = new User();
     $u3->username = '******';
     $u3->lastName = 'U3';
     $saved = $u3->save();
     assert('$saved');
     // Not Coding Standard
     assert('$u3->id == 3');
     // Not Coding Standard
     $u4 = new User();
     $u4->username = '******';
     $u4->lastName = 'U4';
     $saved = $u4->save();
     assert('$saved');
     // Not Coding Standard
     assert('$u4->id == 4');
     // Not Coding Standard
     $u5 = new User();
     $u5->username = '******';
     $u5->lastName = 'U5';
     $saved = $u5->save();
     assert('$saved');
     // Not Coding Standard
     assert('$u5->id == 5');
     // Not Coding Standard
     $u6 = new User();
     $u6->username = '******';
     $u6->lastName = 'U6';
     $saved = $u6->save();
     assert('$saved');
     // Not Coding Standard
     assert('$u6->id == 6');
     // Not Coding Standard
     $u99 = new User();
     // A user with no roles
     $u99->username = '******';
     // that can create accounts
     $u99->lastName = 'U99';
     // without having any
     $saved = $u99->save();
     // effect on the munge.
     assert('$saved');
     // Not Coding Standard
     $g1 = new Group();
     $g1->name = 'G1.';
     $saved = $g1->save();
     assert('$saved');
     // Not Coding Standard
     assert('$g1->id == 1');
     // Not Coding Standard
     $g2 = new Group();
     $g2->name = 'G2.';
     $saved = $g2->save();
     assert('$saved');
     // Not Coding Standard
     assert('$g2->id == 2');
     // Not Coding Standard
     $g3 = new Group();
     $g3->name = 'G3.';
     $saved = $g3->save();
     assert('$saved');
     // Not Coding Standard
     assert('$g3->id == 3');
     // Not Coding Standard
     $r1 = new Role();
     $r1->name = 'R1.';
     $saved = $r1->save();
     assert('$saved');
     // Not Coding Standard
     assert('$r1->id == 1');
     // Not Coding Standard
     $r2 = new Role();
     $r2->name = 'R2.';
     $saved = $r2->save();
     assert('$saved');
     // Not Coding Standard
     assert('$r2->id == 2');
     // Not Coding Standard
     $r3 = new Role();
     $r3->name = 'R3.';
     $saved = $r3->save();
     assert('$saved');
     // Not Coding Standard
     assert('$r3->id == 3');
     // Not Coding Standard
     $r4 = new Role();
     $r4->name = 'R4.';
     $saved = $r4->save();
     assert('$saved');
     // Not Coding Standard
     assert('$r4->id == 4');
     // Not Coding Standard
     $r5 = new Role();
     $r5->name = 'R5.';
     $saved = $r5->save();
     assert('$saved');
     // Not Coding Standard
     assert('$r5->id == 5');
     // Not Coding Standard
     $r6 = new Role();
     $r6->name = 'R6.';
     $saved = $r6->save();
     assert('$saved');
     // Not Coding Standard
     assert('$r6->id == 6');
     // Not Coding Standard
     $r3->roles->add($r2);
     $r2->roles->add($r1);
     $r6->roles->add($r5);
     $r5->roles->add($r4);
     $u1->role = $r1;
     $u2->role = $r4;
     $u3->role = $r4;
     $u4->role = $r4;
     $saved = $r3->save();
     assert('$saved');
     // Not Coding Standard
     $saved = $r2->save();
     assert('$saved');
     // Not Coding Standard
     $saved = $r6->save();
     assert('$saved');
     // Not Coding Standard
     $saved = $r5->save();
     assert('$saved');
     // Not Coding Standard
     $saved = $u1->save();
     assert('$saved');
     // Not Coding Standard
     $saved = $u2->save();
     assert('$saved');
     // Not Coding Standard
     $saved = $u3->save();
     assert('$saved');
     // Not Coding Standard
     $saved = $u4->save();
     assert('$saved');
     // Not Coding Standard
     //Add contacts to help test that the rebuild is working correctly
     $contact = ContactTestHelper::createContactByNameForOwner('jason', Yii::app()->user->userModel);
     $contact->addPermissions($u2, Permission::READ);
     $contact->addPermissions($g2, Permission::READ);
     $saved = $contact->save();
     assert('$saved');
     // Not Coding Standard
     ReadPermissionsOptimizationUtil::rebuild();
     assert('self::getAccountMungeRowCount() == 0');
     // Not Coding Standard
     RedBeanModel::forgetAll();
     self::assertEverythingHasBeenSetBackToHowItStarted();
 }
    public function generateCampaignItemsForDueCampaigns($count)
    {
        $marketingList = MarketingListTestHelper::createMarketingListByName('marketingList Test', 'description goes here', 'fromName', '*****@*****.**');
        $marketingListId = $marketingList->id;
        $contacts = array();
        $emails = array();
        for ($i = 0; $i < $count; $i++) {
            $emails[$i] = new Email();
            $emails[$i]->emailAddress = "demo{$i}@zurmo.com";
            $account = AccountTestHelper::createAccountByNameForOwner('account ' . $i, $this->user);
            $contact = ContactTestHelper::createContactWithAccountByNameForOwner('contact ' . $i, $this->user, $account);
            $contact->primaryEmail = $emails[$i];
            $this->assertTrue($contact->save());
            $contacts[$i] = $contact;
            MarketingListMemberTestHelper::createMarketingListMember(0, $marketingList, $contact);
        }
        $marketingList->forgetAll();
        $marketingList = MarketingList::getById($marketingListId);
        $content = <<<MTG
[[COMPANY^NAME]]
[[CREATED^DATE^TIME]]
[[DEPARTMENT]]
[[DESCRIPTION]]
[[FIRST^NAME]]
[[GOOGLE^WEB^TRACKING^ID]]
[[INDUSTRY]]
[[JOB^TITLE]]
[[LAST^NAME]]
[[LATEST^ACTIVITY^DATE^TIME]]
[[MOBILE^PHONE]]
[[MODIFIED^DATE^TIME]]
[[OFFICE^FAX]]
[[OFFICE^PHONE]]
[[TITLE]]
[[SOURCE]]
[[STATE]]
[[WEBSITE]]
[[MODEL^URL]]
[[BASE^URL]]
[[APPLICATION^NAME]]
[[CURRENT^YEAR]]
[[LAST^YEAR]]
[[OWNERS^AVATAR^SMALL]]
[[OWNERS^AVATAR^MEDIUM]]
[[OWNERS^AVATAR^LARGE]]
[[OWNERS^EMAIL^SIGNATURE]]
[[UNSUBSCRIBE^URL]]
[[MANAGE^SUBSCRIPTIONS^URL]]
[[PRIMARY^EMAIL__EMAIL^ADDRESS]]
[[PRIMARY^EMAIL__EMAIL^ADDRESS]]
[[SECONDARY^ADDRESS__CITY]]
[[SECONDARY^ADDRESS__COUNTRY]]
[[SECONDARY^ADDRESS__INVALID]]
[[SECONDARY^ADDRESS__LATITUDE]]
[[SECONDARY^ADDRESS__LONGITUDE]]
[[SECONDARY^ADDRESS__POSTAL^CODE]]
[[SECONDARY^ADDRESS__STATE]]
[[SECONDARY^ADDRESS__STREET1]]
[[SECONDARY^ADDRESS__STREET2]]
[[OWNER__DEPARTMENT]]
[[OWNER__FIRST^NAME]]
[[OWNER__IS^ACTIVE]]
[[OWNER__MOBILE^PHONE]]
[[OWNER__LAST^LOGIN^DATE^TIME]]
[[OWNER__LAST^NAME]]
[[CREATED^BY^USER__FIRST^NAME]]
[[CREATED^BY^USER__LAST^NAME]]
[[CREATED^BY^USER__MOBILE^PHONE]]
[[CREATED^BY^USER__TITLE]]
[[CREATED^BY^USER__USERNAME]]
[[ACCOUNT__ANNUAL^REVENUE]]
[[ACCOUNT__INDUSTRY]]
[[ACCOUNT__NAME]]
[[ACCOUNT__WEBSITE]]
[[ACCOUNT__BILLING^ADDRESS__COUNTRY]]
[[ACCOUNT__BILLING^ADDRESS__CITY]]
[[ACCOUNT__OWNER__FIRST^NAME]]
 ' " ` " '
MTG;
        $sendOnDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 600);
        $campaign = CampaignTestHelper::createCampaign('campaign Test', 'subject', $content, $content, null, null, null, Campaign::STATUS_ACTIVE, $sendOnDateTime, null, $marketingList, false);
        $fileNames = array('testImage.png', 'testZip.zip', 'testPDF.pdf');
        $files = array();
        foreach ($fileNames as $index => $fileName) {
            $file = ZurmoTestHelper::createFileModel($fileName);
            $files[$index]['name'] = $fileName;
            $files[$index]['type'] = $file->type;
            $files[$index]['size'] = $file->size;
            $files[$index]['contents'] = $file->fileContent->content;
            $campaign->files->add($file);
        }
        $this->assertTrue($campaign->save(false));
        $campaignId = $campaign->id;
        $campaign->forgetAll();
        $campaignItems = CampaignItem::getByProcessedAndCampaignId(0, $campaignId);
        $this->assertEmpty($campaignItems);
        //Process open campaigns.
        Yii::app()->jobQueue->deleteAll();
        AutoresponderOrCampaignBatchSizeConfigUtil::setBatchSize($count);
        Yii::app()->jobQueue->deleteAll();
        $this->assertCount(0, Yii::app()->jobQueue->getAll());
        ForgetAllCacheUtil::forgetAllCaches();
        $job = new CampaignGenerateDueCampaignItemsJob();
        $startedAt = microtime(true);
        $this->assertTrue($job->run());
        $timeTaken = microtime(true) - $startedAt;
        ForgetAllCacheUtil::forgetAllCaches();
        $campaign->forgetAll();
        unset($campaign);
        $campaign = Campaign::getById($campaignId);
        $this->assertNotNull($campaign);
        $this->assertEquals(Campaign::STATUS_PROCESSING, $campaign->status);
        $campaignItems = CampaignItem::getByProcessedAndCampaignId(0, $campaignId);
        $this->assertNotEmpty($campaignItems);
        $this->assertCount($count, $campaignItems);
        return $timeTaken;
    }
Example #14
0
 /**
  * Added forgetAllCaches in case you are debugging and want to run this action again with a saved db.
  */
 public function actionInstallDemoData()
 {
     RedBeanDatabase::setup(Yii::app()->db->connectionString, Yii::app()->db->username, Yii::app()->db->password);
     InstallUtil::freezeDatabase();
     ForgetAllCacheUtil::forgetAllCaches();
     Yii::app()->user->userModel = User::getByUsername('super');
     $nextView = new InstallCompleteView($this->getId(), $this->getModule()->getId());
     $view = new InstallPageView($nextView);
     echo $view->render();
     $template = ZurmoHtml::script("\$('#logging-table').prepend('{message}<br/>');");
     $messageStreamer = new MessageStreamer($template);
     $messageStreamer->add(Zurmo::t('InstallModule', 'Starting to load demo data.'));
     $messageLogger = new MessageLogger($messageStreamer);
     DemoDataUtil::load($messageLogger, 6);
     $messageStreamer->add(Zurmo::t('InstallModule', 'Finished loading demo data.'));
     $messageStreamer->add(Zurmo::t('InstallModule', 'Locking Installation.'));
     InstallUtil::writeInstallComplete(INSTANCE_ROOT);
     ForgetAllCacheUtil::forgetAllCaches();
     echo ZurmoHtml::script('$("#progress-table").hide(); $("#complete-table").show();');
 }
 public function generateAndProcessEmailMessages($count)
 {
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $outboxFolder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_OUTBOX);
     $sentFolder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_SENT);
     $fileNames = array('testImage.png', 'testZip.zip', 'testPDF.pdf');
     $emailMessageIds = array();
     $files = array();
     for ($i = 0; $i < $count; $i++) {
         $emailMessage = EmailMessageTestHelper::createDraftSystemEmail('My Email Message ' . $i, $this->user);
         foreach ($fileNames as $index => $fileName) {
             $file = ZurmoTestHelper::createFileModel($fileName);
             $files[$index]['name'] = $fileName;
             $files[$index]['type'] = $file->type;
             $files[$index]['size'] = $file->size;
             $files[$index]['contents'] = $file->fileContent->content;
             $emailMessage->files->add($file);
         }
         $emailMessage->folder = $outboxFolder;
         $saved = $emailMessage->save(false);
         $this->assertTrue($saved);
         $emailMessageIds[] = $emailMessage->id;
         $emailMessage->forget();
         unset($emailMessage);
     }
     OutboundEmailBatchSizeConfigUtil::setBatchSize($count + 1);
     Yii::app()->jobQueue->deleteAll();
     ForgetAllCacheUtil::forgetAllCaches();
     $job = new ProcessOutboundEmailJob();
     $startedAt = microtime(true);
     $this->assertTrue($job->run());
     $timeTaken = microtime(true) - $startedAt;
     ForgetAllCacheUtil::forgetAllCaches();
     $emailMessages = EmailMessage::getAll();
     $this->assertEquals($count, count($emailMessages));
     foreach ($emailMessageIds as $i => $emailMessageId) {
         $emailMessage = EmailMessage::getById($emailMessageId);
         $this->assertEquals('My Email Message ' . $i, $emailMessage->subject);
         $this->assertEquals(1, $emailMessage->sendAttempts);
         $this->assertEquals($sentFolder->id, $emailMessage->folder->id);
         $this->assertNotEmpty($emailMessage->files);
         $this->assertCount(count($files), $emailMessage->files);
         foreach ($emailMessage->files as $index => $file) {
             $this->assertEquals($file->name, $emailMessage->files[$index]->name);
             $this->assertEquals($file->type, $emailMessage->files[$index]->type);
             $this->assertEquals($file->size, $emailMessage->files[$index]->size);
             $this->assertEquals($file->fileContent->content, $emailMessage->files[$index]->fileContent->content);
             $this->assertEquals($file->fileContent->id, $emailMessage->files[$index]->fileContent->id);
         }
     }
     return $timeTaken;
 }
 public function testCreateMultipleEmailMessageWithAttachments()
 {
     $jane = User::getByUsername('jane');
     $billy = User::getByUsername('billy');
     $emailMessageIds = array();
     for ($count = 0; $count < 5; $count++) {
         $emailMessage = new EmailMessage();
         $emailMessage->owner = $jane;
         $emailMessage->subject = 'My Email with 2 Attachments';
         $emailMessage->files->add(ZurmoTestHelper::createFileModel('testNote.txt'));
         $emailMessage->files->add(ZurmoTestHelper::createFileModel('testPDF.pdf'));
         //Set sender, and recipient, and content
         $emailContent = new EmailMessageContent();
         $emailContent->textContent = 'My Second Message';
         $emailMessage->content = $emailContent;
         //Sending from jane
         $sender = new EmailMessageSender();
         $sender->fromAddress = '*****@*****.**';
         $sender->fromName = 'Jane Smith';
         $sender->personsOrAccounts->add($jane);
         $emailMessage->sender = $sender;
         //Recipient is billy.
         $recipient = new EmailMessageRecipient();
         $recipient->toAddress = '*****@*****.**';
         $recipient->toName = 'Billy James';
         $recipient->type = EmailMessageRecipient::TYPE_TO;
         $recipient->personsOrAccounts->add($billy);
         $emailMessage->recipients->add($recipient);
         //At this point the message is not in a folder.
         $this->assertTrue($emailMessage->folder->id < 0);
         $box = EmailBox::resolveAndGetByName('JaneBox');
         $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_DRAFT);
         //Save, at this point the email should be in the draft folder
         $saved = $emailMessage->save();
         $this->assertTrue($saved);
         $this->assertTrue($emailMessage->folder->id > 0);
         $emailMessageIds[] = $emailMessage->id;
         unset($emailMessage);
         ForgetAllCacheUtil::forgetAllCaches();
     }
     foreach ($emailMessageIds as $id) {
         $emailMessage = EmailMessage::getById($id);
         $this->assertEquals('My Email with 2 Attachments', $emailMessage->subject);
         $this->assertEquals(2, $emailMessage->files->count());
         unset($emailMessage);
         ForgetAllCacheUtil::forgetAllCaches();
     }
 }
Example #17
0
 public static function suite()
 {
     global $argv;
     PhpUnitServiceUtil::checkVersion();
     $usage = PHP_EOL . "  Usage: phpunit [phpunit options] TestSuite.php <All|Framework|Misc|moduleName|TestClassName> [custom options]" . PHP_EOL . PHP_EOL . "    All                     Run all tests." . PHP_EOL . "    Framework               Run the tests in app/protected/extensions/framework/tests/unit." . PHP_EOL . "    Misc                    Run the tests in app/protected/tests/unit." . PHP_EOL . "    moduleName              Run the tests in app/protected/modules/moduleName/tests/unit." . PHP_EOL . "    TestClassName           Run the tests in TestClassName.php, wherever that happens to be." . PHP_EOL . PHP_EOL . "  Custom Options:" . PHP_EOL . PHP_EOL . "    --only-walkthroughs     For the specified test, only includes tests under a walkthroughs directory." . PHP_EOL . "    --exclude-walkthroughs  For the specified test, exclude tests under a walkthroughs directory." . PHP_EOL . "    --only-benchmarks       For the specified test, only includes tests under a benchmarks directory." . PHP_EOL . "    --exclude-benchmarks    For the specified test, exclude tests under a benchmarks directory." . PHP_EOL . "    --reuse-schema          Reload a previously auto build database. (Will auto build if there is no" . PHP_EOL . "                            previous one. The auto built schema is dumped to the system temp dir in" . PHP_EOL . "                            autobuild.sql.)" . PHP_EOL . PHP_EOL . "  Examples:" . PHP_EOL . PHP_EOL . "    phpunit --verbose TestSuite.php accounts (Run the tests in the Accounts module.)" . PHP_EOL . "    phpunit TestSuite.php RedBeanModelTest   (Run the tests in RedBeanModelTest.php.)" . PHP_EOL . PHP_EOL . "    To run specific tests use the phpunit --filter <regex> option." . PHP_EOL . "    phpunit has its own options. Check phpunit --help." . PHP_EOL . PHP_EOL;
     // Not Coding Standard
     $onlyWalkthroughs = self::customOptionSet('--only-walkthroughs', $argv);
     $excludeWalkthroughs = self::customOptionSet('--exclude-walkthroughs', $argv);
     $onlyBenchmarks = self::customOptionSet('--only-benchmarks', $argv);
     $excludeBenchmarks = self::customOptionSet('--exclude-benchmarks', $argv);
     $reuse = self::customOptionSet('--reuse-schema', $argv);
     if ($argv[count($argv) - 2] != 'TestSuite.php') {
         echo $usage;
         exit(static::ERROR_INVOCATION_WITHOUT_TESTSUITE);
     }
     if ($onlyWalkthroughs && $onlyBenchmarks) {
         echo $usage;
         echo "It doesn't have sense to select both \"--only-walkthroughs\" and \"--only-benchmarks\" options. " . PHP_EOL . PHP_EOL;
         exit(static::ERROR_WALKTHROUGH_AND_BENCHMARK_SELECTED);
     }
     $whatToTest = $argv[count($argv) - 1];
     $includeUnitTests = !$onlyWalkthroughs && !$onlyBenchmarks;
     $includeWalkthroughs = !$excludeWalkthroughs && !$onlyBenchmarks;
     $includeBenchmarks = !$excludeBenchmarks && !$onlyWalkthroughs;
     $suite = new PHPUnit_Framework_TestSuite();
     $suite->setName("{$whatToTest} Tests");
     self::buildAndAddSuiteFromDirectory($suite, 'Framework', COMMON_ROOT . '/protected/core/tests/unit', $whatToTest, true, false, $includeBenchmarks);
     $moduleDirectoryName = COMMON_ROOT . '/protected/modules';
     if (is_dir($moduleDirectoryName)) {
         $moduleNames = scandir($moduleDirectoryName);
         foreach ($moduleNames as $moduleName) {
             if ($moduleName != '.' && $moduleName != '..') {
                 $moduleUnitTestDirectoryName = "{$moduleDirectoryName}/{$moduleName}/tests/unit";
                 self::buildAndAddSuiteFromDirectory($suite, $moduleName, $moduleUnitTestDirectoryName, $whatToTest, $includeUnitTests, $includeWalkthroughs, $includeBenchmarks);
             }
         }
     }
     self::buildAndAddSuiteFromDirectory($suite, 'Misc', COMMON_ROOT . '/protected/tests/unit', $whatToTest, $includeUnitTests, $includeWalkthroughs, $includeBenchmarks);
     self::buildAndAddSuiteFromDirectory($suite, 'Commands', COMMON_ROOT . '/protected/commands/tests/unit', $whatToTest, $includeUnitTests, $includeWalkthroughs, $includeBenchmarks);
     ////////////////////////////////////////////////////////////////////////////////
     // Temporary - See Readme.txt in the notSupposedToBeHere directory.
     self::buildAndAddSuiteFromDirectory($suite, 'BadDependencies', COMMON_ROOT . '/protected/tests/unit/notSupposedToBeHere', $whatToTest, $includeUnitTests, $includeWalkthroughs, $includeBenchmarks);
     ////////////////////////////////////////////////////////////////////////////////
     if ($suite->count() == 0) {
         echo $usage;
         echo "  No tests found for '{$whatToTest}'." . PHP_EOL . PHP_EOL;
         exit(static::ERROR_TEST_NOT_FOUND);
     }
     echo "Testing with database: '" . Yii::app()->db->connectionString . '\', ' . 'username: \'' . Yii::app()->db->username . "'." . PHP_EOL;
     static::setupDatabaseConnection();
     // get rid of any caches from last execution, this ensure we rebuild any required tables
     // without this some of many_many tables have issues as we use cache to determine
     // if we need to rebuild those.
     ForgetAllCacheUtil::forgetAllCaches();
     $template = "{message}\n";
     $messageStreamer = new MessageStreamer($template);
     $messageStreamer->setExtraRenderBytes(0);
     $messageLogger = new MessageLogger($messageStreamer);
     $messageLogger->logDateTimeStamp = false;
     if (!$reuse) {
         if (!is_writable(sys_get_temp_dir())) {
             echo PHP_EOL . PHP_EOL . "Temp directory must be writable to store reusable schema" . PHP_EOL;
             // Not Coding Standard
             echo "Temp directory: " . sys_get_temp_dir() . PHP_EOL . PHP_EOL;
             // Not Coding Standard
             exit(static::ERROR_TEMP_DIR_NOT_WRITABLE);
         }
         echo "Auto building database schema..." . PHP_EOL;
         ZurmoRedBean::$writer->wipeAll();
         InstallUtil::autoBuildDatabase($messageLogger, true);
         $messageLogger->printMessages();
         // recreate all tables, we know there aren't existing because we just did a wipeAll();
         static::rebuildReadPermissionsTables(true, true, $messageStreamer);
         assert('RedBeanDatabase::isSetup()');
         Yii::app()->user->userModel = InstallUtil::createSuperUser('super', 'super');
         echo "Saving auto built schema..." . PHP_EOL;
         $schemaFile = sys_get_temp_dir() . '/autobuilt.sql';
         $success = preg_match("/;dbname=([^;]+)/", Yii::app()->db->connectionString, $matches);
         // Not Coding Standard
         assert('$success == 1');
         $databaseName = $matches[1];
         preg_match("/mysql:host=([^;]+)/", Yii::app()->db->connectionString, $matches);
         // Not Coding Standard
         $host = $matches[1];
         $systemOutput = system('mysqldump -u' . Yii::app()->db->username . ' -p' . Yii::app()->db->password . ' -h ' . $host . ' ' . $databaseName . " > {$schemaFile}");
         if ($systemOutput != null) {
             echo 'Dumping schema using system command. Output: ' . $systemOutput . PHP_EOL . PHP_EOL;
         }
     } else {
         echo PHP_EOL;
         static::buildDependentTestModels($messageLogger);
         $messageLogger->printMessages();
     }
     echo PHP_EOL;
     static::closeDatabaseConnection();
     return $suite;
 }
Example #18
0
 /**
  * There was a bug if you had an existing model, then created a custom drop down, it would not show
  * any values.  This was resolved by making sure cached models constructDerived.  This test should pass now
  * that the fix is implemented.
  * @depends testGetRequiredDerivedLayoutAttributeTypes
  */
 public function testExistingModelsShowCustomFieldDataCorrectlyWhenAttributeIsAddedAsDatabaseColumn()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Create account
     $account = AccountTestHelper::createAccountByNameForOwner('test', $super);
     $accountId = $account->id;
     $account->forget();
     $originalMetadata = Account::getMetadata();
     $attributeLabels = array('en' => 'newRelation');
     ModelMetadataUtil::addOrUpdateCustomFieldRelation('Account', 'newRelation', $attributeLabels, null, false, false, 'DropDown', 'Things', array('thing 1', 'thing 2'), array('fr' => array('thing 1 fr', 'thing 2 fr')));
     $adapter = new ModelAttributesAdapter(new Account());
     $adapter->resolveDatabaseSchemaForModel('Account');
     $metadata = Account::getMetadata();
     $this->assertNotEquals($originalMetadata, $metadata);
     $this->assertEquals($originalMetadata['Account']['rules'], $metadata['Account']['rules']);
     $newRelation = $metadata['Account']['relations']['newRelationCstm'];
     $this->assertEquals(array(RedBeanModel::HAS_ONE, 'OwnedCustomField', RedBeanModel::OWNED, RedBeanModel::LINK_TYPE_SPECIFIC, 'newRelationCstm'), $newRelation);
     $this->assertEquals('Things', $metadata['Account']['customFields']['newRelationCstm']);
     //on a new account, does the serialized data show correctly.
     $account = new Account();
     $this->assertEquals(array('thing 1', 'thing 2'), unserialize($account->newRelationCstm->data->serializedData));
     ForgetAllCacheUtil::forgetAllCaches();
     //retrieve account and make sure the serialized data shows correctly.
     //This will not be cached.
     $account = Account::getById($accountId);
     $this->assertNotNull($account->industry->data->serializedData);
     $this->assertEquals(array('thing 1', 'thing 2'), unserialize($account->newRelationCstm->data->serializedData));
     //This will pull from cached.  Clear the php cache first, which simulates a new page request without destroying
     //the persistent cache.
     RedBeanModelsCache::forgetAll(true);
     $account = Account::getById($accountId);
     //Test pulling a different CustomField first. This simulates caching the customField
     $this->assertEquals(array('thing 1', 'thing 2'), unserialize($account->newRelationCstm->data->serializedData));
 }