public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     ZurmoDatabaseCompatibilityUtil::dropStoredFunctionsAndProcedures();
     SecurityTestHelper::createSuperAdmin();
     SecurityTestHelper::createUsers();
     SecurityTestHelper::createGroups();
     SecurityTestHelper::createRoles();
     RedBeanModel::forgetAll();
     //do the rebuild to ensure the tables get created properly.
     ReadPermissionsOptimizationUtil::rebuild();
     //Manually build the test model munge tables.
     ReadPermissionsOptimizationUtil::recreateTable(ReadPermissionsOptimizationUtil::getMungeTableName('OwnedSecurableTestItem'));
     ReadPermissionsOptimizationUtil::recreateTable(ReadPermissionsOptimizationUtil::getMungeTableName('OwnedSecurableTestItem2'));
     $benny = User::getByUsername('benny');
     $model = new OwnedSecurableTestItem();
     $model->member = 'test';
     assert($model->save());
     // Not Coding Standard
     $model = new OwnedSecurableTestItem();
     $model->member = 'test2';
     assert($model->save());
     // Not Coding Standard
     $model = new OwnedSecurableTestItem();
     $model->member = 'test3';
     $model->owner = $benny;
     assert($model->save());
     // Not Coding Standard
     assert(OwnedSecurableTestItem::getCount() == 3);
     // Not Coding Standard
     $model = new OwnedSecurableTestItem2();
     $model->member = 'test5';
     assert($model->save());
     // Not Coding Standard
 }
Пример #2
0
 public function setUp()
 {
     parent::setUp();
     RedBeanModel::forgetAll();
     $this->setupServerUrl();
     if (!$this->isApiTestUrlConfigured()) {
         $this->markTestSkipped(Zurmo::t('ApiModule', 'API test url is not configured in perInstanceTest.php file.'));
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     $super = SecurityTestHelper::createSuperAdmin();
     self::$emailMessage = EmailMessageTestHelper::createDraftSystemEmail('a test message', $super);
     SecurityTestHelper::createUsers();
     SecurityTestHelper::createGroups();
     SecurityTestHelper::createRoles();
     RedBeanModel::forgetAll();
     //do the rebuild to ensure the tables get created properly.
     ReadPermissionsOptimizationUtil::rebuild();
 }
 public function testAttributesTranslateToAllSupportedLanguagesCorrectly()
 {
     $this->assertEquals('en', Yii::app()->language);
     $account = new Account(false);
     $this->assertEquals('Office Phone', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Billing Address', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'fr';
     $this->assertEquals('Téléphone de bureau', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Adresse de facturation', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'it';
     $this->assertEquals('Telefono Ufficio', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Indirizzo di Fatturazione', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'es';
     $this->assertEquals('Teléfono de la Oficina', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Dirección de facturación', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'de';
     $this->assertEquals('Bürotelefon', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('Rechnungsadresse', $account->getAttributeLabel('billingAddress'));
     //Set language back to english.
     Yii::app()->language = 'en';
     //Now customize both labels for all supported languages.
     $metadata = Account::getMetadata();
     $metadata['Account']['labels']['officePhone'] = array('de' => 'GermanSomething', 'en' => 'EnglishSomething', 'es' => 'SpanishSomething', 'fr' => 'FrenchSomething', 'it' => 'ItalianSomething');
     $metadata['Account']['labels']['billingAddress'] = array('de' => 'GermanSomethingElse', 'en' => 'EnglishSomethingElse', 'es' => 'SpanishSomethingElse', 'fr' => 'FrenchSomethingElse', 'it' => 'ItalianSomethingElse');
     Account::setMetadata($metadata);
     RedBeanModel::forgetAll();
     //Set language back to english.
     Yii::app()->language = 'en';
     $this->assertEquals('EnglishSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('EnglishSomethingElse', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'fr';
     $this->assertEquals('FrenchSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('FrenchSomethingElse', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'it';
     $this->assertEquals('ItalianSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('ItalianSomethingElse', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'es';
     $this->assertEquals('SpanishSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('SpanishSomethingElse', $account->getAttributeLabel('billingAddress'));
     Yii::app()->language = 'de';
     $this->assertEquals('GermanSomething', $account->getAttributeLabel('officePhone'));
     $this->assertEquals('GermanSomethingElse', $account->getAttributeLabel('billingAddress'));
     //Set language back to english.
     Yii::app()->language = 'en';
     //Retrieve all the language labels for a particular attribute.
     $officePhoneLabels = $account->getAttributeLabelsForAllActiveLanguagesByAttributeName('officePhone');
     $billingAddressLabels = $account->getAttributeLabelsForAllActiveLanguagesByAttributeName('billingAddress');
     $comparePhoneLabels = array('de' => 'GermanSomething', 'en' => 'EnglishSomething', 'es' => 'SpanishSomething', 'fr' => 'FrenchSomething', 'it' => 'ItalianSomething');
     $compareAddressLabels = array('de' => 'GermanSomethingElse', 'en' => 'EnglishSomethingElse', 'es' => 'SpanishSomethingElse', 'fr' => 'FrenchSomethingElse', 'it' => 'ItalianSomethingElse');
     $this->assertEquals($comparePhoneLabels, $officePhoneLabels);
     $this->assertEquals($compareAddressLabels, $compareAddressLabels);
 }
Пример #5
0
 public static function tearDownAfterClass()
 {
     if (RedBeanDatabase::isFrozen()) {
         TestDatabaseUtil::deleteRowsFromAllTablesExceptLog();
     } else {
         TestDatabaseUtil::deleteAllTablesExceptLog();
     }
     RedBeanModel::forgetAll();
     RedBeanDatabase::close();
     assert('!RedBeanDatabase::isSetup()');
     // Not Coding Standard
     GeneralCache::forgetAll();
 }
 public function testListContactStateAttributes()
 {
     RedBeanModel::forgetAll();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $allAttributes = ApiRestTestHelper::getModelAttributes(new ContactState());
     $response = $this->createApiCallWithRelativeUrl('listAttributes/', 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($allAttributes, $response['data']['items']);
 }
Пример #7
0
 public static function tearDownAfterClass()
 {
     if (static::$activateDefaultLanguages) {
         Yii::app()->languageHelper->deactivateLanguagesForTesting();
     }
     TestDatabaseUtil::deleteRowsFromAllTablesExceptLog();
     PermissionsCache::forgetAll();
     AllPermissionsOptimizationCache::forgetAll();
     RedBeanModel::forgetAll();
     RedBeanDatabase::close();
     assert('!RedBeanDatabase::isSetup()');
     // Not Coding Standard
     GeneralCache::forgetAll();
     BeanModelCache::forgetAll();
 }
 public function testCreateWithScenario()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $data['name'] = 'ABCD';
     $data['createdDateTime'] = '2014-06-12 15:22:41';
     $data['modifiedDateTime'] = '2014-06-12 15:28:41';
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_FAILURE, $response['status']);
     $this->assertEquals('It is not allowed to set read only attribute: createdDateTime.', $response['message']);
     // Now try to use some invalid scenario name
     $data['modelScenario'] = 'dummyScenarioName';
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_FAILURE, $response['status']);
     $this->assertEquals('It is not allowed to set read only attribute: createdDateTime.', $response['message']);
     // Now use scenario name that allow us to set all values
     $data['modelScenario'] = 'importModel';
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     RedBeanModel::forgetAll();
     $account = Account::getById($response['data']['id']);
     $this->assertEquals($account->name, $response['data']['name']);
     $this->assertEquals($account->createdDateTime, $response['data']['createdDateTime']);
 }
 public function testCreateWithRelations()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $everyoneGroup = Group::getByName(Group::EVERYONE_GROUP_NAME);
     $this->assertTrue($everyoneGroup->save());
     $john = UserTestHelper::createBasicUser('John');
     $john->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $john->setRight('MeetingsModule', MeetingsModule::getAccessRight());
     $john->setRight('MeetingsModule', MeetingsModule::getCreateRight());
     $saved = $john->save();
     $this->assertTrue($saved);
     $contact = ContactTestHelper::createContactByNameForOwner('Simon', $super);
     $contact2 = ContactTestHelper::createContactByNameForOwner('Simona', $john);
     $contactItemId = $contact->getClassId('Item');
     $contact2ItemId = $contact2->getClassId('Item');
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $categories = array('Meeting', 'Call');
     $categoryFieldData = CustomFieldData::getByName('MeetingCategories');
     $categoryFieldData->serializedData = serialize($categories);
     $this->assertTrue($categoryFieldData->save());
     $startStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 10000);
     $endStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 11000);
     $data['name'] = "Meeting with relations for super user";
     $data['startDateTime'] = $startStamp;
     $data['endDateTime'] = $endStamp;
     $data['category']['value'] = $categories[1];
     $data['modelRelations'] = array('activityItems' => array(array('action' => 'add', 'modelId' => $contact->id, 'modelClassName' => 'Contact')), 'userAttendees' => array(array('action' => 'add', 'modelId' => $john->id, 'modelClassName' => 'User')));
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($data['name'], $response['data']['name']);
     $this->assertEquals($data['startDateTime'], $response['data']['startDateTime']);
     $this->assertEquals($data['endDateTime'], $response['data']['endDateTime']);
     RedBeanModel::forgetAll();
     $meeting = Meeting::getById($response['data']['id']);
     $this->assertEquals(1, count($meeting->activityItems));
     $this->assertEquals($contactItemId, $meeting->activityItems[0]->id);
     $this->assertEquals(1, count($meeting->userAttendees));
     $this->assertEquals($john->id, $meeting->userAttendees[0]->id);
     // Now test with regular user
     $authenticationData = $this->login('john', 'john');
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $data = array();
     $data['name'] = "Meeting with relations for regular user";
     $data['startDateTime'] = $startStamp;
     $data['endDateTime'] = $endStamp;
     $data['category']['value'] = $categories[1];
     $data['modelRelations'] = array('activityItems' => array(array('action' => 'add', 'modelId' => $contact2->id, 'modelClassName' => 'Contact')), 'userAttendees' => array(array('action' => 'add', 'modelId' => $super->id, 'modelClassName' => 'User')));
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($data['name'], $response['data']['name']);
     $this->assertEquals($data['startDateTime'], $response['data']['startDateTime']);
     $this->assertEquals($data['endDateTime'], $response['data']['endDateTime']);
     RedBeanModel::forgetAll();
     $meeting = Meeting::getById($response['data']['id']);
     $this->assertEquals(1, count($meeting->activityItems));
     $this->assertEquals($contact2ItemId, $meeting->activityItems[0]->id);
     $this->assertEquals(1, count($meeting->userAttendees));
     $this->assertEquals($super->id, $meeting->userAttendees[0]->id);
 }
Пример #10
0
 /**
  * @depends testCreateUser
  */
 public function testUpdateUser()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $user = User::getByUsername('diggy011');
     $compareData = $this->getModelToApiDataUtilData($user);
     $user->forget();
     $data['firstName'] = "John";
     $data['password'] = "******";
     $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     // We need to unset some empty values from response and dates.
     unset($response['data']['modifiedDateTime']);
     unset($compareData['modifiedDateTime']);
     unset($response['data']['lastLoginDateTime']);
     unset($compareData['lastLoginDateTime']);
     $compareData['firstName'] = "John";
     ksort($compareData);
     ksort($response['data']);
     $this->assertEquals($compareData, $response['data']);
     // Check if password is updated
     RedBeanModel::forgetAll();
     $updatedUser = User::getByUsername('diggy011');
     $this->assertNotEquals($user->hash, $updatedUser->hash);
     $response = $this->createApiCallWithRelativeUrl('read/' . $user->id, 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     unset($response['data']['modifiedDateTime']);
     unset($response['data']['lastLoginDateTime']);
     ksort($response['data']);
     $this->assertEquals($compareData, $response['data']);
 }
Пример #11
0
 /**
  * @depends testCreateWithRelations
  */
 public function testUpdateWithRelations()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $contact = ContactTestHelper::createContactByNameForOwner('Mark', $super);
     $contactItemId = $contact->getClassId('Item');
     $note = NoteTestHelper::createNoteByNameForOwner('Note update test.', $super);
     $redBeanModelToApiDataUtil = new RedBeanModelToApiDataUtil($note);
     $compareData = $redBeanModelToApiDataUtil->getData();
     $this->assertEquals(0, count($note->activityItems));
     $note->forget();
     $data['modelRelations'] = array('activityItems' => array(array('action' => 'add', 'modelId' => $contact->id, 'modelClassName' => 'Contact')));
     $data['description'] = "Updated note description";
     $response = ApiRestTestHelper::createApiCall($this->serverUrl . '/test.php/notes/note/api/update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     unset($response['data']['modifiedDateTime']);
     unset($compareData['modifiedDateTime']);
     $compareData['description'] = "Updated note description";
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($compareData, $response['data']);
     RedBeanModel::forgetAll();
     $note = Note::getById($compareData['id']);
     $this->assertEquals(1, count($note->activityItems));
     $this->assertEquals($contactItemId, $note->activityItems[0]->id);
     // Now test remove relations
     $data['modelRelations'] = array('activityItems' => array(array('action' => 'remove', 'modelId' => $contact->id, 'modelClassName' => 'Contact')));
     $response = ApiRestTestHelper::createApiCall($this->serverUrl . '/test.php/notes/note/api/update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     RedBeanModel::forgetAll();
     $note = Note::getById($compareData['id']);
     $this->assertEquals(0, count($note->activityItems));
 }
Пример #12
0
 public function testDeleteSecurableItemDeletesItsPermissions()
 {
     $user = User::getByUsername('billy');
     $account = new Account();
     $account->name = 'Waxamatronic';
     $account->addPermissions($user, Permission::READ);
     $this->assertTrue($account->save());
     $this->assertEquals(1, count($account->permissions));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($user));
     $account->delete();
     unset($account);
     $userId = $user->id;
     unset($user);
     RedBeanModel::forgetAll();
     $this->assertEquals(0, count(Permission::getAll()));
 }
 public function testResolveContactToSenderOrRecipientForReceivedEmail()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $message1 = self::$message1;
     $contact = new Contact();
     $contact->firstName = 'Jason';
     $contact->lastName = 'Green';
     $contact->state = ContactsUtil::getStartingState();
     $saved = $contact->save();
     $this->assertTrue($saved);
     $contactId = $contact->id;
     $contact->forget();
     $contact = Contact::getById($contactId);
     $this->assertNull($contact->primaryEmail->emailAddress);
     ArchivedEmailMatchingUtil::resolveContactToSenderOrRecipient($message1, $contact);
     $saved = $message1->save();
     $this->assertTrue($saved);
     $messageId = $message1->id;
     $message1->forget();
     $contact->forget();
     RedBeanModel::forgetAll();
     //simulates crossing page requests
     $message1 = EmailMessage::getById($messageId);
     $contact = Contact::getById($contactId);
     $this->assertEquals(1, $message1->sender->personsOrAccounts->count());
     $castedDownModel = EmailMessageMashableActivityRules::castDownItem($message1->sender->personsOrAccounts[0]);
     $this->assertEquals('Contact', get_class($castedDownModel));
     $this->assertEquals($contact->id, $castedDownModel->id);
 }
Пример #14
0
 /**
  * @depends testMakeAttributeFormByAttributeName
  */
 public function testSetNewAttributeFromAttributeForm()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $values = array('Automotive', 'Adult Entertainment', 'Financial Services', 'Mercenaries & Armaments');
     $industryFieldData = CustomFieldData::getByName('Industries');
     $industryFieldData->forget();
     unset($industryFieldData);
     $industryFieldData = CustomFieldData::getByName('Industries');
     $industryFieldData->serializedData = serialize($values);
     $this->assertTrue($industryFieldData->save());
     $account = new Account();
     $attributeForm = new DropDownAttributeForm($account, 'industry');
     $attributeForm->attributeLabels = array('de' => 'Industry de', 'en' => 'Industry', 'es' => 'Industry es', 'fr' => 'Industry fr', 'it' => 'Industry it');
     $attributeForm->isAudited = true;
     $attributeForm->isRequired = false;
     $this->assertEquals($values, $attributeForm->customFieldDataData);
     $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData();
     $adapter = new $modelAttributesAdapterClassName(new Account());
     try {
         $adapter->setAttributeMetadataFromForm($attributeForm);
     } catch (FailedDatabaseSchemaChangeException $e) {
         echo $e->getMessage();
         $this->fail();
     }
     RedBeanModel::forgetAll();
     $account = new Account();
     $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName($account, 'industry');
     $this->assertEquals('industry', $attributeForm->attributeName);
     $compareAttributeLabels = array('de' => 'Industry de', 'en' => 'Industry', 'es' => 'Industry es', 'fr' => 'Industry fr', 'it' => 'Industry it');
     $this->assertEquals($compareAttributeLabels, $attributeForm->attributeLabels);
     $this->assertEquals(true, $attributeForm->isAudited);
     $this->assertEquals(false, $attributeForm->isRequired);
     $this->assertEquals($values, $attributeForm->customFieldDataData);
 }
 public function testSuperUserAllDefaultControllerActions()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $imageFile = ImageFileModel::getById($this->imageFile1Id);
     if (file_exists($imageFile->getImageCachePath())) {
         unlink($imageFile->getImageCachePath());
     }
     if (file_exists($imageFile->getImageCachePath(true))) {
         unlink($imageFile->getImageCachePath(true));
     }
     //Test all default controller actions that do not require any POST/GET variables to be passed.
     //This does not include portlet controller actions.
     $content = $this->runControllerWithNoExceptionsAndGetContent('zurmo/imageModel/getUploaded');
     $returnedObject = CJSON::decode($content);
     $this->assertContains('zurmo/imageModel/getImage?fileName=' . $imageFile->getImageCacheFileName(), $returnedObject[0]['image']);
     $this->assertContains('zurmo/imageModel/getThumb?fileName=' . $imageFile->getImageCacheFileName(), $returnedObject[0]['thumb']);
     $this->assertFalse(file_exists($imageFile->getImageCachePath()));
     $this->assertFalse(file_exists($imageFile->getImageCachePath(true)));
     //Test getting the image
     $this->setGetArray(array('fileName' => $imageFile->getImageCacheFileName()));
     @$this->runControllerWithExitExceptionAndGetContent('zurmo/imageModel/getImage');
     $this->assertTrue(file_exists($imageFile->getImageCachePath()));
     $this->assertFalse(file_exists($imageFile->getImageCachePath(true)));
     //Test getting the image thumb
     $this->setGetArray(array('fileName' => $imageFile->getImageCacheFileName()));
     @$this->runControllerWithExitExceptionAndGetContent('zurmo/imageModel/getThumb');
     $this->assertTrue(file_exists($imageFile->getImageCachePath()));
     $this->assertTrue(file_exists($imageFile->getImageCachePath(true)));
     //Test uploading invalid image
     $pathToFiles = Yii::getPathOfAlias('application.modules.zurmo.tests.unit.files');
     $filePath = $pathToFiles . DIRECTORY_SEPARATOR . 'testNote.txt';
     self::resetAndPopulateFilesArrayByFilePathAndName('file', $filePath, 'testNote.txt');
     $content = $this->runControllerWithNoExceptionsAndGetContent('zurmo/imageModel/upload');
     $returnedObject = CJSON::decode($content);
     $this->assertEquals('Error uploading the image', $returnedObject[0]['error']);
     //Test uploading valid image
     $pathToFiles = Yii::getPathOfAlias('application.modules.zurmo.tests.unit.files');
     $fileContents = file_get_contents($pathToFiles . DIRECTORY_SEPARATOR . 'testImage.png');
     $filePath = $pathToFiles . DIRECTORY_SEPARATOR . 'testImage.png';
     self::resetAndPopulateFilesArrayByFilePathAndName('file', $filePath, 'testImage.png');
     $content = $this->runControllerWithNoExceptionsAndGetContent('zurmo/imageModel/upload');
     $returnedObject = CJSON::decode($content);
     $this->assertContains('zurmo/imageModel/getImage?fileName=2_testImage.png', $returnedObject[0]['filelink']);
     // Not Coding Standard
     $createdImageFile = ImageFileModel::getById(2);
     $this->assertEquals($fileContents, $createdImageFile->fileContent->content);
     //Test deleting image
     $createdImageFile->inactive = false;
     $this->setGetArray(array('id' => 2));
     $this->runControllerWithNoExceptionsAndGetContent('zurmo/imageModel/delete', true);
     RedBeanModel::forgetAll();
     $deletedImageFile = ImageFileModel::getById(2);
     $deletedImageFile->inactive = true;
 }
 public function testAllDefaultControllerActions()
 {
     $this->user->setRight('ContactsModule', ContactsModule::getAccessRight());
     $this->assertTrue($this->user->save());
     $emailTemplate = EmailTemplateTestHelper::create('Test Name Regular 01', 'Test Subject Regular 01', 'Contact', 'Test HtmlContent Regular 01', 'Test TextContent Regular 01');
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default');
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/index');
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/listForMarketing');
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/listForWorkflow');
     $this->setGetArray(array('type' => EmailTemplate::TYPE_CONTACT));
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/create');
     $this->setGetArray(array('id' => $emailTemplate->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/edit');
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/details');
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/delete');
     $this->resetGetArray();
     $this->user->setRight('EmailTemplatesModule', EmailTemplatesModule::getAccessRight());
     $this->assertTrue($this->user->save());
     $this->runControllerWithNoExceptionsAndGetContent('emailTemplates/default');
     $this->runControllerWithNoExceptionsAndGetContent('emailTemplates/default/index');
     $this->runControllerWithNoExceptionsAndGetContent('emailTemplates/default/listForMarketing');
     $this->runControllerWithNoExceptionsAndGetContent('emailTemplates/default/listForWorkflow');
     $this->setGetArray(array('id' => $emailTemplate->id));
     $this->runControllerWithNoExceptionsAndGetContent('emailTemplates/default/details');
     $this->resetGetArray();
     $this->user->setRight('EmailTemplatesModule', EmailTemplatesModule::getCreateRight());
     $this->assertTrue($this->user->save());
     $this->setGetArray(array('type' => EmailTemplate::TYPE_CONTACT, 'builtType' => EmailTemplate::BUILT_TYPE_PLAIN_TEXT_ONLY));
     $this->runControllerWithNoExceptionsAndGetContent('emailTemplates/default/create');
     $this->setGetArray(array('type' => EmailTemplate::TYPE_WORKFLOW, 'builtType' => EmailTemplate::BUILT_TYPE_PLAIN_TEXT_ONLY));
     $this->runControllerWithNoExceptionsAndGetContent('emailTemplates/default/create');
     $this->setGetArray(array('id' => $emailTemplate->id));
     $this->runControllerWithNoExceptionsAndGetContent('emailTemplates/default/edit');
     $this->user->setRight('EmailTemplatesModule', EmailTemplatesModule::getDeleteRight());
     $this->assertTrue($this->user->save());
     $this->runControllerWithRedirectExceptionAndGetUrl('emailTemplates/default/delete');
     $this->setGetArray(array('id' => static::$templateOwnedBySuper->id));
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/edit');
     RedBeanModel::forgetAll();
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/details');
     RedBeanModel::forgetAll();
     $this->runControllerShouldResultInAccessFailureAndGetContent('emailTemplates/default/delete');
 }
 protected function createCustomAttributeWalkthroughSequence($moduleClassName, $name, $attributeTypeName, $extraPostData, $attributeName = null, $isCustomField = false)
 {
     assert('$name[0] == strtolower($name[0])');
     // Not Coding Standard
     assert('is_array($extraPostData)');
     // Not Coding Standard
     $formName = $attributeTypeName . 'AttributeForm';
     $this->setGetArray(array('moduleClassName' => $moduleClassName, 'attributeTypeName' => $attributeTypeName, 'attributeName' => $attributeName));
     $this->resetPostArray();
     //Now test going to the user interface edit view.
     $content = $this->runControllerWithNoExceptionsAndGetContent('designer/default/attributeEdit');
     //Now validate save with failed validation.
     $this->setPostArray(array('ajax' => 'edit-form', $formName => array_merge(array('attributeLabels' => $this->createAttributeLabelBadValidationPostData($name), 'attributeName' => $name), $extraPostData)));
     $content = $this->runControllerWithExitExceptionAndGetContent('designer/default/attributeEdit');
     $this->assertTrue(strlen($content) > 50);
     //approximate, but should definetely be larger than 50.
     //Now validate save with successful validation.
     $this->setPostArray(array('ajax' => 'edit-form', $formName => array_merge(array('attributeLabels' => $this->createAttributeLabelGoodValidationPostData($name), 'attributeName' => $name), $extraPostData)));
     $content = $this->runControllerWithExitExceptionAndGetContent('designer/default/attributeEdit');
     $this->assertEquals('[]', $content);
     //Now save successfully.
     $this->setPostArray(array('save' => 'Save', $formName => array_merge(array('attributeLabels' => $this->createAttributeLabelGoodValidationPostData($name), 'attributeName' => $name), $extraPostData)));
     $this->runControllerWithRedirectExceptionAndGetContent('designer/default/attributeEdit');
     //Now confirm everything did in fact save correctly.
     RedBeanModel::forgetAll();
     $modelClassName = $moduleClassName::getPrimaryModelName();
     $newModel = new $modelClassName(false);
     $compareData = array('de' => $name . ' de', 'it' => $name . ' it', 'es' => $name . ' es', 'en' => $name . ' en', 'fr' => $name . ' fr');
     if ($isCustomField) {
         $name = $name . 'Cstm';
     }
     if ($attributeTypeName != "CalculatedNumber" && $attributeTypeName != "DropDownDependency") {
         $this->assertEquals($compareData, $newModel->getAttributeLabelsForAllActiveLanguagesByAttributeName($name));
     }
     if ($attributeTypeName != "CalculatedNumber" && $attributeTypeName != "DropDownDependency") {
         //Now test going to the user interface edit view for the existing attribute.
         $this->setGetArray(array('moduleClassName' => $moduleClassName, 'attributeTypeName' => $attributeTypeName, 'attributeName' => $name));
         // if we don't do this attributeName from POST will override and result in duplicate columns.
         // Frontend also doesn't send attributeName in POST on edit.
         unset($_POST[$formName]['attributeName']);
         $content = $this->runControllerWithRedirectExceptionAndGetContent('designer/default/attributeEdit');
     }
 }
 protected static function assertEverythingHasBeenSetBackToHowItStarted()
 {
     RedBeanModel::forgetAll();
     $u1 = User::getByUsername('u1.');
     $u2 = User::getByUsername('u2.');
     $u3 = User::getByUsername('u3.');
     $u4 = User::getByUsername('u4.');
     $u5 = User::getByUsername('u5.');
     $u6 = User::getByUsername('u6.');
     $g1 = Group::getByName('G1.');
     $g2 = Group::getByName('G2.');
     $g3 = Group::getByName('G3.');
     $r1 = Role::getByName('R1.');
     $r2 = Role::getByName('R2.');
     $r3 = Role::getByName('R3.');
     $r4 = Role::getByName('R4.');
     $r5 = Role::getByName('R5.');
     $r6 = Role::getByName('R6.');
     assert('$g1->users->count() == 0');
     // Not Coding Standard
     assert('$g2->users->count() == 0');
     // Not Coding Standard
     assert('$g3->users->count() == 0');
     // Not Coding Standard
     assert('$g1->groups->count() == 0');
     // Not Coding Standard
     assert('$g2->groups->count() == 0');
     // Not Coding Standard
     assert('$g3->groups->count() == 0');
     // Not Coding Standard
     assert('$r1->role->isSame($r2)');
     // Not Coding Standard
     assert('$r2->role->isSame($r3)');
     // Not Coding Standard
     assert('$r3->role->id < 0');
     // Not Coding Standard
     assert('$r4->role->isSame($r5)');
     // Not Coding Standard
     assert('$r5->role->isSame($r6)');
     // Not Coding Standard
     assert('$r6->role->id < 0');
     // Not Coding Standard
     assert('$u1->role->isSame($r1)');
     // Not Coding Standard
     assert('$u2->role->isSame($r4)');
     // Not Coding Standard
     //            assert('$u3->role->isSame($r4)'); // Not Coding Standard
     assert('$u4->role->isSame($r4)');
     // Not Coding Standard
     assert('$u5->role->id < 0');
     // Not Coding Standard
     assert('$u6->role->id < 0');
     // Not Coding Standard
 }
 public function testModelWithAttachmentTestItem()
 {
     $pathToFiles = Yii::getPathOfAlias('application.modules.zurmo.tests.unit.files');
     $filePath = $pathToFiles . DIRECTORY_SEPARATOR . 'testNote.txt';
     // create 2 extra file model which should persist when $model is delete, their content should also persist.
     $pdfFile = FileModelUtil::makeByFilePathAndName($filePath, 'testPDF.pdf');
     $pdfFileId = $pdfFile->id;
     $pdfFileName = $pdfFile->name;
     $pdfFileContent = $pdfFile->fileContent->content;
     $pdfFileType = $pdfFile->type;
     $pdfFileSize = $pdfFile->size;
     $pdfFile->forgetAll();
     unset($pdfFile);
     $zipFile = FileModelUtil::makeByFilePathAndName($filePath, 'testZip.zip');
     $zipFileId = $zipFile->id;
     $zipFileName = $zipFile->name;
     $zipFileContent = $zipFile->fileContent->content;
     $zipFileType = $zipFile->type;
     $zipFileSize = $zipFile->size;
     $zipFile->forgetAll();
     unset($zipFile);
     $model = new ModelWithAttachmentTestItem();
     $fileModel = FileModelUtil::makeByFilePathAndName($filePath, 'testNote.txt');
     $firstFileModelId = $fileModel->id;
     $this->assertTrue($fileModel instanceof FileModel);
     $this->assertEquals(6495, strlen($fileModel->fileContent->content));
     $theContent = $fileModel->fileContent->content;
     $model->files->add($fileModel);
     $model->member = 'test';
     $saved = $model->save();
     $this->assertTrue($saved);
     $modelId = $model->id;
     $model->forget();
     $model = ModelWithAttachmentTestItem::getById($modelId);
     $this->assertEquals($theContent, $model->files[0]->fileContent->content);
     $this->assertEquals('testNote.txt', $model->files[0]->name);
     $this->assertEquals('text/plain', $model->files[0]->type);
     $this->assertEquals(6495, $model->files[0]->size);
     //Now try using CUploadedFile.
     self::resetAndPopulateFilesArrayByFilePathAndName('aTest', $filePath, 'testNote.txt');
     $uploadedFile = CUploadedFile::getInstanceByName('aTest');
     $this->assertTrue($uploadedFile instanceof CUploadedFile);
     $fileModel = FileModelUtil::makeByUploadedFile($uploadedFile);
     $this->assertTrue($fileModel instanceof FileModel);
     $this->assertTrue($fileModel->id != $firstFileModelId);
     $this->assertTrue($fileModel->id > 0);
     $model = ModelWithAttachmentTestItem::getById($modelId);
     $model->files->add($fileModel);
     $saved = $model->save();
     $this->assertTrue($saved);
     $modelId = $model->id;
     $model->forget();
     RedBeanModel::forgetAll();
     $model = ModelWithAttachmentTestItem::getById($modelId);
     $this->assertEquals(2, $model->files->count());
     //Delete the model and confirm the related models are removed
     $this->assertEquals(1, ModelWithAttachmentTestitem::getCount());
     $this->assertEquals(4, FileModel::getCount());
     $this->assertEquals(4, FileContent::getCount());
     $this->assertTrue($model->delete());
     $this->assertEquals(0, ModelWithAttachmentTestitem::getCount());
     $this->assertEquals(2, FileModel::getCount());
     $this->assertEquals(2, FileContent::getCount());
     $pdfFile = FileModel::getById($pdfFileId);
     $this->assertEquals($pdfFileContent, $pdfFile->fileContent->content);
     $this->assertEquals($pdfFileName, $pdfFile->name);
     $this->assertEquals($pdfFileType, $pdfFile->type);
     $this->assertEquals($pdfFileSize, $pdfFile->size);
     $zipFile = FileModel::getById($zipFileId);
     $this->assertEquals($zipFileContent, $zipFile->fileContent->content);
     $this->assertEquals($zipFileName, $zipFile->name);
     $this->assertEquals($zipFileType, $zipFile->type);
     $this->assertEquals($zipFileSize, $zipFile->size);
 }
 /**
  * @depends testCreateWithRelations
  */
 public function testUpdateWithRelations()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $contact = ContactTestHelper::createContactByNameForOwner('Simon', $super);
     $opportunity = OpportunityTestHelper::createOpportunityByNameForOwner('My Opportunity', $super);
     $compareData = $this->getModelToApiDataUtilData($contact);
     $contact->forget();
     $data['modelRelations'] = array('opportunities' => array(array('action' => 'add', 'modelId' => $opportunity->id, 'modelClassName' => 'Opportunity')));
     $data['firstName'] = 'Fred';
     $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     unset($response['data']['modifiedDateTime']);
     unset($compareData['modifiedDateTime']);
     $compareData['firstName'] = 'Fred';
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($compareData, $response['data']);
     RedBeanModel::forgetAll();
     $contact = Contact::getById($compareData['id']);
     $this->assertEquals(1, count($contact->opportunities));
     $this->assertEquals($opportunity->id, $contact->opportunities[0]->id);
     $opportunity = Opportunity::getById($opportunity->id);
     $this->assertEquals(1, count($opportunity->contacts));
     $this->assertEquals($contact->id, $opportunity->contacts[0]->id);
     // Now test remove relations
     $data['modelRelations'] = array('opportunities' => array(array('action' => 'remove', 'modelId' => $opportunity->id, 'modelClassName' => 'Opportunity')));
     $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     RedBeanModel::forgetAll();
     $contact = Contact::getById($compareData['id']);
     $this->assertEquals(0, count($contact->opportunities));
     $opportunity = Opportunity::getById($opportunity->id);
     $this->assertEquals(0, count($opportunity->contacts));
 }
Пример #21
0
 /**
  * @depends testRemovePolicies
  */
 public function testDeleteAllPolicies()
 {
     $nerd = User::getByUsername('billy');
     $salesStaff = Group::getByName('Sales Staff');
     $this->assertEquals(null, $nerd->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(null, $salesStaff->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(null, $nerd->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(null, $salesStaff->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $nerd->setPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS, 30);
     $this->assertTrue($nerd->save());
     $this->assertEquals(30, $nerd->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(null, $salesStaff->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $salesStaff->setPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS, 10);
     $this->assertTrue($salesStaff->save());
     $this->assertEquals(30, $nerd->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(10, $salesStaff->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     Policy::removeAllForPermitable($nerd);
     PoliciesCache::forgetAll();
     unset($nerd);
     unset($salesStaff);
     RedBeanModel::forgetAll();
     $nerd = User::getByUsername('billy');
     $salesStaff = Group::getByName('Sales Staff');
     $this->assertEquals(null, $nerd->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(10, $salesStaff->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     Policy::deleteAll();
     PoliciesCache::forgetAll();
     unset($nerd);
     unset($salesStaff);
     RedBeanModel::forgetAll();
     $nerd = User::getByUsername('billy');
     $salesStaff = Group::getByName('Sales Staff');
     $this->assertEquals(null, $nerd->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(null, $salesStaff->getActualPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
 }
Пример #22
0
 /**
  * @depends testUpdateLead
  */
 public function testListLead()
 {
     RedBeanModel::forgetAll();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $leads = Contact::getByName('Michael Smith');
     $this->assertEquals(1, count($leads));
     $redBeanModelToApiDataUtil = new RedBeanModelToApiDataUtil($leads[0]);
     $compareData = $redBeanModelToApiDataUtil->getData();
     $response = ApiRestTestHelper::createApiCall($this->serverUrl . '/test.php/leads/contact/api/list/', 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(1, count($response['data']['items']));
     $this->assertEquals(1, $response['data']['totalCount']);
     $this->assertEquals(1, $response['data']['currentPage']);
     $this->assertEquals(array($compareData), $response['data']['items']);
 }
Пример #23
0
 /**
  * @depends testAutoBuildDatabase
  */
 public function testAutoBuildUpgrade()
 {
     $this->unfreezeWhenDone = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $this->unfreezeWhenDone = true;
     }
     // adding Text Field
     $metadata = Account::getMetadata();
     $metadata['Account']['members'][] = 'newField';
     $rules = array('newField', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string128';
     $rules = array('string128', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string128', 'length', 'min' => 3, 'max' => 128);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string555';
     $rules = array('string555', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string555', 'length', 'min' => 1, 'max' => 555);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string100000';
     $rules = array('string100000', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string100000', 'length', 'min' => 1, 'max' => 100000);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'textField';
     $rules = array('textField', 'type', 'type' => 'text');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longTextField';
     $rules = array('longTextField', 'type', 'type' => 'longtext');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'dateField';
     $rules = array('dateField', 'type', 'type' => 'date');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'booleanField';
     $rules = array('booleanField', 'boolean');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'integerField';
     $rules = array('integerField', 'type', 'type' => 'integer');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'dateTimeField';
     $rules = array('dateTimeField', 'type', 'type' => 'datetime');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'urlField';
     $rules = array('urlField', 'url');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'floatField';
     $rules = array('floatField', 'type', 'type' => 'float');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longTextField';
     $rules = array('longTextField', 'type', 'type' => 'longtext');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'blobField';
     $rules = array('blobField', 'type', 'type' => 'blob');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longBlobField';
     $rules = array('longBlobField', 'type', 'type' => 'longblob');
     $metadata['Account']['rules'][] = $rules;
     Account::setMetadata($metadata);
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $messageLogger = new MessageLogger();
     $beforeRowCount = DatabaseCompatibilityUtil::getTableRowsCountTotal();
     InstallUtil::autoBuildDatabase($messageLogger);
     $afterRowCount = DatabaseCompatibilityUtil::getTableRowsCountTotal();
     $this->assertEquals($beforeRowCount, $afterRowCount);
     //Check Account fields
     $tableName = RedBeanModel::getTableName('Account');
     $columns = R::$writer->getColumns($tableName);
     $this->assertEquals('text', $columns['newfield']);
     $this->assertEquals('varchar(128)', $columns['string128']);
     $this->assertEquals('text', $columns['string555']);
     $this->assertEquals('longtext', $columns['string100000']);
     $this->assertEquals('text', $columns['textfield']);
     $this->assertEquals('date', $columns['datefield']);
     $this->assertEquals('tinyint(1)', $columns['booleanfield']);
     $this->assertEquals('int(11) unsigned', $columns['integerfield']);
     $this->assertEquals('datetime', $columns['datetimefield']);
     $this->assertEquals('varchar(255)', $columns['urlfield']);
     $this->assertEquals('double', $columns['floatfield']);
     $this->assertEquals('longtext', $columns['longtextfield']);
     $this->assertEquals('blob', $columns['blobfield']);
     $this->assertEquals('longblob', $columns['longblobfield']);
     $account = new Account();
     $account->name = 'Test Name';
     $account->owner = $super;
     $randomString = str_repeat("Aa", 64);
     $account->string128 = $randomString;
     $this->assertTrue($account->save());
     $metadata = Account::getMetadata();
     foreach ($metadata['Account']['rules'] as $key => $rule) {
         if ($rule[0] == 'string128' && $rule[1] == 'length') {
             $metadata['Account']['rules'][$key]['max'] = 64;
         }
     }
     Account::setMetadata($metadata);
     InstallUtil::autoBuildDatabase($messageLogger);
     RedBeanModel::forgetAll();
     $modifiedAccount = Account::getById($account->id);
     $this->assertEquals($randomString, $modifiedAccount->string128);
     //Check Account fields
     $tableName = RedBeanModel::getTableName('Account');
     $columns = R::$writer->getColumns($tableName);
     $this->assertEquals('varchar(128)', $columns['string128']);
 }
Пример #24
0
 public function testSetParentOfGroup_ieBelongsToSideOfRelation()
 {
     $group1 = new Group();
     $group1->name = 'Monotremes';
     $this->assertTrue($group1->save());
     $group2 = new Group();
     $group2->name = 'Platypuses';
     $this->assertTrue($group2->save());
     // Test from the many side.
     $group1->groups->add($group2);
     $this->assertTrue($group1->save());
     $this->assertTrue($group1->contains($group2));
     unset($group1);
     unset($group2);
     RedBeanModel::forgetAll();
     $group1 = Group::getByName('Monotremes');
     $this->assertEquals(1, count($group1->groups));
     $group2 = Group::getByName('Platypuses');
     $this->assertTrue($group1->contains($group2));
     $this->assertTrue($group2->group->isSame($group1));
     $group1->groups->remove($group2);
     $this->assertTrue($group2->save());
     $this->assertFalse($group1->contains($group2));
     $group2->group = $group1;
     $this->assertTrue($group2->save());
     $group1->forget();
     $group2->forget();
     // Test from the belongs to side.
     $group1 = Group::getByName('Monotremes');
     $this->assertEquals(1, count($group1->groups));
     $group2 = Group::getByName('Platypuses');
     $this->assertTrue($group2->group->isSame($group1));
     $this->assertTrue($group1->contains($group2));
 }
Пример #25
0
 public function testRightsPropagationViaRoles()
 {
     $parentRole = Role::getByName('Sales Manager');
     $childRole = Role::getByName('Sales Person');
     $childChildRole = Role::getByName('Junior Sales Person');
     $userInParentRole = $parentRole->users[0];
     $userInChildRole = $childRole->users[0];
     $userInChildChildRole = $childChildRole->users[0];
     $this->assertEquals(Right::DENY, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInChildRole->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $this->assertTrue($userInChildRole->save());
     $this->assertEquals(Right::ALLOW, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::ALLOW, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInParentRole->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API, Right::DENY);
     $this->assertTrue($userInParentRole->save());
     $this->assertEquals(Right::ALLOW, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInParentRole->removeRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $this->assertTrue($userInParentRole->save());
     $this->assertEquals(Right::ALLOW, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::ALLOW, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInChildRole->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API, Right::DENY);
     $this->assertTrue($userInChildRole->save());
     $this->assertEquals(Right::DENY, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInParentRole->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $this->assertTrue($userInParentRole->save());
     $this->assertEquals(Right::DENY, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::ALLOW, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInParentRole->removeRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $this->assertTrue($userInParentRole->save());
     $this->assertEquals(Right::DENY, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInChildRole->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $this->assertTrue($userInChildRole->save());
     $this->assertEquals(Right::ALLOW, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::ALLOW, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInChildRole->removeRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $this->assertTrue($userInChildRole->save());
     $this->assertEquals(Right::DENY, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $userInChildChildRole->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $this->assertTrue($userInChildChildRole->save());
     $this->assertEquals(Right::ALLOW, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::ALLOW, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::ALLOW, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     Right::deleteAll();
     //Clear the cache since the method above removeAll calls directly to the database.
     RightsCache::forgetAll();
     $userInParentRoleId = $userInParentRole->id;
     $userInChildRoleId = $userInChildRole->id;
     $userInChildChildRoleId = $userInChildChildRole->id;
     RedBeanModel::forgetAll();
     unset($userInParentRole);
     unset($userInChildRole);
     unset($userInChildChildRole);
     $userInParentRole = User::getById($userInParentRoleId);
     $userInChildRole = User::getById($userInChildRoleId);
     $userInChildChildRole = User::getById($userInChildChildRoleId);
     $this->assertEquals(Right::DENY, $userInParentRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
     $this->assertEquals(Right::DENY, $userInChildChildRole->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API));
 }
 /**
  * Test when user change role, from one to another to null
  * @depends testRoleChangeOrDeleteScenario2
  */
 public function testRoleChangeOrDeleteScenario4()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $job = new ReadPermissionSubscriptionUpdateForAccountJob();
     $jobBasedOnBuildTable = new ReadPermissionSubscriptionUpdateForAccountFromBuildTableJob();
     Yii::app()->jobQueue->deleteAll();
     $this->deleteAllModelsAndRecordsFromReadPermissionTable('Account');
     Yii::app()->jobQueue->deleteAll();
     sleep(1);
     $user1 = self::$johnny;
     $user2 = self::$billy;
     $user3 = self::$david;
     $account = AccountTestHelper::createAccountByNameForOwner('Forth Account For Roles', $user1);
     Yii::app()->jobQueue->deleteAll();
     // Set user role
     $role1 = Role::getByName('Role1');
     $role2 = Role::getByName('Role2');
     $role3 = Role::getByName('Role3');
     $role4 = Role::getByName('Role4');
     // Just to trigger role changes
     Yii::app()->jobQueue->deleteAll();
     $user1->role = null;
     $this->assertTrue($user1->save());
     RedBeanModel::forgetAll();
     ReadPermissionsOptimizationUtil::rebuild();
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccount', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(2, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals($user1->id, $rows[1]['userid']);
     $this->assertEquals($account->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     // Now set $role1 for $user1
     Yii::app()->jobQueue->deleteAll();
     $user1->role = $role1;
     $this->assertTrue($user1->save());
     RedBeanModel::forgetAll();
     ReadPermissionsOptimizationUtil::rebuild();
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccount', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(3, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals($user1->id, $rows[1]['userid']);
     $this->assertEquals($account->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     $this->assertEquals($user2->id, $rows[2]['userid']);
     $this->assertEquals($account->id, $rows[2]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[2]['subscriptiontype']);
     // Now set $role4 for $user1
     Yii::app()->jobQueue->deleteAll();
     $user1->role = $role4;
     $this->assertTrue($user1->save());
     RedBeanModel::forgetAll();
     ReadPermissionsOptimizationUtil::rebuild();
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccount', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(4, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals($user1->id, $rows[1]['userid']);
     $this->assertEquals($account->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     $this->assertEquals($user2->id, $rows[2]['userid']);
     $this->assertEquals($account->id, $rows[2]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_DELETE, $rows[2]['subscriptiontype']);
     $this->assertEquals($user3->id, $rows[3]['userid']);
     $this->assertEquals($account->id, $rows[3]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[3]['subscriptiontype']);
     // Now set $role1 for $user1
     Yii::app()->jobQueue->deleteAll();
     $user1->role = null;
     $this->assertTrue($user1->save());
     RedBeanModel::forgetAll();
     ReadPermissionsOptimizationUtil::rebuild();
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccount', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(4, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals($user1->id, $rows[1]['userid']);
     $this->assertEquals($account->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     $this->assertEquals($user2->id, $rows[2]['userid']);
     $this->assertEquals($account->id, $rows[2]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_DELETE, $rows[2]['subscriptiontype']);
     $this->assertEquals($user3->id, $rows[3]['userid']);
     $this->assertEquals($account->id, $rows[3]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_DELETE, $rows[3]['subscriptiontype']);
 }
 /**
  * @depends testUpdate
  */
 public function testUpdateWithRelations()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $testModel = new ApiTestModelItem();
     $testModel->firstName = "Ruth";
     $testModel->lastName = "Tester";
     $testModel->string = "aString";
     $this->assertTrue($testModel->save());
     $compareData = $this->getModelToApiDataUtilData($testModel);
     $testModel->forget();
     $testItem4 = new ApiTestModelItem4();
     $testItem4->name = 'John7';
     $this->assertTrue($testItem4->save());
     $testItem3_1 = new ApiTestModelItem3();
     $testItem3_1->name = 'Kevin7';
     $this->assertTrue($testItem3_1->save());
     $testItem3_2 = new ApiTestModelItem3();
     $testItem3_2->name = 'Jim7';
     $this->assertTrue($testItem3_2->save());
     $testItemRelated = new ApiTestModelItem();
     $testItemRelated->lastName = 'Cohens7';
     $testItemRelated->string = 'aString';
     $this->assertTrue($testItemRelated->save());
     $data['modelRelations'] = array('modelItems3' => array(array('action' => 'add', 'modelId' => $testItem3_1->id, 'modelClassName' => 'ApiTestModelItem3'), array('action' => 'add', 'modelId' => $testItem3_2->id, 'modelClassName' => 'ApiTestModelItem3')), 'modelItems4' => array(array('action' => 'add', 'modelId' => $testItem4->id, 'modelClassName' => 'ApiTestModelItem4')), 'modelItems' => array(array('action' => 'add', 'modelId' => $testItemRelated->id, 'modelClassName' => 'ApiTestModelItem')));
     $data['firstName'] = 'Michael6';
     $group = static::$randomNonEveryoneNonAdministratorsGroup;
     $explicitReadWriteModelPermissions = array('type' => 2, 'nonEveryoneGroup' => $group->id);
     $data['explicitReadWriteModelPermissions'] = $explicitReadWriteModelPermissions;
     $compareData['explicitReadWriteModelPermissions'] = $explicitReadWriteModelPermissions;
     $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     unset($response['data']['modifiedDateTime']);
     unset($compareData['modifiedDateTime']);
     $compareData['firstName'] = 'Michael6';
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($compareData, $response['data']);
     RedBeanModel::forgetAll();
     $updatedModel = ApiTestModelItem::getById($compareData['id']);
     $this->assertEquals(2, count($updatedModel->modelItems3));
     $this->assertEquals($testItem3_1->id, $updatedModel->modelItems3[0]->id);
     $this->assertEquals($testItem3_2->id, $updatedModel->modelItems3[1]->id);
     $this->assertEquals(1, count($updatedModel->modelItems4));
     $this->assertEquals($testItem4->id, $updatedModel->modelItems4[0]->id);
     $this->assertEquals(1, count($updatedModel->modelItems));
     $this->assertEquals($testItemRelated->id, $updatedModel->modelItems[0]->id);
     // Now test remove relations
     $data['modelRelations'] = array('modelItems3' => array(array('action' => 'remove', 'modelId' => $testItem3_1->id, 'modelClassName' => 'ApiTestModelItem3'), array('action' => 'remove', 'modelId' => $testItem3_2->id, 'modelClassName' => 'ApiTestModelItem3')), 'modelItems4' => array(array('action' => 'remove', 'modelId' => $testItem4->id, 'modelClassName' => 'ApiTestModelItem4')), 'modelItems' => array(array('action' => 'remove', 'modelId' => $testItemRelated->id, 'modelClassName' => 'ApiTestModelItem')));
     $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     RedBeanModel::forgetAll();
     $updatedModel = ApiTestModelItem::getById($compareData['id']);
     $this->assertEquals(0, count($updatedModel->modelItems3));
     $this->assertEquals(0, count($updatedModel->modelItems4));
     $this->assertEquals(0, count($updatedModel->modelItems));
     // Test with invalid action
     $data['modelRelations'] = array('modelItems' => array(array('action' => 'invalidAction', 'modelId' => $testItemRelated->id, 'modelClassName' => 'ApiTestModelItem')));
     $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_FAILURE, $response['status']);
     // Test with invalid relation
     $data['modelRelations'] = array('aaad' => array(array('action' => 'remove', 'modelId' => $testItemRelated->id, 'modelClassName' => 'ApiTestModelItem')));
     $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_FAILURE, $response['status']);
     // Test with invalid related model id
     $data['modelRelations'] = array('modelItems3' => array(array('action' => 'remove', 'modelId' => 345, 'modelClassName' => 'ApiTestModelItem3')));
     $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_FAILURE, $response['status']);
 }
 /**
  * @depends testCreateWithRelations
  */
 public function testUpdateWithRelations()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/xml', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $account = AccountTestHelper::createAccountByNameForOwner('Factor X', $super);
     $account1 = AccountTestHelper::createAccountByNameForOwner('Miko', $super);
     $account2 = AccountTestHelper::createAccountByNameForOwner('Troter', $super);
     $contact = ContactTestHelper::createContactByNameForOwner('Simon', $super);
     $redBeanModelToApiDataUtil = new RedBeanModelToApiDataUtil($account);
     $compareData = $redBeanModelToApiDataUtil->getData();
     $account->forget();
     $data['modelRelations'] = array('accounts' => array(array('action' => 'add', 'modelId' => $account1->id, 'modelClassName' => 'Account'), array('action' => 'add', 'modelId' => $account2->id, 'modelClassName' => 'Account')), 'contacts' => array(array('action' => 'add', 'modelId' => $contact->id, 'modelClassName' => 'Contact')));
     $data['name'] = 'Zurmo Inc.';
     $response = ApiRestTestHelper::createXmlApiCall($this->serverUrl . '/test.php/accounts/account/api/update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = XML2Array::createArray($response);
     unset($response['data']['modifiedDateTime']);
     unset($compareData['modifiedDateTime']);
     $compareData['name'] = 'Zurmo Inc.';
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($compareData, $response['data']);
     RedBeanModel::forgetAll();
     $account = Account::getById($compareData['id']);
     $this->assertEquals(2, count($account->accounts));
     $this->assertEquals($account1->id, $account->accounts[0]->id);
     $this->assertEquals($account2->id, $account->accounts[1]->id);
     $this->assertEquals(1, count($account->contacts));
     $this->assertEquals($contact->id, $account->contacts[0]->id);
     $account1 = Account::getById($account1->id);
     $this->assertEquals($account->id, $account1->account->id);
     $account2 = Account::getById($account2->id);
     $this->assertEquals($account->id, $account2->account->id);
     $contact = Contact::getById($contact->id);
     $this->assertEquals($account->id, $contact->account->id);
     // Now test remove relations
     $data['modelRelations'] = array('accounts' => array(array('action' => 'remove', 'modelId' => $account1->id, 'modelClassName' => 'Account'), array('action' => 'remove', 'modelId' => $account2->id, 'modelClassName' => 'Account')), 'contacts' => array(array('action' => 'remove', 'modelId' => $contact->id, 'modelClassName' => 'Contact')));
     $response = ApiRestTestHelper::createXmlApiCall($this->serverUrl . '/test.php/accounts/account/api/update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = XML2Array::createArray($response);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     RedBeanModel::forgetAll();
     $updatedModel = Account::getById($compareData['id']);
     $this->assertEquals(0, count($updatedModel->accounts));
     $this->assertEquals(0, count($updatedModel->contacts));
     $account1 = Account::getById($account1->id);
     $this->assertLessThanOrEqual(0, $account1->account->id);
     $account2 = Account::getById($account2->id);
     $this->assertLessThanOrEqual(0, $account2->account->id);
     $contact = Contact::getById($contact->id);
     $this->assertLessThanOrEqual(0, $contact->account->id);
 }
 /**
  * @depends testGroupsContainingGroupsAndContains
  */
 public function testPerformanceOfFastContainsUserByGroupId()
 {
     $runs = 10;
     $u = array();
     for ($i = 0; $i < 5; $i++) {
         $u[$i] = User::getByUsername("uuuuu{$i}");
     }
     $startTime = microtime(true);
     for ($i = 0; $i < $runs; $i++) {
         RedBeanModel::forgetAll();
         $a = Group::getByName('AAA');
         $this->assertTrue($a->contains($u[0]));
         $this->assertTrue($a->contains($u[1]));
         $this->assertTrue($a->contains($u[2]));
         $this->assertTrue($a->contains($u[3]));
         $this->assertTrue($a->contains($u[4]));
     }
     $endTime = microtime(true);
     $totalTimeSlow = $endTime - $startTime;
     $groupId = Group::getByName('AAA')->id;
     $userId0 = User::getByUsername("uuuuu0")->id;
     $userId1 = User::getByUsername("uuuuu1")->id;
     $userId2 = User::getByUsername("uuuuu2")->id;
     $userId3 = User::getByUsername("uuuuu3")->id;
     $userId4 = User::getByUsername("uuuuu4")->id;
     $startTime = microtime(true);
     for ($i = 0; $i < $runs; $i++) {
         $this->assertTrue(self::fastContainsUserByGroupId($groupId, $userId0));
         $this->assertTrue(self::fastContainsUserByGroupId($groupId, $userId1));
         $this->assertTrue(self::fastContainsUserByGroupId($groupId, $userId2));
         $this->assertTrue(self::fastContainsUserByGroupId($groupId, $userId3));
         $this->assertTrue(self::fastContainsUserByGroupId($groupId, $userId4));
     }
     $endTime = microtime(true);
     $totalTimeOptimized = $endTime - $startTime;
     $ratio = $totalTimeSlow / $totalTimeOptimized;
     $expectedMinimumRatio = 20;
     $this->assertGreaterThan($expectedMinimumRatio, $ratio);
 }
Пример #30
0
 public function testManyToManyRelationInTheMiddleOfTheInheritanceHierarchy()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $accounts = Account::getByName('anAccount');
     $possibleDerivationPaths = array(array('SecurableItem', 'OwnedSecurableItem', 'Account'), array('SecurableItem', 'OwnedSecurableItem', 'Person', 'Contact'), array('SecurableItem', 'OwnedSecurableItem', 'Opportunity'));
     $model = new TestManyManyRelationToItemModel();
     $model->items->add($accounts[0]);
     $this->assertTrue($model->save());
     $item = Item::getById($model->items[0]->getClassId('Item'));
     $this->assertTrue($item instanceof Item);
     $this->assertFalse($item instanceof Account);
     $this->assertTrue($item->isSame($accounts[0]));
     $account2 = $item->castDown($possibleDerivationPaths);
     $this->assertTrue($account2->isSame($accounts[0]));
     $id = $model->id;
     unset($model);
     RedBeanModel::forgetAll();
     $model = TestManyManyRelationToItemModel::getById($id);
     $this->assertEquals(1, $model->items->count());
     $this->assertTrue($model->items[0] instanceof Item);
     $this->assertFalse($model->items[0] instanceof Account);
     $this->assertTrue($model->items[0]->isSame($accounts[0]));
     $account3 = $model->items[0]->castDown($possibleDerivationPaths);
     $this->assertTrue($account3->isSame($accounts[0]));
 }