diff options
Diffstat (limited to 'tests')
75 files changed, 1767 insertions, 3112 deletions
diff --git a/tests/acceptance/.gitignore b/tests/acceptance/.gitignore deleted file mode 100644 index 3c3629e647f..00000000000 --- a/tests/acceptance/.gitignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/tests/acceptance/package.json b/tests/acceptance/package.json deleted file mode 100644 index daeb245b51a..00000000000 --- a/tests/acceptance/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "specs", - "version": "0.0.0", - "description": "ownCloud specs for automated acceptance tests", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Felix Böhm", - "dependencies": { - "protractor": "^1.1.1", - "request": "^2.40.0", - "xml2js": "^0.4.4", - "jasmine-spec-reporter": "^0.6.0", - "phantomjs": "^1.9.7-15" - }, - "devDependencies": { - } -} diff --git a/tests/acceptance/protractor_conf.js b/tests/acceptance/protractor_conf.js deleted file mode 100644 index e89e79e5478..00000000000 --- a/tests/acceptance/protractor_conf.js +++ /dev/null @@ -1,103 +0,0 @@ -// An example configuration file. -exports.config = { - // Do not start a Selenium Standalone sever - only run this using chrome. - chromeOnly: true, - chromeDriver: './node_modules/protractor/selenium/chromedriver', - - // Capabilities to be passed to the webdriver instance. - // See https://sites.google.com/a/chromium.org/chromedriver/capabilities - capabilities: { - 'browserName': 'chrome', - 'chromeOptions': { - 'args': ['show-fps-counter=true', '--test-type', '--ignore-certificate-errors'] - } - }, - - // Use on Commmandline: - // protractor ... --params.login.user=abc --params.login.password=123 - params: { - baseUrl: "http://127.0.0.1/", - login: { - user: 'admin', - password: 'password' - } - }, - - suites: { - install: 'tests/install/**/*_spec.js', - login: 'tests/login/**/*_spec.js', - apps: 'tests/apps/**/*_spec.js', - files: 'tests/files/**/*_spec.js', - share: 'tests/share/**/*_spec.js', - }, - - // seleniumAddress: 'http://0.0.0.0:4444/wd/hub', - - // Options to be passed to Jasmine-node. - jasmineNodeOpts: { - silent: true, - showColors: true, - onComplete: null, - isVerbose: true, - includeStackTrace: true, - defaultTimeoutInterval: 180000 - }, - - onPrepare: function(){ - global.isAngularSite = function(flag){ - browser.ignoreSynchronization = !flag; - }; - browser.driver.manage().window().setSize(1000, 800); - browser.driver.manage().window().maximize(); - - require('jasmine-spec-reporter'); - // add jasmine spec reporter - var spec_reporter = new jasmine.SpecReporter({ - displayStacktrace: false, // display stacktrace for each failed assertion - displayFailuresSummary: false, // display summary of all failures after execution - displaySuccessfulSpec: true, // display each successful spec - displayFailedSpec: true, // display each failed spec - displaySkippedSpec: false, // display each skipped spec - displaySpecDuration: true, // display each spec duration - colors: { - success: 'green', - failure: 'red', - skipped: 'cyan' - }, - prefixes: { - success: '✓ ', - failure: '✗ ', - skipped: '- ' - } - }); - global.display = spec_reporter.display; - jasmine.getEnv().addReporter(spec_reporter); - } -}; - - -// Headless testing with Phantomjs -// capabilities: { -// 'browserName': 'phantomjs', -// -// /* -// * Can be used to specify the phantomjs binary path. -// * This can generally be ommitted if you installed phantomjs globally. -// */ -// 'phantomjs.binary.path':'./node_modules/phantomjs/bin/phantomjs', -// -// /* -// * Command line arugments to pass to phantomjs. -// * Can be ommitted if no arguments need to be passed. -// * Acceptable cli arugments: https://github.com/ariya/phantomjs/wiki/API-Reference#wiki-command-line-options -// */ -// 'phantomjs.cli.args':['--logfile=PATH', '--loglevel=DEBUG'] -// }, - -// TODO: Mobile? See: https://github.com/angular/protractor/blob/master/docs/browser-setup.md#setting-up-protractor-with-appium---androidchrome -// multiCapabilities: [{ -// 'browserName': 'firefox' -// }, { -// 'browserName': 'chrome' -// }] - diff --git a/tests/acceptance/readme.md b/tests/acceptance/readme.md deleted file mode 100644 index 2bf42c70a0f..00000000000 --- a/tests/acceptance/readme.md +++ /dev/null @@ -1,80 +0,0 @@ -ownCloud Acceptance Tests -========================= - - -Setup ------ - -Install node.js and run the following to install the dependencies - -``` -npm install -``` - -Install the webdriver -``` -./node_modules/protractor/bin/webdriver-manager update -``` - -Install protractor as global command ( optional ) -``` -npm install -g protractor -``` - -Run ---- - -Run the tests with protractor -``` -protractor protractor_conf.js -``` - -Run only a specific test suite or spec -``` -protractor protractor_conf.js --suite install -protractor protractor_conf.js --params.baseUrl="http://127.0.0.1/ownClouds/test-community-7.0.1/" --suite=login -protractor protractor_conf.js --params.baseUrl="http://127.0.0.1/ownClouds/test-community-7.0.1/" --specs tests/login/newUser_spec.js -``` - -More Test Suites ----------------- - -You can find and define suites in ```protractor_conf.js``` - -Install suite: Run this suite on a not yet installed ownCloud, it will install during the tests - -After installation tests should run without the "First Run Wizard" app because of timing issues. -Disable the app on the server with - -``` -php occ app:disable firstrunwizard -``` - -Page Objects ------------- - -The ```tests/pages``` folder contains page objects. -A page object describes a webpage, gathers selectors and provides functions for actions on the page. - -In the specs these higher level functionality can be reused and the tests become nice and readable. - -Development ------------ - -A good starting point is the login suite in the login folder and the login page object. - -If you want to start only a single test (it) or collection of tests (describe) use: - -* iit to run a single test -* ddescribe to run only this collection - -You can also use - -* xit to exclude this test -* xdescribe to exclude this collection - -For deeper insights and api docs have a look at - -* Protractor, [https://github.com/angular/protractor](https://github.com/angular/protractor) -* Jasmine, [https://github.com/pivotal/jasmine](https://github.com/pivotal/jasmine) - diff --git a/tests/acceptance/screenshots/.gitignore b/tests/acceptance/screenshots/.gitignore deleted file mode 100644 index bc7947beb62..00000000000 --- a/tests/acceptance/screenshots/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -* - -!.gitignore
\ No newline at end of file diff --git a/tests/acceptance/tests/apps/apps_spec.js b/tests/acceptance/tests/apps/apps_spec.js deleted file mode 100644 index 0b7937f97ab..00000000000 --- a/tests/acceptance/tests/apps/apps_spec.js +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2014 - * - * This file is licensed under the Affero General Public License version 3 - * or later. - * - * See the COPYING-README file. - * - */ - -/* global element, browser, require */ -var Page = require('../helper/page.js'); -var AppsPage = require('../pages/apps.page.js'); -var LoginPage = require('../pages/login.page.js'); - -describe('Enabling apps', function() { - var testApp; - var params = browser.params; - var loginPage; - var appsPage; - var testGroup; - - beforeEach(function() { - isAngularSite(false); - // app to test, must have a navigation entry and allow group restriction - testApp = 'calendar'; - // group to test, additionally to "admin" - testGroup = 'group1'; - loginPage = new LoginPage(params.baseUrl); - appsPage = new AppsPage(params.baseUrl); - - loginPage.get(); - loginPage.login(params.login.user, params.login.password); - appsPage.get(); - }); - - afterEach(function() { - Page.logout(); - }); - - it('user should see enabled app', function() { - appsPage.enableApp(testApp, true, null).then(function() { - // reload page - appsPage.get(); - Page.toggleAppsMenu(); - expect(element(Page.appMenuEntryId(testApp + '_index')).isPresent()).toBe(true); - }); - }); - - it('user should not see disabled app', function() { - appsPage.enableApp(testApp, false, null).then(function() { - // reload page - appsPage.get(); - Page.toggleAppsMenu(); - expect(element(Page.appMenuEntryId(testApp + '_index')).isPresent()).toBe(false); - }); - }); - - it('group member should see app when enabled in that group', function() { - appsPage.enableApp(testApp, true, ['admin']).then(function() { - // reload page - appsPage.get(); - Page.toggleAppsMenu(); - expect(element(Page.appMenuEntryId(testApp + '_index')).isPresent()).toBe(true); - }); - }); - - it('group member should not see app when enabled in another group', function() { - appsPage.enableApp(testApp, true, ['group1']).then(function() { - // reload page - appsPage.get(); - Page.toggleAppsMenu(); - expect(element(Page.appMenuEntryId(testApp + '_index')).isPresent()).toBe(false); - }); - }); - - it('group member should see app when all groups deselected (all case)', function() { - // when selecting no groups, it will show "All" even though the checkboxes - // are not checked - appsPage.enableApp(testApp, true, []).then(function() { - // reload page - appsPage.get(); - Page.toggleAppsMenu(); - expect(element(Page.appMenuEntryId(testApp + '_index')).isPresent()).toBe(false); - }); - }); -}); diff --git a/tests/acceptance/tests/files/folder_spec.js b/tests/acceptance/tests/files/folder_spec.js deleted file mode 100644 index 0b143ea0d33..00000000000 --- a/tests/acceptance/tests/files/folder_spec.js +++ /dev/null @@ -1,86 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var FilesPage = require('../pages/files.page.js'); - - -// ============================ FOLDERS ============================================================== // -// =================================================================================================== // - -describe('Folders', function() { - var params = browser.params; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - it('should create a new folder', function() { - filesPage.createNewFolder('testFolder'); - expect(filesPage.listFiles()).toContain('testFolder'); - }); - - it('should not create new folder if foldername already exists', function() { - filesPage.createNewFolder('testFolder'); - var warning = by.css('.tipsy-inner'); - expect(filesPage.alertWarning.isDisplayed()).toBeTruthy(); - }); - - it('should delete a folder', function() { - filesPage.get(); // TODO: reload cause warning alerts don't disappear - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.deleteFile('testFolder'); - browser.sleep(800); - expect(filesPage.listFiles()).not.toContain('testFolder'); - }); -}); - -// ============================== SUB FOLDERS ======================================================== // -// =================================================================================================== // - -describe('Subfolders', function() { - var params = browser.params; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - - it('should go into folder and create subfolder', function() { - var folder = 'hasSubFolder'; - filesPage.createNewFolder(folder); - filesPage.goInToFolder(folder); - filesPage.createNewFolder('SubFolder'); - filesPage.createNewFolder('SubFolder2'); - expect(filesPage.listFiles()).toContain('SubFolder', 'SubFolder2'); - }); - - it('should rename a subfolder', function() { - filesPage.renameFile('SubFolder2', 'NewSubFolder'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.listFiles()).toContain('NewSubFolder'); - }); - - it('should delete a subfolder', function() { - filesPage.deleteFile('SubFolder'); - browser.sleep(800); - expect(filesPage.listFiles()).not.toContain('SubFolder'); - }); - - it('should delete a folder containing a subfolder', function() { - filesPage.get(); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.deleteFile('hasSubFolder'); - browser.sleep(800); - expect(filesPage.listFiles()).not.toContain('hasSubFolder'); - }); -});
\ No newline at end of file diff --git a/tests/acceptance/tests/files/rename_spec.js b/tests/acceptance/tests/files/rename_spec.js deleted file mode 100644 index a4dfdfa9613..00000000000 --- a/tests/acceptance/tests/files/rename_spec.js +++ /dev/null @@ -1,140 +0,0 @@ -var Page = require('../helper/page.js') -var LoginPage = require('../pages/login.page.js'); -var FilesPage = require('../pages/files.page.js'); - -// =============================================== RENAME FOLDER =================================== // -// ================================================================================================= // - -describe('Rename Folder', function() { - var params = browser.params; - var page; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - page = new Page(); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - it('should rename a folder', function() { - filesPage.createNewFolder('testFolder'); - filesPage.renameFile('testFolder', 'newFolder'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.listFiles()).toContain('newFolder'); - }); - - it('should show alert message if foldername already in use', function() { - filesPage.createNewFolder('testFolder'); - filesPage.renameFile('testFolder', 'newFolder'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.alertWarning.isDisplayed()).toBeTruthy(); - }); - - it('should show alert message if using forbidden characters', function() { - filesPage.renameFile('newFolder', 'new:Folder'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.alertWarning.isDisplayed()).toBeTruthy(); - }); - - it('should rename a file using special characters', function() { - filesPage.get(); // TODO: reload cause warning alerts don't disappear - filesPage.renameFile('testFolder', 'sP€c!@L B-)'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.listFiles()).toContain('sP€c!@L B-)'); - }); - - it('should show alert message if newName is empty', function() { - filesPage.renameFile('newFolder', ""); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.alertWarning.isDisplayed()).toBeTruthy(); - filesPage.deleteFile('newFolder'); - filesPage.deleteFile('sP€c!@L B-)'); - }); -}); - -// =============================================== RENAME FILES ==================================== // -// ================================================================================================= // - -describe('Rename Files', function() { - var params = browser.params; - var page; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - page = new Page(); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - it('should rename a txt file', function() { - filesPage.createNewTxtFile('testText'); - filesPage.renameFile('testText.txt', 'newText.txt'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.listFiles()).toContain('newText'); - }); - - it('should show alert message if filename is already in use', function() { - filesPage.createNewTxtFile('testText'); - filesPage.renameFile('testText.txt', 'newText.txt'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.alertWarning.isDisplayed()).toBeTruthy(); - }); - - // it('should rename a file with the same name but changed capitalization', function() { - // browser.takeScreenshot().then(function (png) { - - // new Screenshot(png, 'SameNameCapitalization1.png'); - // filesPage.renameFile('testText.txt', 'NewText.txt'); - // browser.wait(function() { - // return(filesPage.listFiles()); - // }, 3000); - // }); - // browser.takeScreenshot().then(function (png) { - // new Screenshot(png, 'SameNameCapitalization2.png'); - // }); - // expect(filesPage.listFiles()).toContain('NewText.txt'); - // }); - - it('should rename a file using special characters', function() { - filesPage.renameFile('newText.txt', 'sP€c!@L B-).txt'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.listFiles()).toContain('sP€c!@L B-)'); - }); - - it('should show alert message if newName is empty', function() { - filesPage.get(); // TODO: reload cause warning alerts don't disappear - filesPage.renameFile('sP€c!@L B-).txt', ''); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.alertWarning.isDisplayed()).toBeTruthy(); - }); - - it('should rename a file by taking off the file extension', function() { - filesPage.renameFile('testText.txt', 'Without Subfix'); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - expect(filesPage.listFiles()).toContain('Without Subfix'); - filesPage.deleteFile('Without Subfix'); - filesPage.deleteFile('sP€c!@L B-).txt'); - }); -});
\ No newline at end of file diff --git a/tests/acceptance/tests/files/restore_spec.js b/tests/acceptance/tests/files/restore_spec.js deleted file mode 100644 index 3179c92835f..00000000000 --- a/tests/acceptance/tests/files/restore_spec.js +++ /dev/null @@ -1,151 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var FilesPage = require('../pages/files.page.js'); - -// ============================ RESTORE FOLDERS ====================================================== // -// =================================================================================================== // - -describe('Restore Folders', function() { - var params = browser.params; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - - it('should restore a emtpy folder that has been deleted', function() { - filesPage.createNewFolder('Empty'); - filesPage.deleteFile('Empty'); - filesPage.trashbinButton.click(); - browser.wait(function() { - return filesPage.listFiles(); - }, 5000); - filesPage.restoreFile(0); - filesPage.get(); - - - expect(filesPage.listFiles()).toContain('Empty'); - filesPage.deleteFile('Empty'); - }); - - it('should restore a folder including special characters', function() { - filesPage.createNewFolder('Sp€c!@l FölD€r'); - filesPage.deleteFile('Sp€c!@l FölD€r'); - filesPage.trashbinButton.click(); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - - filesPage.restoreFile(0); - filesPage.get(); - - expect(filesPage.listFiles()).toContain('Sp€c!@l FölD€r'); - filesPage.deleteFile('Sp€c!@l FölD€r'); - }); - - it('should restore a non empty folder that has been deleted', function() { - filesPage.createNewFolder('nonEmpty'); - filesPage.createSubFolder('nonEmpty', 'Subfolder'); - filesPage.createNewTxtFile('TextFile'); - filesPage.get(); - filesPage.deleteFile('nonEmpty'); - filesPage.trashbinButton.click(); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.restoreFile(0); - filesPage.get(); - expect(filesPage.listFiles()).toContain('nonEmpty'); - }); - - it('should restore a folder whose name is currently in use', function() { - - // create and delete non empty folder - filesPage.createNewFolder('sameFolderName'); - filesPage.deleteFile('sameFolderName'); - filesPage.createNewFolder('sameFolderName'); - filesPage.trashbinButton.click(); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.restoreFile(0); - filesPage.get(); - expect(filesPage.listFiles()).toContain('sameFolderName (Wiederhergestellt)'); //for german ownclouds - filesPage.deleteFile('sameFolderName'); - filesPage.deleteFile('sameFolderName (Wiederhergestellt)'); - }); - - it('should restore a sub folder when the root folder has been deleted separately', function() { - filesPage.getSubFolder('nonEmpty', 'Subfolder'); - filesPage.createNewTxtFile('IsInSub'); - filesPage.getFolder('nonEmpty'); - filesPage.deleteFile('Subfolder'); - filesPage.get() - filesPage.deleteFile('nonEmpty'); - filesPage.trashbinButton.click(); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.restoreFile(1); - filesPage.get(); - expect(filesPage.listFiles()).toContain('Subfolder'); - }); -}); - - -// ============================ RESTORE FOLDERS ====================================================== // -// =================================================================================================== // - -describe('Restore Files', function() { - var params = browser.params; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - it('should restore a file thas has been deleted', function() { - filesPage.createNewTxtFile('restoreMe'); - filesPage.deleteFile('restoreMe.txt'); - filesPage.trashbinButton.click(); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.restoreFile(0); - filesPage.get(); - expect(filesPage.listFiles()).toContain('restoreMe'); - filesPage.deleteFile('restoreMe.txt'); - }); - - it('should restore a file including special characters', function() { - filesPage.createNewTxtFile('Sp€c!@L RésTör€'); - filesPage.deleteFile('Sp€c!@L RésTör€.txt'); - filesPage.trashbinButton.click(); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.restoreFile(0); - filesPage.get(); - expect(filesPage.listFiles()).toContain('Sp€c!@L RésTör€'); - filesPage.deleteFile('Sp€c!@L RésTör€.txt'); - }); - - it('should restore a file whose name is currently in use', function() { - filesPage.createNewTxtFile('sameFileName'); - filesPage.deleteFile('sameFileName.txt'); - filesPage.createNewTxtFile('sameFileName'); - filesPage.trashbinButton.click(); - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.restoreFile(0); - filesPage.get(); - expect(filesPage.listFiles()).toContain('sameFileName (Wiederhergestellt)'); //for german ownclouds - filesPage.deleteFile('sameFileName.txt'); - filesPage.deleteFile('sameFileName (Wiederhergestellt).txt'); - }); -});
\ No newline at end of file diff --git a/tests/acceptance/tests/files/search_spec.js b/tests/acceptance/tests/files/search_spec.js deleted file mode 100644 index 4df5415612c..00000000000 --- a/tests/acceptance/tests/files/search_spec.js +++ /dev/null @@ -1,26 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var FilesPage = require('../pages/files.page.js'); - -// ============================ SEARCH =============================================================== // -// =================================================================================================== // - -describe('Search', function() { - var params = browser.params; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - it('should search files by name', function() { - filesPage.createNewTxtFile('searchFile'); - filesPage.createNewFolder('searchFolder'); - filesPage.searchInput.click(); - filesPage.searchInput.sendKeys('search'); - expect(filesPage.listSelctedFiles()).toContain('searchFile', 'searchFolder'); - filesPage.deleteFile('searchFile.txt'); - filesPage.deleteFile('searchFolder'); - }); -});
\ No newline at end of file diff --git a/tests/acceptance/tests/files/sort_spec.js b/tests/acceptance/tests/files/sort_spec.js deleted file mode 100644 index b2abce59a37..00000000000 --- a/tests/acceptance/tests/files/sort_spec.js +++ /dev/null @@ -1,35 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var FilesPage = require('../pages/files.page.js'); - -// ============================ SORT ================================================================= // -// =================================================================================================== // - -describe('Sort', function() { - var params = browser.params; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - it('shloud sort files by name', function() { - expect(filesPage.firstListElem == element(filesPage.fileListElemId("documents"))).toBeTruthy; - filesPage.nameSortArrow.click(); - expect(filesPage.firstListElem == element(filesPage.fileListElemId("ownCloudUserManual.pdf"))).toBeTruthy; - }); - - it('should sort files by size', function() { - expect(filesPage.firstListElem == element(filesPage.fileListElemId("documents"))).toBeTruthy; - filesPage.sizeSortArrow.click(); - expect(filesPage.firstListElem == element(filesPage.fileListElemId("music"))).toBeTruthy; - }); - - it('should sort files by modified date', function() { - expect(filesPage.firstListElem == element(filesPage.fileListElemId("documents"))).toBeTruthy; - filesPage.createNewTxtFile('newText') - filesPage.modifiedSortArrow.click(); - expect(filesPage.firstListElem == element(filesPage.fileListElemId("newText.txt"))).toBeTruthy; - }); -});
\ No newline at end of file diff --git a/tests/acceptance/tests/files/txt_spec.js b/tests/acceptance/tests/files/txt_spec.js deleted file mode 100644 index 4e0165b18dc..00000000000 --- a/tests/acceptance/tests/files/txt_spec.js +++ /dev/null @@ -1,36 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var FilesPage = require('../pages/files.page.js'); -var Screenshot = require('../helper/screenshot.js'); - -// ============================ TXT FILES ============================================================ // -// =================================================================================================== // - -describe('Txt Files', function() { - var params = browser.params; - var filesPage; - - beforeEach(function() { - isAngularSite(false); - filesPage = new FilesPage(params.baseUrl); - filesPage.getAsUser(params.login.user, params.login.password); - }); - - it('should create a new txt file', function() { - filesPage.createNewTxtFile('testText'); - expect(filesPage.listFiles()).toContain('testText'); - }); - - it('should not create new file if filename already exists', function() { - filesPage.createNewTxtFile('testText'); - expect(filesPage.alertWarning.isDisplayed()).toBeTruthy(); - }); - - it('should delete a txt file', function() { - browser.wait(function() { - return(filesPage.listFiles()); - }, 3000); - filesPage.deleteFile('testText.txt'); - filesPage.get(); - expect(filesPage.listFiles()).not.toContain('testText') - }); -});
\ No newline at end of file diff --git a/tests/acceptance/tests/helper/page.js b/tests/acceptance/tests/helper/page.js deleted file mode 100644 index 98545032bea..00000000000 --- a/tests/acceptance/tests/helper/page.js +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2014 - * - * This file is licensed under the Affero General Public License version 3 - * or later. - * - * See the COPYING-README file. - * - */ - -/* global protractor, module, element, by, browser */ -(function() { - var Page = function() { - - }; - - Page.prototype.moveMouseTo = function(locator) { - var ele = element(locator); - return browser.actions().mouseMove(ele).perform(); - }; - - Page.toggleAppsMenu = function() { - var el = element(this.appsMenuId()); - return el.click(); - }; - - Page.logout = function() { - element(Page.settingsMenuId()).click(); - element(by.id('logout')).click(); - browser.sleep(300); - }; - - //================ LOCATOR FUNCTIONS ====================================// - Page.appsMenuId = function() { - return by.css('#header .menutoggle'); - }; - - Page.appMenuEntryId = function(appId) { - return by.css('nav #apps [data-id=\'' + appId + '\']'); - }; - - Page.settingsMenuId = function() { - return by.css('#header #settings'); - }; - - //================ UTILITY FUNCTIONS ====================================// - - /** - * Sets the selection of a multiselect element - * - * @param el select element of the multiselect - * @param {Array} id of the values to select - */ - Page.multiSelectSetSelection = function(el, selection) { - var d = protractor.promise.defer(); - var dropDownEl = element(by.css('.multiselectoptions.down')); - - el.click(); - - function processEntry(entry) { - entry.isSelected().then(function(selected) { - entry.getAttribute('id').then(function(inputId) { - // format is "ms0-option-theid", we extract that id - var dataId = inputId.split('-')[2]; - var mustBeSelected = selection.indexOf(dataId) >= 0; - // if state doesn't match what we want, toggle - - if (selected !== mustBeSelected) { - // need to click on the label, not input - entry.element(by.xpath('following-sibling::label')).click(); - // confirm that the checkbox was set - browser.wait(function() { - return entry.isSelected().then(function(newSelection) { - return newSelection === mustBeSelected; - }); - }); - } - }); - }); - } - - browser.wait(function() { - return dropDownEl.isPresent(); - }, 1000).then(function() { - dropDownEl.all(by.css('[type=checkbox]')).then(function(entries) { - for (var i = 0; i < entries.length; i++) { - processEntry(entries[i]); - } - // give it some time to save changes - browser.sleep(300).then(function() { - d.fulfill(true); - }); - }); - }); - - return d.promise; - }; - - module.exports = Page; -})(); diff --git a/tests/acceptance/tests/helper/screenshot.js b/tests/acceptance/tests/helper/screenshot.js deleted file mode 100644 index cd3a38b3143..00000000000 --- a/tests/acceptance/tests/helper/screenshot.js +++ /dev/null @@ -1,16 +0,0 @@ -(function() { - - var fs = require('fs'); - - var Screenshot = function(data, filename) { - this.screenshotPath = __dirname + '/../../screenshots/'; - - display.log('Created screenshot: ' + this.screenshotPath + filename); - var stream = fs.createWriteStream(this.screenshotPath + filename); - - stream.write(new Buffer(data, 'base64')); - stream.end(); - }; - - module.exports = Screenshot; -})();
\ No newline at end of file diff --git a/tests/acceptance/tests/install/install_spec.js b/tests/acceptance/tests/install/install_spec.js deleted file mode 100644 index ffb4e678dfe..00000000000 --- a/tests/acceptance/tests/install/install_spec.js +++ /dev/null @@ -1,63 +0,0 @@ -var InstallPage = require('../pages/install.page.js'); -var Screenshot = require('../helper/screenshot.js'); - -describe('Installation', function() { - var params = browser.params; - var installPage; - - beforeEach(function() { - isAngularSite(false); - installPage = new InstallPage(params.baseUrl); - installPage.get(); - }); - - it('should load the install page with logo', function() { - expect(installPage.installField.getAttribute('name')).toEqual("install"); - expect(installPage.installField.getAttribute('value')).toEqual('true'); - - expect(element(by.css('.logo'))).toBeDefined(); - browser.takeScreenshot().then(function (png) { - new Screenshot(png, 'InstallPage.png'); - }); - }); - - it('should not show any warnings or errors', function() { - if (installPage.warningField.isDisplayed()) { - installPage.warningField.getText().then(function(text) { - display.log(text); - }); - } - expect(installPage.warningField.isDisplayed()).toBeFalsy(); - }); - - it('should show more config after clicking the advanced config link ', function() { - // TODO: Check not displayed in a proper way - // expect(installPage.dataDirectoryConfig.isDisplayed()).toBeFalsy(); - // expect(installPage.dbConfig.isDisplayed()).toBeFalsy(); - - installPage.advancedConfigLink.click(); - - expect(installPage.dataDirectoryConfig.isDisplayed()).toBeTruthy(); - expect(installPage.dbConfig.isDisplayed()).toBeTruthy(); - - browser.takeScreenshot().then(function (png) { - new Screenshot(png, 'InstallConfig.png'); - }); - }); - - it('should install as admin with sqlite', function() { - installPage.fillAdminAccount(params.login.user, params.login.password); - - browser.takeScreenshot().then(function (png) { - new Screenshot(png, 'Credentials.png'); - }); - - installPage.installButton.click().then(function() { - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - browser.takeScreenshot().then(function (png) { - new Screenshot(png, 'InstallFinished.png'); - }); - }); - }); - -});
\ No newline at end of file diff --git a/tests/acceptance/tests/login/authentication_spec.js b/tests/acceptance/tests/login/authentication_spec.js deleted file mode 100644 index ad02db40922..00000000000 --- a/tests/acceptance/tests/login/authentication_spec.js +++ /dev/null @@ -1,88 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var UserPage = require('../pages/user.page.js'); -var FirstRunWizardPage = require('../pages/firstRunWizard.page.js'); -var Screenshot = require('../helper/screenshot.js'); - -ddescribe('Authentication', function() { - var params = browser.params; - var loginPage; - - beforeEach(function() { - isAngularSite(false); - loginPage = new LoginPage(params.baseUrl); - browser.manage().deleteAllCookies(); // logout the hard way - loginPage.get(); - - // Skip tests after first failed test - // if (this.results_.failedCount > 0) { - // // Hack: Quit by filtering upcoming tests - // this.env.specFilter = function(spec) { - // return false; - // }; - // } - }); - - it('should show a logo', function() { - expect(element(by.css('.logo'))).toBeDefined(); - }); - - it('should load the login page', function() { - browser.takeScreenshot().then(function (png) { - new Screenshot(png, 'LoginPage.png'); - }); - - expect(loginPage.isCurrentPage()).toBeTruthy(); - }); - - it('should meet the locator dependencies', function() { - expect(loginPage.loginForm.isDisplayed()).toBeTruthy(); - expect(loginPage.userInput.isDisplayed()).toBeTruthy(); - expect(loginPage.passwordInput.isDisplayed()).toBeTruthy(); - expect(loginPage.loginButton.isDisplayed()).toBeTruthy(); - }); - - it('should not load the files page url', function() { - expect(browser.getCurrentUrl()).not.toContain('index.php/apps/files/'); - }); - - it('should login admin user', function() { - // Assumes FirstRunWizard to be disabled - loginPage.login(params.login.user, params.login.password); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login with admin account', function() { - loginPage.login(params.login.user, params.login.password); - browser.takeScreenshot().then(function (png) { - new Screenshot(png, 'LoginAsAdmin.png'); - }); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - expect(loginPage.isCurrentPage()).toBeFalsy(); - }); - - it('should return to the login page after logout', function() { - loginPage.login(params.login.user, params.login.password); - expect(browser.getCurrentUrl()).not.toEqual(loginPage.url); - - loginPage.logout(); - expect(browser.getCurrentUrl()).toEqual(loginPage.url); - }); - - it('should not login with wrong credentials', function() { - loginPage.fillUserCredentilas('wrongName', 'wrongPass'); - loginPage.loginButton.click(); - browser.takeScreenshot().then(function (png) { - new Screenshot(png, 'LoginWrong.png'); - }); - expect(browser.getCurrentUrl()).not.toContain('index.php/apps/files/'); - expect(loginPage.isCurrentPage()).toBeTruthy(); - }); - - it('should have rights to visit user management after admin login', function() { - loginPage.login(params.login.user, params.login.password); - userPage = new UserPage(params.baseUrl); - userPage.get(); - expect(browser.getCurrentUrl()).toEqual(userPage.url); - }); - -});
\ No newline at end of file diff --git a/tests/acceptance/tests/login/change_password_spec.js b/tests/acceptance/tests/login/change_password_spec.js deleted file mode 100644 index 8eef444aadc..00000000000 --- a/tests/acceptance/tests/login/change_password_spec.js +++ /dev/null @@ -1,104 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var UserPage = require('../pages/user.page.js'); -var PersonalPage = require('../pages/personal.page.js'); - -describe('Change Password - Valid Usernames', function() { - var params = browser.params; - var loginPage; - var long_pass = 'newNEW123!"§$%&()=?öüß'; - var special_pass = 'special%&@/1234!-+='; - - beforeEach(function() { - isAngularSite(false); - loginPage = new LoginPage(params.baseUrl); - browser.manage().deleteAllCookies(); // logout the hard way - loginPage.get(); - }); - - it('should login as admin and create a test users ', function() { - loginPage.fillUserCredentilas(params.login.user, params.login.password); - loginPage.loginButton.click(); - userPage = new UserPage(params.baseUrl); - userPage.get(); - userPage.createNewUser('demo', 'password'); - userPage.get(); - expect(userPage.listUser()).toContain('demo'); - }); - - it('should login test user', function() { - // workaround: Test needed to close firstrunwizard - loginPage.login('demo', 'password'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login and change password in personal settings', function() { - loginPage.login('demo', 'password'); - var personalPage = new PersonalPage(params.baseUrl); - personalPage.get(); - personalPage.changePassword('password', 'newpassword') - - expect(personalPage.passwordChanged.isDisplayed()).toBeTruthy(); - expect(personalPage.passwordError.isDisplayed()).toBeFalsy(); - }); - - it('should login and change password to super save password in personal settings', function() { - loginPage.login('demo', 'newpassword'); - var personalPage = new PersonalPage(params.baseUrl); - personalPage.get(); - personalPage.changePassword('newpassword', long_pass); - browser.wait(function () { - return personalPage.passwordChanged.isDisplayed(); - }, 3000); - expect(personalPage.passwordChanged.isDisplayed()).toBeTruthy(); - expect(personalPage.passwordError.isDisplayed()).toBeFalsy(); - }); - - it('should login and not change password with wrong old password in personal settings', function() { - loginPage.login('demo', long_pass); - var personalPage = new PersonalPage(params.baseUrl); - personalPage.get(); - personalPage.changePassword('wrongpassword', 'newpassword'); - expect(personalPage.passwordChanged.isDisplayed()).toBeFalsy(); - expect(personalPage.passwordError.isDisplayed()).toBeTruthy(); - }); - - // %, &, @ and / - it('should change password including specialcharacters in personal settings', function() { - loginPage.login('demo', long_pass); - var personalPage = new PersonalPage(params.baseUrl); - personalPage.get(); - personalPage.changePassword(long_pass, special_pass); - expect(personalPage.passwordChanged.isDisplayed()).toBeTruthy(); - expect(personalPage.passwordError.isDisplayed()).toBeFalsy(); - }); - - it('should login with password including specialcharacters', function() { - loginPage.login('demo', special_pass); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login as admin and change password for test users ', function() { - loginPage.login(params.login.user, params.login.password); - userPage = new UserPage(params.baseUrl); - userPage.get(); - element(by.css('#userlist tr[data-displayname="demo"] td.password')).click().then(function() { - element(by.css('#userlist tr[data-displayname="demo"] td.password input')).sendKeys("password"); - element(by.css('#userlist tr[data-displayname="demo"] td.password input')).sendKeys(protractor.Key.ENTER); - }); - }); - - it('should login with password changed by admin', function() { - loginPage.login('demo', 'password'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login as admin and delete test user', function() { - // Cleanup prev tests - loginPage.login(params.login.user, params.login.password); - userPage.get(); - userPage.deleteUser('demo'); - userPage.get(); - expect(userPage.listUser()).not.toContain('demo'); - }); - -});
\ No newline at end of file diff --git a/tests/acceptance/tests/login/new_user_spec.js b/tests/acceptance/tests/login/new_user_spec.js deleted file mode 100644 index 06df5d69ea1..00000000000 --- a/tests/acceptance/tests/login/new_user_spec.js +++ /dev/null @@ -1,43 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var UserPage = require('../pages/user.page.js'); -var Screenshot = require('../helper/screenshot.js'); - -describe('New User', function() { - var params = browser.params; - var loginPage; - - beforeEach(function() { - isAngularSite(false); - loginPage = new LoginPage(params.baseUrl); - browser.manage().deleteAllCookies(); // logout the hard way - loginPage.get(); - }); - - it('should login as admin and create a new user ', function() { - loginPage.login(params.login.user, params.login.password); - userPage = new UserPage(params.baseUrl); - userPage.get(); - userPage.createNewUser('demo', 'demo'); - userPage.get(); - expect(userPage.listUser()).toContain('demo'); - }); - - it('should login with a new user', function() { - loginPage.login('demo', 'demo'); - - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - browser.takeScreenshot().then(function (png) { - new Screenshot(png, 'LoginAsNewUser.png'); - }); - }); - - it('should login as admin and delete new user', function() { - // Cleanup prev test - loginPage.login(params.login.user, params.login.password); - userPage.get(); - userPage.deleteUser('demo'); - userPage.get(); - expect(userPage.listUser()).not.toContain('demo'); - }); - -});
\ No newline at end of file diff --git a/tests/acceptance/tests/login/username_cases_spec.js b/tests/acceptance/tests/login/username_cases_spec.js deleted file mode 100644 index fe7e95b02b4..00000000000 --- a/tests/acceptance/tests/login/username_cases_spec.js +++ /dev/null @@ -1,88 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var UserPage = require('../pages/user.page.js'); - -describe('Username Cases', function() { - var params = browser.params; - var loginPage; - - beforeEach(function() { - isAngularSite(false); - loginPage = new LoginPage(params.baseUrl); - browser.manage().deleteAllCookies(); // logout the hard way - loginPage.get(); - }); - - it('should login as admin and create test users ', function() { - loginPage.fillUserCredentilas(params.login.user, params.login.password); - loginPage.loginButton.click(); - userPage = new UserPage(params.baseUrl); - userPage.get(); - userPage.createNewUser('demo1', 'demo'); - userPage.createNewUser('Demo2', 'demo'); - userPage.createNewUser('DEMO3', 'demo'); - - userPage.get(); - expect(userPage.listUser()).toContain('demo1'); - expect(userPage.listUser()).toContain('Demo2'); - expect(userPage.listUser()).toContain('DEMO3' ); - }); - - it('should login lowercase username with test user in lowercase', function() { - loginPage.login('demo1', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login camelcase username with test user in lowercase', function() { - loginPage.login('demo2', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login uppercase username with test user in lowercase', function() { - loginPage.login('demo3', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login with lowercase username in camelcase', function() { - loginPage.login('Demo1', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login with camelcase username in camelcase', function() { - loginPage.login('Demo2', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login with uppercase username in camelcase', function() { - loginPage.login('Demo3', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login with lowercase username in uppercase', function() { - loginPage.login('DEMO1', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login with lowercase username in uppercase', function() { - loginPage.login('DEMO2', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login with lowercase username in uppercase', function() { - loginPage.login('DEMO3', 'demo'); - expect(browser.getCurrentUrl()).toContain('index.php/apps/files/'); - }); - - it('should login as admin and delete test user', function() { - // Cleanup prev tests - loginPage.login(params.login.user, params.login.password); - userPage.get(); - userPage.deleteUser('demo1'); - userPage.deleteUser('Demo2'); - userPage.deleteUser('DEMO3'); - userPage.get(); - expect(userPage.listUser()).not.toContain('demo1'); - expect(userPage.listUser()).not.toContain('Demo2'); - expect(userPage.listUser()).not.toContain('DEMO3' ); - }); - -});
\ No newline at end of file diff --git a/tests/acceptance/tests/pages/apps.page.js b/tests/acceptance/tests/pages/apps.page.js deleted file mode 100644 index eb018979c90..00000000000 --- a/tests/acceptance/tests/pages/apps.page.js +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2014 - * - * This file is licensed under the Affero General Public License version 3 - * or later. - * - * See the COPYING-README file. - * - */ - -/* global module, protractor, element, by, browser, require */ -(function() { - var Page = require('../helper/page.js'); - - var AppsPage = function(baseUrl) { - this.baseUrl = baseUrl; - this.path = 'index.php/settings/apps'; - this.url = baseUrl + this.path; - - this.appList = element(by.css('#app-navigation .applist')); - }; - - //================ LOCATOR FUNCTIONS ====================================// - AppsPage.prototype.appId = function(appId) { - return by.css('#app-navigation .applist [data-id=\'' + appId + '\']'); - }; - - AppsPage.prototype.enableButtonId = function() { - return by.css('#app-content .appinfo .enable'); - }; - - AppsPage.prototype.groupsEnableCheckboxId = function() { - return by.id('groups_enable'); - }; - - AppsPage.prototype.groupsEnableListId = function() { - return by.css('#app-content .multiselect.button'); - }; - //================ SHARED ===============================================// - - AppsPage.prototype.get = function() { - browser.get(this.url); - - var appList = this.appList; - browser.wait(function() { - return appList.isDisplayed(); - }, 5000, 'load app page'); - }; - - /** - * Enables or disables the given app. - * - * @param {String} appId app id - * @param {bool} [state] true (default) to enable the app, false otherwise - * @param {Array} [groups] groups for which to enable the app or null to disable - * group selection. If not specified (undefined), the group checkbox, if it exists, - * will be left as is. - */ - AppsPage.prototype.enableApp = function(appId, state, groups) { - var d = protractor.promise.defer(); - if (state === undefined) { - state = true; - } - - var enableButton = element(this.enableButtonId()); - - element(this.appId(appId)).click(); - browser.wait(function() { - return enableButton.isPresent(); - }, 800); - - // an app is already enabled if the button value is "Disable" - enableButton.getAttribute('value').then(function(attr) { - if (state !== (attr === 'Disable')) { - enableButton.click(); - } - }); - - // wait for the button to change its attribute - browser.wait(function() { - return enableButton.getAttribute('value').then(function(attr) { - return attr === state ? 'Disable' : 'Enable'; - }); - }, 800); - - if (state && groups !== undefined) { - var groupsCheckbox = element(this.groupsEnableCheckboxId()); - var hasGroups = false; - - if (groups && groups.length > 0) { - hasGroups = true; - } - - // check/uncheck checkbox to match desired state - groupsCheckbox.isSelected().then(function(checkboxState) { - if (hasGroups !== checkboxState) { - groupsCheckbox.click(); - } - }); - - // wait for checkbox to change state - browser.wait(function() { - return groupsCheckbox.isSelected().then(function(checkboxState) { - return hasGroups === checkboxState; - }); - }, 800); - - if (hasGroups) { - var groupsList = element(this.groupsEnableListId()); - Page.multiSelectSetSelection(groupsList, groups).then(function() { - d.fulfill(true); - }); - } else { - d.fulfill(true); - } - } - return d.promise; - }; - - module.exports = AppsPage; -})(); diff --git a/tests/acceptance/tests/pages/files.page.js b/tests/acceptance/tests/pages/files.page.js deleted file mode 100644 index e5445309b26..00000000000 --- a/tests/acceptance/tests/pages/files.page.js +++ /dev/null @@ -1,317 +0,0 @@ -(function() { - var Page = require('../helper/page.js'); - var LoginPage = require('../pages/login.page.js'); - - var FilesPage = function(baseUrl) { - this.baseUrl = baseUrl; - this.path = 'index.php/apps/files'; - this.url = baseUrl + this.path; - - var url = this.url - this.folderUrl = function(folder) { - return url + '/?dir=%2F' + folder - } - - // topbar - this.UserActionDropdown = element(by.id("expandDisplayName")); - - // filelist - this.selectedFileListId = by.css('tr.searchresult td.filename .innernametext'); - this.firstListElem = element(by.css('#fileList tr:first-child')); - - // new Button and sublist - this.newButton = element(by.css('#new a')); - this.newTextButton = element(by.css('li.icon-filetype-text.svg')); - this.newFolderButton = element(by.css('li.icon-filetype-folder.svg')); - this.newTextnameForm = element(by.css('li.icon-filetype-text form input')); - this.newFoldernameForm = element(by.css('li.icon-filetype-folder form input')); - - this.alertWarning = element(by.css('.tipsy-inner')); - - this.trashbinButton = element(by.css('#app-navigation li.nav-trashbin a')); - - // sort arrows - this.nameSortArrow = element(by.css('a.name.sort')); - this.sizeSortArrow = element(by.css('a.size.sort')); - this.modifiedSortArrow = element(by.id('modified')); - - this.searchInput = element(by.id('searchbox')); - - this.shareWithForm = element(by.id('shareWith')); - this.sharedWithDropdown = element(by.id('ui-id-1')); - // this.textArea = element(by.css('.ace_content')); - // this.textLine = element(by.css('.ace_content .ace_line')); - // this.saveButton = element(by.id('editor_save')); - }; - -//================ LOCATOR FUNCTIONS ====================================// - FilesPage.prototype.fileListId = function() { - return by.css('td.filename .innernametext'); - } - - FilesPage.prototype.fileListElemId = function(fileName) { - return by.css("tr[data-file='" + fileName + "']"); - }; - - FilesPage.prototype.fileListElemNameId = function(fileName) { - return by.css("tr[data-file='" + fileName + "'] span.innernametext"); - }; - - FilesPage.prototype.restoreListElemId = function(id) { - return (by.css("#fileList tr[data-id='" + id + "']")); - }; - - FilesPage.prototype.restoreButtonId = function(id) { - return (by.css("#fileList tr[data-id='" + id + "'] .action.action-restore")); - }; - - FilesPage.prototype.renameButtonId = function(fileName) { - return by.css("tr[data-file='" + fileName + "'] .action.action-rename"); - }; - - FilesPage.prototype.renameFormId = function(fileName) { - return by.css("tr[data-file='" + fileName + "'] form input"); - }; - - FilesPage.prototype.shareButtonId = function(fileName) { - return by.css("tr[data-file='" + fileName + "'] .action.action-share"); - }; - - FilesPage.prototype.deleteButtonId = function(fileName) { - return by.css("tr[data-file='" + fileName + "'] .action.delete.icon-delete"); - }; - -//================ SHARED ===============================================// - - FilesPage.prototype.isLoggedIn = function() { - return this.UserActionDropdown.isPresent().then(function(isLoggedIn) { - return isLoggedIn; - }); - } - - FilesPage.prototype.get = function() { - browser.get(this.url); - - var button = this.newButton; - browser.wait(function() { - return button.isDisplayed(); - }, 5000, 'load files content'); - }; - - FilesPage.prototype.getAsUser = function(name, pass) { - var loginPage; - loginPage = new LoginPage(this.baseUrl); - - this.isLoggedIn().then(function(isLoggedIn) { - if(isLoggedIn) { - // console.log('isLoggedIn: ' + isLoggedIn); - return false - } else { - console.log('isLoggedIn: ' + isLoggedIn); - browser.manage().deleteAllCookies(); // logout the hard way - loginPage.get(); - loginPage.login(name, pass); - } - }); - }; - - FilesPage.prototype.getFolder = function(folder) { - folderUrl = this.folderUrl(folder); - browser.get(folderUrl); - var button = this.newButton; - browser.wait(function() { - return button.isDisplayed(); - }, 5000, 'load files content'); - } - FilesPage.prototype.getSubFolder = function(folder, subFolder) { - folderUrl = this.folderUrl(folder) + '%2F' + subFolder; - console.log(folderUrl); - browser.get(folderUrl); - var button = this.newButton; - browser.wait(function() { - return button.isDisplayed(); - }, 5000, 'load files content'); - } - - FilesPage.prototype.listFiles = function() { - // TODO: waiting to avoid "index out of bound error" - browser.sleep(800); - return element.all(this.fileListId()).map(function(filename) { - return filename.getText(); - }); - }; - - FilesPage.prototype.listSelctedFiles = function() { - return element.all(this.selectedFileListId).map(function(filename) { - return filename.getText(); - }); - }; - -//================ SHARED ACTIONS ========================================// - - // FilesPage.prototype.setCurrentListElem = function(name) { - // this.setCurrentListElem = element(by.css("tr[data-file='" + name + "']")); - // } - - FilesPage.prototype.openRenameForm = function(fileName) { - var page = new Page(); - var renameButton = element(this.renameButtonId(fileName)); - - return page.moveMouseTo(this.fileListElemId(fileName)).then(function() { - return renameButton.click(); - }) - }; - - FilesPage.prototype.renameFile = function(fileName, newFileName) { - var renameForm = element(this.renameFormId(fileName)); - return this.openRenameForm(fileName).then(function() { - for(var i=0; i<5; i++) { - renameForm.sendKeys(protractor.Key.DELETE) - }; - renameForm - .sendKeys(newFileName) - .sendKeys(protractor.Key.ENTER) - }); - }; - - FilesPage.prototype.deleteFile = function(fileName) { - var page = new Page(); - - page.moveMouseTo(this.fileListElemId(fileName)); - return element(this.deleteButtonId(fileName)).click(); - }; - - FilesPage.prototype.openShareForm = function(fileName) { - var page = new Page(); - - page.moveMouseTo(this.fileListElemId(fileName)); - return element(this.shareButtonId(fileName)).click(); - }; - - FilesPage.prototype.shareFile = function(fileName, userName) { - this.openShareForm(fileName); - this.shareWithForm.sendKeys(userName); - var dropdown = this.sharedWithDropdown - browser.wait(function(){ - return dropdown.isDisplayed(); - }, 3000); - this.shareWithForm.sendKeys(protractor.Key.ENTER); - } - - FilesPage.prototype.disableReshare = function(fileName, userName) { - var disableReshareButton = element(by.css("li[title='" + userName + "'] label input[name='share']")); - var dropdown = this.sharedWithDropdown - - // this.openShareForm(fileName); - - // TODO: find correct wait trigger - // browser.wait(function(){ - // return dropdown.isDisplayed(); - // }, 3000);s - - // TODO: Timing Workaround - browser.sleep(800); - disableReshareButton.click(); - }; - - FilesPage.prototype.checkReshareability = function(fileName) { - var page = new Page(); - var shareButtonLocator = this.shareButtonId(fileName); - - return page.moveMouseTo(this.fileListElemId(fileName)).then(function() { - return element(shareButtonLocator).isPresent(); - }); - }; - - // FilesPage.prototype.showFileVersions = function(name) { - // this.moveMouseTo("tr[data-file='"+name+"']"); - // var versionId = by.css("tr[data-file='"+name+"'] a.action.action-versions"); - // return element(versionId).click(); - // }; - - // FilesPage.prototype.downloadFile = function(name) { - // this.moveMouseTo("tr[data-file='"+name+"']"); - // var downloadId = by.css("tr[data-file='"+name+"'] a.action.action-download"); - // return element(downloadId).click(); - // }; - - FilesPage.prototype.restoreFile = function(id) { - var page = new Page(); - page.moveMouseTo(this.restoreListElemId(id)); - return element(this.restoreButtonId(id)).click(); - }; - -//================ TXT FILES ============================================// - - FilesPage.prototype.createNewTxtFile = function(name) { - this.newButton.click(); - this.newTextButton.click(); - this.newTextnameForm.sendKeys(name); - this.newTextnameForm.sendKeys(protractor.Key.ENTER); - - // TODO: find correct wait trigger - // browser.wait(function() { - // // return - // }); - - // TODO: Timing Workaround - browser.sleep(800); - }; - -//================ FOLDERS ==============================================// - - FilesPage.prototype.createNewFolder = function(name) { - this.newButton.click() - this.newFolderButton.click(); - this.newFoldernameForm.sendKeys(name); - this.newFoldernameForm.sendKeys(protractor.Key.ENTER); - - // TODO: find correct wait trigger - // browser.wait(function() { - // // return - // }); - - // TODO: Timing Workaround - browser.sleep(800); - }; - - FilesPage.prototype.goInToFolder = function(fileName) { - var page = new Page(); - - page.moveMouseTo(this.fileListElemId(fileName)); - element(this.fileListElemNameId(fileName)).click(); - var button = this.newButton; - browser.wait(function() { - return button.isDisplayed(); - }, 5000, 'load files content'); - }; - - FilesPage.prototype.createSubFolder = function(folderName, subFolderName) { - this.goInToFolder(folderName); - this.createNewFolder(subFolderName); - }; - -//================ NOT WORKING STUFF ====================================// - - // FilesPage.prototype.editFile = function(file) { - // var listElement = element(by.css("tr[data-file='testText.txt'] span.innernametext")); - // listElement.click(); - // var textArea = this.textArea; - // browser.pause(); - // browser.wait(function() { - // return(textArea.isDisplayed()); - // }, 3000, 'load textEditPage'); - // }; - - // FilesPage.prototype.writeInFile = function(text) { - // // this.textArea.click(); - // this.textLine.sendKeys(text); - // }; - - // FilesPage.prototype.saveFile = function() { - // this.saveButton.click(); - // }; - - - module.exports = FilesPage; -})();
\ No newline at end of file diff --git a/tests/acceptance/tests/pages/firstRunWizard.page.js b/tests/acceptance/tests/pages/firstRunWizard.page.js deleted file mode 100644 index c8f728e7f2a..00000000000 --- a/tests/acceptance/tests/pages/firstRunWizard.page.js +++ /dev/null @@ -1,36 +0,0 @@ -(function() { - var FirstRunWizardPage = function(baseUrl) { - this.firstRunWizardId = by.id('firstrunwizard'); - this.firstRunWizard = element(this.firstRunWizardId); - this.closeLink = element(by.id('cboxOverlay')); - }; - - FirstRunWizardPage.prototype.waitForDisplay = function() { - browser.wait(function() { - console.log(by.id('closeWizard')); - return by.id('closeWizard'); - // return by.id('firstrunwizard'); - }, 8000); - }; - - FirstRunWizardPage.prototype.isFirstRunWizardPage = function() { - this.waitForDisplay(); - return !!this.firstRunWizardId; - }; - - FirstRunWizardPage.prototype.waitForClose = function() { - browser.wait(function () { - return element(by.id('cboxOverlay')).isDisplayed().then(function(displayed) { - return !displayed; // Do a little Promise/Boolean dance here, since wait will resolve promises. - }); - }, 3000, 'firstrunwizard should dissappear'); - } - - FirstRunWizardPage.prototype.close = function() { - browser.executeScript('$("#closeWizard").click();'); - browser.executeScript('$("#cboxOverlay").click();'); - this.waitForClose(); - }; - - module.exports = FirstRunWizardPage; -})();
\ No newline at end of file diff --git a/tests/acceptance/tests/pages/install.page.js b/tests/acceptance/tests/pages/install.page.js deleted file mode 100644 index 67c66577d67..00000000000 --- a/tests/acceptance/tests/pages/install.page.js +++ /dev/null @@ -1,52 +0,0 @@ -(function() { - var InstallPage = function(baseUrl) { - this.baseUrl = baseUrl; - - this.installField = element(by.name('install')); - this.warningField = element(by.css('.warning')); - - this.adminAccount = element(by.id('adminaccount')); - this.adminInput = this.adminAccount.element(by.id('adminlogin')); - this.passwordInput = this.adminAccount.element(by.id('adminpass')); - this.installButton = element(by.css('form .buttons input[type="submit"]')); - - this.advancedConfigLink = element(by.id('showAdvanced')); - this.dataDirectoryConfig = element(by.id('datadirContent')); - this.dbConfig = element(by.id('databaseBackend')); - }; - - InstallPage.prototype.get = function() { - browser.get(this.baseUrl); - }; - - InstallPage.prototype.isInstallPage = function() { - return !!this.installField; - }; - - InstallPage.prototype.fillAdminAccount = function(user, pass) { - this.adminInput.sendKeys(user); - this.passwordInput.sendKeys(pass); - }; - - InstallPage.prototype.isAdvancedConfigOpen = function() { - return this.databaseBackend.isDisplayed() && this.dbConfig.isDisplayed(); - }; - - InstallPage.prototype.openAdvancedConfig = function() { - if (! this.isAdvancedConfigOpen()) { - this.advancedConfigLink.click(); - } - }; - - InstallPage.prototype.closeAdvancedConfig = function() { - if (this.isAdvancedConfigOpen()) { - this.advancedConfigLink.click(); - } - }; - - InstallPage.prototype.configDatabase = function(dbConfig) { - - }; - - module.exports = InstallPage; -})();
\ No newline at end of file diff --git a/tests/acceptance/tests/pages/login.page.js b/tests/acceptance/tests/pages/login.page.js deleted file mode 100644 index b7019fa54a6..00000000000 --- a/tests/acceptance/tests/pages/login.page.js +++ /dev/null @@ -1,46 +0,0 @@ -(function() { - var LoginPage = function(baseUrl) { - this.baseUrl = baseUrl; - this.url = baseUrl; - - this.loginForm = element(by.name('login')); - this.userInput = this.loginForm.element(by.id('user')); - this.passwordInput = this.loginForm.element(by.id('password')); - this.loginButton = element(by.id('submit')); - - // On Page when logged in - this.menuButton = element(by.id('expand')); - this.logoutButton = element(by.id('logout')); - this.newButton = element(by.id('expandDisplayName')); - }; - - LoginPage.prototype.get = function() { - browser.get(this.url); - }; - - LoginPage.prototype.isCurrentPage = function() { - - return this.loginForm.isPresent(); - }; - - LoginPage.prototype.fillUserCredentilas = function(user, pass) { - this.userInput.sendKeys(user); - this.passwordInput.sendKeys(pass); - }; - - LoginPage.prototype.login = function(user, pass) { - this.fillUserCredentilas(user, pass); - this.loginButton.click(); - var button = this.newButton; - browser.wait(function() { - return button.isPresent(); - }, 5000, 'load files content'); - }; - - LoginPage.prototype.logout = function() { - this.menuButton.click(); - this.logoutButton.click(); - }; - - module.exports = LoginPage; -})();
\ No newline at end of file diff --git a/tests/acceptance/tests/pages/personal.page.js b/tests/acceptance/tests/pages/personal.page.js deleted file mode 100644 index aa552335a38..00000000000 --- a/tests/acceptance/tests/pages/personal.page.js +++ /dev/null @@ -1,57 +0,0 @@ -(function() { - var PersonalPage = function(baseUrl) { - this.baseUrl = baseUrl; - this.path = 'index.php/settings/personal'; - this.url = baseUrl + this.path; - - this.passwordForm = element(by.css('form#passwordform')); - this.oldPasswordInput = element(by.id('pass1')); - this.newPasswordInput = element(by.id('pass2')); - this.newPasswordButton = element(by.id('passwordbutton')); - - this.passwordChanged = element(by.id('passwordchanged')); - this.passwordError = element(by.id('passworderror')); - - this.displaynameForm = element(by.id('displaynameform')); - this.displaynameInput = this.displaynameForm.element(by.id('displayName')); - - }; - - PersonalPage.prototype.get = function() { - browser.get(this.url); - }; - - PersonalPage.prototype.isUserPage = function() { - return browser.driver.getCurrentUrl() == this.url; - }; - - PersonalPage.prototype.ensurePersonalPage = function() { - // console.log(this.isUserPage()); - // if (! this.isUserPage()) { - // display.log('Warning: Auto loading UserPage'); - // this.get(); - // } - }; - - PersonalPage.prototype.changePassword = function(oldPass, newPass) { - this.ensurePersonalPage(); - this.oldPasswordInput.sendKeys(oldPass); - this.newPasswordInput.sendKeys(newPass); - this.newPasswordButton.click(); - - // result need some time to display - var changed = this.passwordChanged; - var error = this.passwordError; - var ready = false; - browser.wait(function () { - changed.isDisplayed().then(function(c) { - error.isDisplayed().then(function(e) { - ready = c || e; - }); - }); - return ready; - }, 8000, 'personal password change result not displayed'); - }; - - module.exports = PersonalPage; -})();
\ No newline at end of file diff --git a/tests/acceptance/tests/pages/shareApi.page.js b/tests/acceptance/tests/pages/shareApi.page.js deleted file mode 100644 index a1a3be8f889..00000000000 --- a/tests/acceptance/tests/pages/shareApi.page.js +++ /dev/null @@ -1,84 +0,0 @@ -(function() { - var request = require('request'); - var parseString = require('xml2js').parseString; - process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" // Avoids DEPTH_ZERO_SELF_SIGNED_CERT error for self-signed certs - - var ShareApi = function(baseUrl) { - this.baseUrl = baseUrl; - this.path = 'ocs/v1.php/apps/files_sharing/api/v1/shares'; - this.url = baseUrl + this.path; - - this.request = { - method: "GET" - }; - }; - ShareApi.prototype.get = function () { - var url = this.url; - - var defer = protractor.promise.defer(); - console.log("Calling", this.url); - - request({ - method: "GET", - uri: url, - followRedirect: true, - auth: { - user: "admin", - password: "password", - } - }, - function(error, response) { - console.log("Done call to", url, "status:", response.statusCode); - if (error || response.statusCode >= 400) { - defer.reject({ - error : error, - response : response - }); - } else { - defer.fulfill(response); - } - }); - return defer.promise; - }; - - ShareApi.prototype.create = function (path, shareWith, shareType) { - var url = this.url; - - var defer = protractor.promise.defer(); - console.log("Calling", this.url); - - request({ - method: "POST", - uri: url, - followRedirect: true, - form: { - path: path, - shareWith: shareWith, - shareType: shareType - }, - auth: { - user: "admin", - password: "password", - } - }, - function(error, response) { - console.log("Done call to", url, "status:", response.statusCode); - if (error || response.statusCode >= 400) { - defer.reject({ - error : error, - response : response - }); - } else { - defer.fulfill(response); - } - }); - return defer.promise; - - }; - - module.exports = ShareApi; - -})(); - - - diff --git a/tests/acceptance/tests/pages/user.page.js b/tests/acceptance/tests/pages/user.page.js deleted file mode 100644 index 9a973bd42c1..00000000000 --- a/tests/acceptance/tests/pages/user.page.js +++ /dev/null @@ -1,114 +0,0 @@ -(function() { - var UserPage = function(baseUrl) { - this.baseUrl = baseUrl; - this.path = 'index.php/settings/users'; - this.url = baseUrl + this.path; - - this.newUserNameInput = element(by.id('newusername')); - this.newUserPasswordInput = element(by.id('newuserpassword')); - this.createNewUserButton = element(by.css('#newuser input[type="submit"]')); - - this.newGroupButton = element(by.css('#newgroup-init a')); - this.newGroupNameInput = element(by.css('#newgroup-form input#newgroupname')); - - }; - - UserPage.prototype.get = function() { - browser.get(this.url); - }; - - UserPage.prototype.isUserPage = function() { - return browser.driver.getCurrentUrl() == this.url; - }; - - UserPage.prototype.ensureUserPage = function() { - // console.log(this.isUserPage()); - // if (! this.isUserPage()) { - // display.log('Warning: Auto loading UserPage'); - // this.get(); - // } - }; - - UserPage.prototype.fillNewUserInput = function(user, pass) { - this.ensureUserPage(); - this.newUserNameInput.sendKeys(user); - this.newUserPasswordInput.sendKeys(pass); - }; - - UserPage.prototype.createNewUser = function(user, pass) { - this.ensureUserPage(); - this.fillNewUserInput(user, pass); - this.createNewUserButton.click(); - }; - - UserPage.prototype.deleteUser = function(user) { - this.ensureUserPage(); - - var removeId = by.css('#userlist tr[data-displayname="' + user + '"] td.remove a'); - var filter = browser.findElement(removeId); - var scrollIntoView = function () { - arguments[0].scrollIntoView(); - } - browser.executeScript(scrollIntoView, filter).then(function () { - browser.actions().mouseMove(browser.findElement(removeId)).perform(); - element(removeId).click(); - }); - }; - - UserPage.prototype.setCurrentListElem = function(name) { - return element(by.css("tr[data-uid='" + name + "']")); - } - - UserPage.prototype.renameDisplayName = function(name, newName) { - var renameDisplayNameButton = element(by.css("tr[data-uid='" + name + "'] td.displayName")); - renameDisplayNameButton.click(); - var renameDisplayNameForm = element(by.css("tr[data-uid='" + name + "'] td.displayName input")); - renameDisplayNameForm.sendKeys(newName); - renameDisplayNameForm.sendKeys(protractor.Key.ENTER); - }; - - UserPage.prototype.listUser = function() { - this.ensureUserPage(); - return element.all(by.css('td.displayName')).map(function(user) { - return user.getText(); - }); - }; - - UserPage.prototype.createNewGroup = function(name) { - this.newGroupButton.click(); - var newGroupNameInput = this.newGroupNameInput; - browser.wait(function() { - return newGroupNameInput.isDisplayed(); - }, 3000); - this.newGroupNameInput.sendKeys(name); - this.newGroupNameInput.sendKeys(protractor.Key.ENTER); - }; - -///// NOT WORKING, CLICK ON CHECKBOX RESEIVES AN OTHER ELEMENT ////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - // UserPage.prototype.setUserGroup = function(userName, groupName) { - // var renameDisplayNameButton = element(by.css("tr[data-uid='" + userName + "'] td.groups .multiselect.button")); - // renameDisplayNameButton.click(); - - // var a = 'tr[data-uid="' + userName + '"] ul.multiselectoptions.down'; - - // var dropdown = element(by.css(a)); - // browser.wait(function() { - // return dropdown.isDisplayed(); - // }, 3000); - // browser.pause(); - // var checkboxId = by.css('tr[data-uid="' + userName + '"] ul.multiselectoptions.down label'); - // element.all(checkboxId).each(function(checkbox) { - // checkbox.getText().then(function(text) { - // console.log(checkboxId); - // console.log(text); - // if(text == groupName) { - // return checkbox.click(); - // } - // }) - // }); - // }; - - module.exports = UserPage; -})();
\ No newline at end of file diff --git a/tests/acceptance/tests/share/share_api_spec.js b/tests/acceptance/tests/share/share_api_spec.js deleted file mode 100644 index ed41fa94021..00000000000 --- a/tests/acceptance/tests/share/share_api_spec.js +++ /dev/null @@ -1,50 +0,0 @@ -var ShareApi = require('../pages/shareApi.page.js'); -var LoginPage = require('../pages/login.page.js'); -var UserPage = require('../pages/user.page.js'); -var FilesPage = require('../pages/files.page.js'); -var parseXml = require('xml2js').parseString; - -var flow = protractor.promise.controlFlow(); - -describe('Share Api', function() { - var params = browser.params; - var shareApi; - var loginPage; - var userPage - var filesPage; - var firstRunWizardPage; - - - beforeEach(function() { - isAngularSite(false); - shareApi = new ShareApi(params.baseUrl); - }); - - it('should get all shares', function() { - var get = function () { - return shareApi.get(); - }; - - flow.execute(get).then(function(res){ - parseXml(res.body, function (err, result) { - console.dir(result.ocs.data); - }); - expect(res.statusCode).toEqual(200); - }); - }); - - it('should create a new share', function() { - var create = function () { - return shareApi.create('asdf.txt', 'demo2', 0); - }; - - flow.execute(create).then(function(res){ - parseXml(res.body, function (err, result) { - console.log(result.ocs.data, result.ocs.meta); - expect(result.ocs.meta[0].statuscode[0]).toEqual('100'); - }); - }); - }); - - -}); diff --git a/tests/acceptance/tests/share/share_spec.js b/tests/acceptance/tests/share/share_spec.js deleted file mode 100644 index 0dc12ad506d..00000000000 --- a/tests/acceptance/tests/share/share_spec.js +++ /dev/null @@ -1,198 +0,0 @@ -var LoginPage = require('../pages/login.page.js'); -var UserPage = require('../pages/user.page.js'); -var FilesPage = require('../pages/files.page.js'); - - -describe('Share', function() { - var params = browser.params; - var loginPage; - var userPage - var filesPage; - - beforeEach(function() { - isAngularSite(false); - loginPage = new LoginPage(params.baseUrl); - userPage = new UserPage(params.baseUrl); - filesPage = new FilesPage(params.baseUrl); - }); - - it('should login as admin and create 4 new users', function() { - filesPage.getAsUser(params.login.user, params.login.password); - // userPage.get(); - // userPage.createNewGroup('test_specGroup_1'); - userPage.get(); - // userPage.createNewGroup('test_specGroup_2'); - userPage.createNewUser('demo', 'password'); - userPage.createNewUser('demo2', 'password'); - userPage.createNewUser('demo3', 'password'); - userPage.createNewUser('demo4', 'password'); - userPage.get(); - userPage.renameDisplayName('demo2', ' display2'); - userPage.renameDisplayName('demo3', ' display3'); - userPage.renameDisplayName('demo4', ' display4'); - // setting Group to User fails cause click receives an other element - // userPage.setUserGroup('demo2', 'test_specGroup_1'); - // userPage.setUserGroup('demo3', 'test_specGroup_1'); - // userPage.setUserGroup('demo4', 'test_specGroup_2'); - expect(userPage.listUser()).toContain('demo', 'demo2', 'demo3', 'demo4'); - }); - - - it('should share a folder with another user by username', function() { - filesPage.getAsUser(params.login.user, params.login.password); - filesPage.createNewFolder('toShare_1'); - browser.sleep(500); - filesPage.shareFile('toShare_1', 'demo'); - - loginPage.logout(); - loginPage.login('demo', 'password'); - expect(filesPage.listFiles()).toContain('toShare_1'); - }); - - it('should share a folder including special characters', function() { - filesPage.getAsUser(params.login.user, params.login.password); - filesPage.createNewFolder('sP€c!@L'); - browser.sleep(500); - filesPage.shareFile('sP€c!@L', 'demo'); - - loginPage.logout(); - loginPage.login('demo', 'password'); - expect(filesPage.listFiles()).toContain('sP€c!@L'); - }); - - it('should share a folder with 3 another user by display name', function() { - filesPage.getAsUser(params.login.user, params.login.password); - filesPage.createNewFolder('toShare_2'); - browser.sleep(500); - filesPage.shareFile('toShare_2', 'display2'); - - filesPage.shareWithForm.sendKeys(protractor.Key.DELETE); - filesPage.shareWithForm.sendKeys('display3'); - browser.wait(function(){ - return filesPage.sharedWithDropdown.isDisplayed(); - }, 3000); - filesPage.shareWithForm.sendKeys(protractor.Key.ENTER); - - filesPage.shareWithForm.sendKeys(protractor.Key.DELETE); - filesPage.shareWithForm.sendKeys('display4'); - browser.wait(function(){ - return filesPage.sharedWithDropdown.isDisplayed(); - }, 3000); - filesPage.shareWithForm.sendKeys(protractor.Key.ENTER); - - loginPage.logout(); - loginPage.login('demo2', 'password'); - expect(filesPage.listFiles()).toContain('toShare_2'); - - loginPage.logout(); - loginPage.login('demo3', 'password'); - expect(filesPage.listFiles()).toContain('toShare_2'); - - loginPage.logout(); - loginPage.login('demo4', 'password'); - expect(filesPage.listFiles()).toContain('toShare_2'); - }); - - it('should grant second users CRUDS rights to their folder', function() { - filesPage.getAsUser('demo2', 'password'); - filesPage.getFolder('toShare_2'); - - //create file - filesPage.createNewTxtFile('inSharedBySecond'); - filesPage.createNewTxtFile('toBeDeleted'); - expect(filesPage.listFiles()).toContain('inSharedBySecond' ,'toBeDeleted'); - - //delete file - filesPage.deleteFile('toBeDeleted.txt'); - browser.sleep(800); - expect(filesPage.listFiles()).not.toContain('toBeDeleted'); - - - //share file - filesPage.shareFile('inSharedBySecond.txt', 'demo'); - - loginPage.logout(); - loginPage.login('demo', 'password'); - filesPage.renameFile('inSharedBySecond.txt', 'renamedBySecond.txt') - expect(filesPage.listFiles()).toContain('renamedBySecond'); - filesPage.deleteFile('renamedBySecond.txt'); - }); - - it('should delete the root folder shared with a user account by another user', function() { - filesPage.getAsUser('demo2', 'password'); - filesPage.deleteFile('toShare_2'); - browser.sleep(800); - expect(filesPage.listFiles()).not.toContain('toShare_2'); - - loginPage.logout(); - loginPage.login(params.login.user, params.login.password); - expect(filesPage.listFiles()).toContain('toShare_2'); - }); - - it('should delete a file shared with a user, only form user if user deletes it', function() { - filesPage.getAsUser(params.login.user, params.login.password); - filesPage.createNewTxtFile('toDeleteByUser'); - filesPage.shareFile('toDeleteByUser.txt', 'demo'); - - loginPage.logout(); - loginPage.login('demo', 'password'); - filesPage.deleteFile('toDeleteByUser.txt'); - browser.sleep(800); - expect(filesPage.listFiles()).not.toContain('inSharedBySecond'); - - loginPage.logout(); - loginPage.login(params.login.user, params.login.password); - expect(filesPage.listFiles()).toContain('toDeleteByUser'); - filesPage.deleteFile('toDeleteByUser.txt'); - }); - - it('should delete a file in a shared folder, from all', function() { - filesPage.getAsUser(params.login.user, params.login.password); - filesPage.getFolder('toShare_1'); - filesPage.createNewTxtFile('toDeleteFromAll'); - - loginPage.logout(); - loginPage.login('demo', 'password'); - filesPage.getFolder('toShare_1'); - filesPage.deleteFile('toDeleteFromAll.txt'); - browser.sleep(800); - expect(filesPage.listFiles()).not.toContain('toDeleteFormAll'); - - loginPage.logout(); - loginPage.login(params.login.user, params.login.password); - filesPage.getFolder('toShare_1'); - expect(filesPage.listFiles()).not.toContain('toDeleteFromAll'); - }); - - it('should delete a file shared with a user, form all if owner deletes it', function() { - filesPage.getAsUser(params.login.user, params.login.password); - filesPage.createNewTxtFile('toDeleteByOwner'); - filesPage.shareFile('toDeleteByOwner.txt', 'demo'); - - loginPage.logout(); - loginPage.login('demo', 'password'); - expect(filesPage.listFiles()).toContain('toDeleteByOwner'); - - loginPage.logout(); - loginPage.login(params.login.user, params.login.password); - filesPage.deleteFile('toDeleteByOwner.txt'); - - loginPage.logout(); - loginPage.login('demo', 'password'); - expect(filesPage.listFiles()).not.toContain('toDeleteByOwner'); - - }); - - it('should not be possible to reshare a folder, if the "re-share" option is removed', function() { - filesPage.getAsUser(params.login.user, params.login.password); - filesPage.createNewFolder('noReshare'); - filesPage.shareFile('noReshare', 'demo'); - filesPage.disableReshare('noReshare', 'demo'); - - loginPage.logout(); - loginPage.login('demo', 'password'); - - expect(filesPage.checkReshareability('noReshare')).toBeFalsy(); - }); - -});
\ No newline at end of file diff --git a/tests/core/command/encryption/changekeystorageroottest.php b/tests/core/command/encryption/changekeystorageroottest.php index 6cb52cdea99..2a1f48983f1 100644 --- a/tests/core/command/encryption/changekeystorageroottest.php +++ b/tests/core/command/encryption/changekeystorageroottest.php @@ -74,9 +74,9 @@ class ChangeKeyStorageRootTest extends TestCase { $this->outputInterface = $this->getMock('Symfony\Component\Console\Output\OutputInterface'); $this->userInterface = $this->getMock('\OCP\UserInterface'); - $outputFormaterInterface = $this->getMock('Symfony\Component\Console\Formatter\OutputFormatterInterface'); + $outputFormatterInterface = $this->getMock('Symfony\Component\Console\Formatter\OutputFormatterInterface'); $this->outputInterface->expects($this->any())->method('getFormatter') - ->willReturn($outputFormaterInterface); + ->willReturn($outputFormatterInterface); $this->changeKeyStorageRoot = new ChangeKeyStorageRoot( $this->view, diff --git a/tests/core/command/maintenance/datafingerprinttest.php b/tests/core/command/maintenance/datafingerprinttest.php new file mode 100644 index 00000000000..4d661b5c027 --- /dev/null +++ b/tests/core/command/maintenance/datafingerprinttest.php @@ -0,0 +1,64 @@ +<?php +/** + * @author Roeland Jago Douma <rullzer@owncloud.com> + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace Tests\Core\Command\Maintenance; + +use OC\Core\Command\Maintenance\DataFingerprint; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\IConfig; +use Test\TestCase; + +class DataFingerprintTest extends TestCase { + /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ + protected $config; + /** @var \PHPUnit_Framework_MockObject_MockObject */ + protected $consoleInput; + /** @var \PHPUnit_Framework_MockObject_MockObject */ + protected $consoleOutput; + /** @var ITimeFactory|\PHPUnit_Framework_MockObject_MockObject */ + protected $timeFactory; + + /** @var \Symfony\Component\Console\Command\Command */ + protected $command; + + protected function setUp() { + parent::setUp(); + + $this->config = $this->getMock('OCP\IConfig'); + $this->timeFactory = $this->getMock('OCP\AppFramework\Utility\ITimeFactory'); + $this->consoleInput = $this->getMock('Symfony\Component\Console\Input\InputInterface'); + $this->consoleOutput = $this->getMock('Symfony\Component\Console\Output\OutputInterface'); + + /** @var \OCP\IConfig $config */ + $this->command = new DataFingerprint($this->config, $this->timeFactory); + } + + public function testSetFingerPrint() { + $this->timeFactory->expects($this->once()) + ->method('getTime') + ->willReturn(42); + $this->config->expects($this->once()) + ->method('setSystemValue') + ->with('data-fingerprint', md5(42)); + + self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]); + } +} diff --git a/tests/core/controller/LoginControllerTest.php b/tests/core/controller/LoginControllerTest.php new file mode 100644 index 00000000000..f9a6080892b --- /dev/null +++ b/tests/core/controller/LoginControllerTest.php @@ -0,0 +1,267 @@ +<?php +/** + * @author Lukas Reschke <lukas@owncloud.com> + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace OC\Core\Controller; + +use OCP\AppFramework\Http\RedirectResponse; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use OCP\IRequest; +use OCP\ISession; +use OCP\IURLGenerator; +use OCP\IUserManager; +use OCP\IUserSession; +use Test\TestCase; + +class LoginControllerTest extends TestCase { + /** @var LoginController */ + private $loginController; + /** @var IRequest */ + private $request; + /** @var IUserManager */ + private $userManager; + /** @var IConfig */ + private $config; + /** @var ISession */ + private $session; + /** @var IUserSession */ + private $userSession; + /** @var IURLGenerator */ + private $urlGenerator; + + public function setUp() { + parent::setUp(); + $this->request = $this->getMock('\\OCP\\IRequest'); + $this->userManager = $this->getMock('\\OCP\\IUserManager'); + $this->config = $this->getMock('\\OCP\\IConfig'); + $this->session = $this->getMock('\\OCP\\ISession'); + $this->userSession = $this->getMock('\\OCP\\IUserSession'); + $this->urlGenerator = $this->getMock('\\OCP\\IURLGenerator'); + + $this->loginController = new LoginController( + 'core', + $this->request, + $this->userManager, + $this->config, + $this->session, + $this->userSession, + $this->urlGenerator + ); + } + + public function testLogoutWithoutToken() { + $this->request + ->expects($this->once()) + ->method('getCookie') + ->with('oc_token') + ->willReturn(null); + $this->config + ->expects($this->never()) + ->method('deleteUserValue'); + $this->urlGenerator + ->expects($this->once()) + ->method('linkToRouteAbsolute') + ->with('core.login.showLoginForm') + ->willReturn('/login'); + + $expected = new RedirectResponse('/login'); + $this->assertEquals($expected, $this->loginController->logout()); + } + + public function testLogoutWithToken() { + $this->request + ->expects($this->once()) + ->method('getCookie') + ->with('oc_token') + ->willReturn('MyLoginToken'); + $user = $this->getMock('\\OCP\\IUser'); + $user + ->expects($this->once()) + ->method('getUID') + ->willReturn('JohnDoe'); + $this->userSession + ->expects($this->once()) + ->method('getUser') + ->willReturn($user); + $this->config + ->expects($this->once()) + ->method('deleteUserValue') + ->with('JohnDoe', 'login_token', 'MyLoginToken'); + $this->urlGenerator + ->expects($this->once()) + ->method('linkToRouteAbsolute') + ->with('core.login.showLoginForm') + ->willReturn('/login'); + + $expected = new RedirectResponse('/login'); + $this->assertEquals($expected, $this->loginController->logout()); + } + + public function testShowLoginFormForLoggedInUsers() { + $this->userSession + ->expects($this->once()) + ->method('isLoggedIn') + ->willReturn(true); + + $expectedResponse = new RedirectResponse(\OC_Util::getDefaultPageUrl()); + $this->assertEquals($expectedResponse, $this->loginController->showLoginForm('', '', '')); + } + + public function testShowLoginFormWithErrorsInSession() { + $this->userSession + ->expects($this->once()) + ->method('isLoggedIn') + ->willReturn(false); + $this->session + ->expects($this->once()) + ->method('get') + ->with('loginMessages') + ->willReturn( + [ + [ + 'ErrorArray1', + 'ErrorArray2', + ], + [ + 'MessageArray1', + 'MessageArray2', + ], + ] + ); + + $expectedResponse = new TemplateResponse( + 'core', + 'login', + [ + 'ErrorArray1' => true, + 'ErrorArray2' => true, + 'messages' => [ + 'MessageArray1', + 'MessageArray2', + ], + 'loginName' => '', + 'user_autofocus' => true, + 'canResetPassword' => true, + 'alt_login' => [], + 'rememberLoginAllowed' => \OC_Util::rememberLoginAllowed(), + 'rememberLoginState' => 0, + ], + 'guest' + ); + $this->assertEquals($expectedResponse, $this->loginController->showLoginForm('', '', '')); + } + + /** + * @return array + */ + public function passwordResetDataProvider() { + return [ + [ + true, + true, + ], + [ + false, + false, + ], + ]; + } + + /** + * @dataProvider passwordResetDataProvider + */ + public function testShowLoginFormWithPasswordResetOption($canChangePassword, + $expectedResult) { + $this->userSession + ->expects($this->once()) + ->method('isLoggedIn') + ->willReturn(false); + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('lost_password_link') + ->willReturn(false); + $user = $this->getMock('\\OCP\\IUser'); + $user + ->expects($this->once()) + ->method('canChangePassword') + ->willReturn($canChangePassword); + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('LdapUser') + ->willReturn($user); + + $expectedResponse = new TemplateResponse( + 'core', + 'login', + [ + 'messages' => [], + 'loginName' => 'LdapUser', + 'user_autofocus' => false, + 'canResetPassword' => $expectedResult, + 'alt_login' => [], + 'rememberLoginAllowed' => \OC_Util::rememberLoginAllowed(), + 'rememberLoginState' => 0, + ], + 'guest' + ); + $this->assertEquals($expectedResponse, $this->loginController->showLoginForm('LdapUser', '', '')); + } + + public function testShowLoginFormForUserNamedNull() { + $this->userSession + ->expects($this->once()) + ->method('isLoggedIn') + ->willReturn(false); + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('lost_password_link') + ->willReturn(false); + $user = $this->getMock('\\OCP\\IUser'); + $user + ->expects($this->once()) + ->method('canChangePassword') + ->willReturn(false); + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('0') + ->willReturn($user); + + $expectedResponse = new TemplateResponse( + 'core', + 'login', + [ + 'messages' => [], + 'loginName' => '0', + 'user_autofocus' => false, + 'canResetPassword' => false, + 'alt_login' => [], + 'rememberLoginAllowed' => \OC_Util::rememberLoginAllowed(), + 'rememberLoginState' => 0, + ], + 'guest' + ); + $this->assertEquals($expectedResponse, $this->loginController->showLoginForm('0', '', '')); + } +} diff --git a/tests/core/controller/avatarcontrollertest.php b/tests/core/controller/avatarcontrollertest.php index 8e5e58904a7..c99b69228b1 100644 --- a/tests/core/controller/avatarcontrollertest.php +++ b/tests/core/controller/avatarcontrollertest.php @@ -93,7 +93,7 @@ class AvatarControllerTest extends \Test\TestCase { $this->container['UserSession']->method('getUser')->willReturn($this->userMock); $this->avatarFile = $this->getMock('OCP\Files\File'); - $this->avatarFile->method('getContnet')->willReturn('image data'); + $this->avatarFile->method('getContent')->willReturn('image data'); $this->avatarFile->method('getMimeType')->willReturn('image type'); $this->avatarFile->method('getEtag')->willReturn('my etag'); } diff --git a/tests/core/templates/templates.php b/tests/core/templates/templates.php new file mode 100644 index 00000000000..338d80b276c --- /dev/null +++ b/tests/core/templates/templates.php @@ -0,0 +1,20 @@ +<?php + +namespace Tests\Core\Templates; + +class Templates extends \Test\TestCase { + + public function test403() { + $template = \OC::$SERVERROOT . '/core/templates/403.php'; + $expectedHtml = "<ul><li class='error'>\n\t\tAccess forbidden<br><p class='hint'></p></li></ul>"; + $this->assertTemplate($expectedHtml, $template); + } + + public function test404() { + $template = \OC::$SERVERROOT . '/core/templates/404.php'; + $href = \OC::$server->getURLGenerator()->linkTo('', 'index.php'); + $expectedHtml = "<ul><li class='error'>\n\t\t\tFile not found<br><p class='hint'>The specified document has not been found on the server.</p>\n<p class='hint'><a href='$href'>You can click here to return to ownCloud.</a></p>\n\t\t</li></ul>"; + $this->assertTemplate($expectedHtml, $template); + } + +} diff --git a/tests/data/openssl.cnf b/tests/data/openssl.cnf index 1eb86c40126..1aada1fa73f 100644 --- a/tests/data/openssl.cnf +++ b/tests/data/openssl.cnf @@ -55,7 +55,7 @@ crl = $dir/crl.pem # The current CRL private_key = $dir/private/cakey.pem# The private key RANDFILE = $dir/private/.rand # private random number file -x509_extensions = usr_cert # The extentions to add to the cert +x509_extensions = usr_cert # The extensions to add to the cert # Comment out the following two lines for the "traditional" # (and highly broken) format. @@ -107,7 +107,7 @@ default_bits = 2048 default_keyfile = privkey.pem distinguished_name = req_distinguished_name attributes = req_attributes -x509_extensions = v3_ca # The extentions to add to the self signed cert +x509_extensions = v3_ca # The extensions to add to the self signed cert # Passwords for private keys if not present they will be prompted for # input_password = secret diff --git a/tests/acceptance/tests/pages/webdav_api.page.js b/tests/data/themes/abc/apps/files/l10n/zz.json index e69de29bb2d..e69de29bb2d 100644 --- a/tests/acceptance/tests/pages/webdav_api.page.js +++ b/tests/data/themes/abc/apps/files/l10n/zz.json diff --git a/tests/lib/appframework/db/mappertest.php b/tests/lib/appframework/db/mappertest.php index c8b999ad62c..108e4eee28e 100644 --- a/tests/lib/appframework/db/mappertest.php +++ b/tests/lib/appframework/db/mappertest.php @@ -22,10 +22,11 @@ */ -namespace OCP\AppFramework\Db; +namespace Test\AppFramework\Db; use \OCP\IDBConnection; -use Test\AppFramework\Db\MapperTestUtility; +use \OCP\AppFramework\Db\Entity; +use \OCP\AppFramework\Db\Mapper; /** * @method integer getId() @@ -236,7 +237,7 @@ class MapperTest extends MapperTestUtility { $entity->resetUpdatedFields(); $this->db->expects($this->never()) - ->method('prepareQuery'); + ->method('prepare'); $this->mapper->update($entity); } diff --git a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php index 9e71a3d0961..dd4ec3af96f 100644 --- a/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php +++ b/tests/lib/appframework/middleware/security/SecurityMiddlewareTest.php @@ -343,9 +343,14 @@ class SecurityMiddlewareTest extends \Test\TestCase { $this->middleware = $this->getMiddleware(false, false); $this->urlGenerator ->expects($this->once()) - ->method('getAbsoluteURL') - ->with('index.php') - ->will($this->returnValue('http://localhost/index.php')); + ->method('linkToRoute') + ->with( + 'core.login.showLoginForm', + [ + 'redirect_url' => 'owncloud%2Findex.php%2Fapps%2Fspecialapp', + ] + ) + ->will($this->returnValue('http://localhost/index.php/login?redirect_url=owncloud%2Findex.php%2Fapps%2Fspecialapp')); $this->logger ->expects($this->once()) ->method('debug') @@ -356,7 +361,7 @@ class SecurityMiddlewareTest extends \Test\TestCase { new NotLoggedInException() ); - $expected = new RedirectResponse('http://localhost/index.php?redirect_url=owncloud%2Findex.php%2Fapps%2Fspecialapp'); + $expected = new RedirectResponse('http://localhost/index.php/login?redirect_url=owncloud%2Findex.php%2Fapps%2Fspecialapp'); $this->assertEquals($expected , $response); } diff --git a/tests/lib/autoloader.php b/tests/lib/autoloader.php index 6443d87a2e5..f93b7c33cab 100644 --- a/tests/lib/autoloader.php +++ b/tests/lib/autoloader.php @@ -77,15 +77,11 @@ class AutoLoader extends TestCase { } public function testLoadCoreNamespaceCore() { - $this->assertEquals([ - \OC::$SERVERROOT . '/core/foo/bar.php', - ], $this->loader->findClass('OC\Core\Foo\Bar')); + $this->assertEquals([], $this->loader->findClass('OC\Core\Foo\Bar')); } public function testLoadCoreNamespaceSettings() { - $this->assertEquals([ - \OC::$SERVERROOT . '/settings/foo/bar.php', - ], $this->loader->findClass('OC\Settings\Foo\Bar')); + $this->assertEquals([], $this->loader->findClass('OC\Settings\Foo\Bar')); } public function testLoadCoreNamespaceRepair() { diff --git a/tests/lib/avatartest.php b/tests/lib/avatartest.php index e7d78311085..b0ab4cb8b5c 100644 --- a/tests/lib/avatartest.php +++ b/tests/lib/avatartest.php @@ -27,7 +27,7 @@ class AvatarTest extends \Test\TestCase { $l = $this->getMock('\OCP\IL10N'); $l->method('t')->will($this->returnArgument(0)); $this->user = $this->getMockBuilder('\OC\User\User')->disableOriginalConstructor()->getMock(); - $this->avatar = new \OC\Avatar($this->folder, $l, $this->user); + $this->avatar = new \OC\Avatar($this->folder, $l, $this->user, $this->getMock('\OCP\ILogger')); } public function testGetNoAvatar() { @@ -148,8 +148,7 @@ class AvatarTest extends \Test\TestCase { ->willReturn('avatarX'); $nonAvatarFile->expects($this->never())->method('delete'); - $this->folder->method('search') - ->with('avatar') + $this->folder->method('getDirectoryListing') ->willReturn([$avatarFileJPG, $avatarFilePNG, $resizedAvatarFile, $nonAvatarFile]); $newFile = $this->getMock('\OCP\Files\File'); diff --git a/tests/lib/cache.php b/tests/lib/cache.php index feddcac4693..a91f37467d2 100644 --- a/tests/lib/cache.php +++ b/tests/lib/cache.php @@ -28,7 +28,7 @@ abstract class Test_Cache extends \Test\TestCase { $this->instance->set('value1', $value); $this->assertTrue($this->instance->hasKey('value1')); $received=$this->instance->get('value1'); - $this->assertEquals($value, $received, 'Value recieved from cache not equal to the original'); + $this->assertEquals($value, $received, 'Value received from cache not equal to the original'); $value='ipsum lorum'; $this->instance->set('value1', $value); $received=$this->instance->get('value1'); diff --git a/tests/lib/datetimeformatter.php b/tests/lib/datetimeformatter.php index 9a50ee4a257..bf1ef3b84dc 100644 --- a/tests/lib/datetimeformatter.php +++ b/tests/lib/datetimeformatter.php @@ -42,7 +42,7 @@ class DateTimeFormatter extends TestCase { } public function formatTimeSpanData() { - $time = 1416916800; // Use a fixed timestamp so we dont switch days/years with the getTimestampAgo + $time = 1416916800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo $deL10N = new \OC_L10N('lib', 'de'); return array( array('seconds ago', $time, $time), @@ -80,7 +80,7 @@ class DateTimeFormatter extends TestCase { } public function formatDateSpanData() { - $time = 1416916800; // Use a fixed timestamp so we dont switch days/years with the getTimestampAgo + $time = 1416916800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo $deL10N = new \OC_L10N('lib', 'de'); return array( // Normal testing diff --git a/tests/lib/db/connection.php b/tests/lib/db/connection.php index 62d0a77ca1f..4022bee511e 100644 --- a/tests/lib/db/connection.php +++ b/tests/lib/db/connection.php @@ -72,7 +72,7 @@ class Connection extends \Test\TestCase { // sqlite removes the tables after closing the DB $this->assertTrue(true); } else { - $this->assertFalse($this->connection->tableExists($table), 'Table ' . $table . ' doesnt exists.'); + $this->assertFalse($this->connection->tableExists($table), 'Table ' . $table . " doesn't exist."); } } diff --git a/tests/lib/encryption/encryptionwrappertest.php b/tests/lib/encryption/encryptionwrappertest.php new file mode 100644 index 00000000000..909187ae43b --- /dev/null +++ b/tests/lib/encryption/encryptionwrappertest.php @@ -0,0 +1,101 @@ +<?php +/** + * @author Björn Schießle <schiessle@owncloud.com> + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + + +namespace Test\Encryption; + + +use OC\Encryption\EncryptionWrapper; +use Test\TestCase; + +class EncryptionWrapperTest extends TestCase { + + /** @var EncryptionWrapper */ + private $instance; + + /** @var \PHPUnit_Framework_MockObject_MockObject | \OCP\ILogger */ + private $logger; + + /** @var \PHPUnit_Framework_MockObject_MockObject | \OC\Encryption\Manager */ + private $manager; + + /** @var \PHPUnit_Framework_MockObject_MockObject | \OC\Memcache\ArrayCache */ + private $arrayCache; + + public function setUp() { + parent::setUp(); + + $this->arrayCache = $this->getMock('OC\Memcache\ArrayCache'); + $this->manager = $this->getMockBuilder('OC\Encryption\Manager') + ->disableOriginalConstructor()->getMock(); + $this->logger = $this->getMock('OCP\ILogger'); + + $this->instance = new EncryptionWrapper($this->arrayCache, $this->manager, $this->logger); + } + + + /** + * @dataProvider provideWrapStorage + */ + public function testWrapStorage($expectedWrapped, $wrappedStorages) { + $storage = $this->getMockBuilder('OC\Files\Storage\Storage') + ->disableOriginalConstructor() + ->getMock(); + + foreach ($wrappedStorages as $wrapper) { + $storage->expects($this->any()) + ->method('instanceOfStorage') + ->willReturnMap([ + [$wrapper, true], + ]); + } + + $mount = $this->getMockBuilder('OCP\Files\Mount\IMountPoint') + ->disableOriginalConstructor() + ->getMock(); + + $returnedStorage = $this->instance->wrapStorage('mountPoint', $storage, $mount); + + $this->assertEquals( + $expectedWrapped, + $returnedStorage->instanceOfStorage('OC\Files\Storage\Wrapper\Encryption'), + 'Asserted that the storage is (not) wrapped with encryption' + ); + } + + public function provideWrapStorage() { + return [ + // Wrap when not wrapped or not wrapped with storage + [true, []], + [true, ['OCA\Files_Trashbin\Storage']], + + // Do not wrap shared storages + [false, ['OC\Files\Storage\Shared']], + [false, ['OCA\Files_Sharing\External\Storage']], + [false, ['OC\Files\Storage\OwnCloud']], + [false, ['OC\Files\Storage\Shared', 'OCA\Files_Sharing\External\Storage']], + [false, ['OC\Files\Storage\Shared', 'OC\Files\Storage\OwnCloud']], + [false, ['OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], + [false, ['OC\Files\Storage\Shared', 'OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], + ]; + } + +} diff --git a/tests/lib/encryption/managertest.php b/tests/lib/encryption/managertest.php index 6355c706b61..3dcfc949a18 100644 --- a/tests/lib/encryption/managertest.php +++ b/tests/lib/encryption/managertest.php @@ -24,6 +24,9 @@ class ManagerTest extends TestCase { /** @var \PHPUnit_Framework_MockObject_MockObject */ private $util; + + /** @var \PHPUnit_Framework_MockObject_MockObject | \OC\Memcache\ArrayCache */ + private $arrayCache; public function setUp() { parent::setUp(); @@ -32,7 +35,8 @@ class ManagerTest extends TestCase { $this->l10n = $this->getMock('\OCP\Il10n'); $this->view = $this->getMock('\OC\Files\View'); $this->util = $this->getMockBuilder('\OC\Encryption\Util')->disableOriginalConstructor()->getMock(); - $this->manager = new Manager($this->config, $this->logger, $this->l10n, $this->view, $this->util); + $this->arrayCache = $this->getMock('OC\Memcache\ArrayCache'); + $this->manager = new Manager($this->config, $this->logger, $this->l10n, $this->view, $this->util, $this->arrayCache); } public function testManagerIsDisabled() { diff --git a/tests/lib/encryption/utiltest.php b/tests/lib/encryption/utiltest.php index 449326bb351..ec316a9f05a 100644 --- a/tests/lib/encryption/utiltest.php +++ b/tests/lib/encryption/utiltest.php @@ -188,49 +188,4 @@ class UtilTest extends TestCase { ); } - /** - * @dataProvider provideWrapStorage - */ - public function testWrapStorage($expectedWrapped, $wrappedStorages) { - $storage = $this->getMockBuilder('OC\Files\Storage\Storage') - ->disableOriginalConstructor() - ->getMock(); - - foreach ($wrappedStorages as $wrapper) { - $storage->expects($this->any()) - ->method('instanceOfStorage') - ->willReturnMap([ - [$wrapper, true], - ]); - } - - $mount = $this->getMockBuilder('OCP\Files\Mount\IMountPoint') - ->disableOriginalConstructor() - ->getMock(); - - $returnedStorage = $this->util->wrapStorage('mountPoint', $storage, $mount); - - $this->assertEquals( - $expectedWrapped, - $returnedStorage->instanceOfStorage('OC\Files\Storage\Wrapper\Encryption'), - 'Asserted that the storage is (not) wrapped with encryption' - ); - } - - public function provideWrapStorage() { - return [ - // Wrap when not wrapped or not wrapped with storage - [true, []], - [true, ['OCA\Files_Trashbin\Storage']], - - // Do not wrap shared storages - [false, ['OC\Files\Storage\Shared']], - [false, ['OCA\Files_Sharing\External\Storage']], - [false, ['OC\Files\Storage\OwnCloud']], - [false, ['OC\Files\Storage\Shared', 'OCA\Files_Sharing\External\Storage']], - [false, ['OC\Files\Storage\Shared', 'OC\Files\Storage\OwnCloud']], - [false, ['OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], - [false, ['OC\Files\Storage\Shared', 'OCA\Files_Sharing\External\Storage', 'OC\Files\Storage\OwnCloud']], - ]; - } } diff --git a/tests/lib/files/node/folder.php b/tests/lib/files/node/folder.php index 09bf32561e6..f6d488d6590 100644 --- a/tests/lib/files/node/folder.php +++ b/tests/lib/files/node/folder.php @@ -376,6 +376,14 @@ class Folder extends \Test\TestCase { ->method('getCache') ->will($this->returnValue($cache)); + $mount = $this->getMock('\OCP\Files\Mount\IMountPoint'); + $mount->expects($this->once()) + ->method('getStorage') + ->will($this->returnValue($storage)); + $mount->expects($this->once()) + ->method('getInternalPath') + ->will($this->returnValue('foo')); + $cache->expects($this->once()) ->method('search') ->with('%qw%') @@ -388,9 +396,10 @@ class Folder extends \Test\TestCase { ->with('/bar/foo') ->will($this->returnValue(array())); - $view->expects($this->once()) - ->method('resolvePath') - ->will($this->returnValue(array($storage, 'foo'))); + $root->expects($this->once()) + ->method('getMount') + ->with('/bar/foo') + ->will($this->returnValue($mount)); $node = new \OC\Files\Node\Folder($root, $view, '/bar/foo'); $result = $node->search('qw'); @@ -404,13 +413,21 @@ class Folder extends \Test\TestCase { * @var \OC\Files\View | \PHPUnit_Framework_MockObject_MockObject $view */ $view = $this->getMock('\OC\Files\View'); - $root = $this->getMock('\OC\Files\Node\Root', array('getUser', 'getMountsIn'), array($manager, $view, $this->user)); + $root = $this->getMock('\OC\Files\Node\Root', array('getUser', 'getMountsIn', 'getMount'), array($manager, $view, $this->user)); $root->expects($this->any()) ->method('getUser') ->will($this->returnValue($this->user)); $storage = $this->getMock('\OC\Files\Storage\Storage'); $cache = $this->getMock('\OC\Files\Cache\Cache', array(), array('')); + $mount = $this->getMock('\OCP\Files\Mount\IMountPoint'); + $mount->expects($this->once()) + ->method('getStorage') + ->will($this->returnValue($storage)); + $mount->expects($this->once()) + ->method('getInternalPath') + ->will($this->returnValue('files')); + $storage->expects($this->once()) ->method('getCache') ->will($this->returnValue($cache)); @@ -428,9 +445,10 @@ class Folder extends \Test\TestCase { ->with('') ->will($this->returnValue(array())); - $view->expects($this->once()) - ->method('resolvePath') - ->will($this->returnValue(array($storage, 'files'))); + $root->expects($this->once()) + ->method('getMount') + ->with('') + ->will($this->returnValue($mount)); $result = $root->search('qw'); $this->assertEquals(1, count($result)); @@ -450,6 +468,14 @@ class Folder extends \Test\TestCase { $storage = $this->getMock('\OC\Files\Storage\Storage'); $cache = $this->getMock('\OC\Files\Cache\Cache', array(), array('')); + $mount = $this->getMock('\OCP\Files\Mount\IMountPoint'); + $mount->expects($this->once()) + ->method('getStorage') + ->will($this->returnValue($storage)); + $mount->expects($this->once()) + ->method('getInternalPath') + ->will($this->returnValue('')); + $storage->expects($this->once()) ->method('getCache') ->will($this->returnValue($cache)); @@ -466,9 +492,10 @@ class Folder extends \Test\TestCase { ->with('/bar') ->will($this->returnValue(array())); - $view->expects($this->once()) - ->method('resolvePath') - ->will($this->returnValue(array($storage, ''))); + $root->expects($this->once()) + ->method('getMount') + ->with('/bar') + ->will($this->returnValue($mount)); $node = new \OC\Files\Node\Folder($root, $view, '/bar'); $result = $node->search('qw'); @@ -489,6 +516,14 @@ class Folder extends \Test\TestCase { $storage = $this->getMock('\OC\Files\Storage\Storage'); $cache = $this->getMock('\OC\Files\Cache\Cache', array(), array('')); + $mount = $this->getMock('\OCP\Files\Mount\IMountPoint'); + $mount->expects($this->once()) + ->method('getStorage') + ->will($this->returnValue($storage)); + $mount->expects($this->once()) + ->method('getInternalPath') + ->will($this->returnValue('foo')); + $storage->expects($this->once()) ->method('getCache') ->will($this->returnValue($cache)); @@ -505,9 +540,10 @@ class Folder extends \Test\TestCase { ->with('/bar/foo') ->will($this->returnValue(array())); - $view->expects($this->once()) - ->method('resolvePath') - ->will($this->returnValue(array($storage, 'foo'))); + $root->expects($this->once()) + ->method('getMount') + ->with('/bar/foo') + ->will($this->returnValue($mount)); $node = new \OC\Files\Node\Folder($root, $view, '/bar/foo'); $result = $node->searchByTag('tag1', 'user1'); @@ -531,6 +567,14 @@ class Folder extends \Test\TestCase { $subStorage = $this->getMock('\OC\Files\Storage\Storage'); $subMount = $this->getMock('\OC\Files\Mount\MountPoint', array(), array(null, '')); + $mount = $this->getMock('\OCP\Files\Mount\IMountPoint'); + $mount->expects($this->once()) + ->method('getStorage') + ->will($this->returnValue($storage)); + $mount->expects($this->once()) + ->method('getInternalPath') + ->will($this->returnValue('foo')); + $subMount->expects($this->once()) ->method('getStorage') ->will($this->returnValue($subStorage)); @@ -566,9 +610,10 @@ class Folder extends \Test\TestCase { ->with('/bar/foo') ->will($this->returnValue(array($subMount))); - $view->expects($this->once()) - ->method('resolvePath') - ->will($this->returnValue(array($storage, 'foo'))); + $root->expects($this->once()) + ->method('getMount') + ->with('/bar/foo') + ->will($this->returnValue($mount)); $node = new \OC\Files\Node\Folder($root, $view, '/bar/foo'); @@ -601,8 +646,8 @@ class Folder extends \Test\TestCase { $cache = $this->getMock('\OC\Files\Cache\Cache', array(), array('')); $view->expects($this->once()) - ->method('file_exists') - ->will($this->returnValue(true)); + ->method('getFileInfo') + ->will($this->returnValue(new FileInfo('/bar/foo/qwerty', null, 'qwerty', ['mimetype' => 'text/plain'], null))); $storage->expects($this->once()) ->method('getCache') @@ -683,8 +728,8 @@ class Folder extends \Test\TestCase { $cache = $this->getMock('\OC\Files\Cache\Cache', array(), array('')); $view->expects($this->any()) - ->method('file_exists') - ->will($this->returnValue(true)); + ->method('getFileInfo') + ->will($this->returnValue(new FileInfo('/bar/foo/qwerty', null, 'qwerty', ['mimetype' => 'plain'], null))); $storage->expects($this->any()) ->method('getCache') diff --git a/tests/lib/files/node/root.php b/tests/lib/files/node/root.php index 4b1aea1da4e..9c77959869d 100644 --- a/tests/lib/files/node/root.php +++ b/tests/lib/files/node/root.php @@ -12,6 +12,9 @@ use OC\Files\FileInfo; use OCP\Files\NotPermittedException; use OC\Files\Mount\Manager; +/** + * @group DB + */ class Root extends \Test\TestCase { private $user; @@ -41,16 +44,6 @@ class Root extends \Test\TestCase { ->with('/bar/foo') ->will($this->returnValue($this->getFileInfo(array('fileid' => 10, 'path' => 'bar/foo', 'name', 'mimetype' => 'text/plain')))); - $view->expects($this->once()) - ->method('is_dir') - ->with('/bar/foo') - ->will($this->returnValue(false)); - - $view->expects($this->once()) - ->method('file_exists') - ->with('/bar/foo') - ->will($this->returnValue(true)); - $root->mount($storage, ''); $node = $root->get('/bar/foo'); $this->assertEquals(10, $node->getId()); @@ -73,7 +66,7 @@ class Root extends \Test\TestCase { $root = new \OC\Files\Node\Root($manager, $view, $this->user); $view->expects($this->once()) - ->method('file_exists') + ->method('getFileInfo') ->with('/bar/foo') ->will($this->returnValue(false)); diff --git a/tests/lib/files/storage/storage.php b/tests/lib/files/storage/storage.php index f3d265df2de..ed2ea87f9d9 100644 --- a/tests/lib/files/storage/storage.php +++ b/tests/lib/files/storage/storage.php @@ -87,13 +87,13 @@ abstract class Storage extends \Test\TestCase { } $this->assertEquals(array($directory), $content); - $this->assertFalse($this->instance->mkdir('/' . $directory)); //cant create existing folders + $this->assertFalse($this->instance->mkdir('/' . $directory)); //can't create existing folders $this->assertTrue($this->instance->rmdir('/' . $directory)); $this->wait(); $this->assertFalse($this->instance->file_exists('/' . $directory)); - $this->assertFalse($this->instance->rmdir('/' . $directory)); //cant remove non existing folders + $this->assertFalse($this->instance->rmdir('/' . $directory)); //can't remove non existing folders $dh = $this->instance->opendir('/'); $content = array(); diff --git a/tests/lib/files/storage/wrapper/encryption.php b/tests/lib/files/storage/wrapper/encryption.php index bde920e440e..21f7d9f09b9 100644 --- a/tests/lib/files/storage/wrapper/encryption.php +++ b/tests/lib/files/storage/wrapper/encryption.php @@ -5,6 +5,7 @@ namespace Test\Files\Storage\Wrapper; use OC\Encryption\Util; use OC\Files\Storage\Temporary; use OC\Files\View; +use OC\User\Manager; use Test\Files\Storage\Storage; class Encryption extends Storage { @@ -87,6 +88,9 @@ class Encryption extends Storage { */ private $config; + /** @var \OC\Memcache\ArrayCache | \PHPUnit_Framework_MockObject_MockObject */ + private $arrayCache; + /** @var integer dummy unencrypted size */ private $dummySize = -1; @@ -104,6 +108,7 @@ class Encryption extends Storage { ->method('getEncryptionModule') ->willReturn($mockModule); + $this->arrayCache = $this->getMock('OC\Memcache\ArrayCache'); $this->config = $this->getMockBuilder('\OCP\IConfig') ->disableOriginalConstructor() ->getMock(); @@ -111,9 +116,10 @@ class Encryption extends Storage { ->disableOriginalConstructor() ->getMock(); - $this->util = $this->getMock('\OC\Encryption\Util', + $this->util = $this->getMock( + '\OC\Encryption\Util', ['getUidAndFilename', 'isFile', 'isExcluded'], - [new View(), new \OC\User\Manager(), $this->groupManager, $this->config]); + [new View(), new Manager(), $this->groupManager, $this->config, $this->arrayCache]); $this->util->expects($this->any()) ->method('getUidAndFilename') ->willReturnCallback(function ($path) { @@ -168,7 +174,7 @@ class Encryption extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager + $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache ] ) ->setMethods(['getMetaData', 'getCache', 'getEncryptionModule']) @@ -195,7 +201,7 @@ class Encryption extends Storage { protected function buildMockModule() { $this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') ->disableOriginalConstructor() - ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll']) + ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser']) ->getMock(); $this->encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE'); @@ -245,7 +251,7 @@ class Encryption extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager + $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache ] ) ->setMethods(['getCache', 'verifyUnencryptedSize']) @@ -255,25 +261,39 @@ class Encryption extends Storage { $this->invokePrivate($this->instance, 'unencryptedSize', [[$path => $storedUnencryptedSize]]); } - + $fileEntry = $this->getMockBuilder('\OC\Files\Cache\Cache') + ->disableOriginalConstructor()->getMock(); $sourceStorage->expects($this->once())->method('getMetaData')->with($path) ->willReturn($metaData); + $sourceStorage->expects($this->any()) + ->method('getCache') + ->with($path) + ->willReturn($fileEntry); + $fileEntry->expects($this->any()) + ->method('get') + ->with($metaData['fileid']); $this->instance->expects($this->any())->method('getCache')->willReturn($cache); $this->instance->expects($this->any())->method('verifyUnencryptedSize') ->with($path, 0)->willReturn($expected['size']); $result = $this->instance->getMetaData($path); - $this->assertSame($expected['encrypted'], $result['encrypted']); + if(isset($expected['encrypted'])) { + $this->assertSame($expected['encrypted'], (bool)$result['encrypted']); + + if(isset($expected['encryptedVersion'])) { + $this->assertSame($expected['encryptedVersion'], $result['encryptedVersion']); + } + } $this->assertSame($expected['size'], $result['size']); } public function dataTestGetMetaData() { return [ - ['/test.txt', ['size' => 42, 'encrypted' => false], true, true, 12, ['size' => 12, 'encrypted' => true]], + ['/test.txt', ['size' => 42, 'encrypted' => 2, 'encryptedVersion' => 2, 'fileid' => 1], true, true, 12, ['size' => 12, 'encrypted' => true, 'encryptedVersion' => 2]], ['/test.txt', null, true, true, 12, null], - ['/test.txt', ['size' => 42, 'encrypted' => false], false, false, 12, ['size' => 42, 'encrypted' => false]], - ['/test.txt', ['size' => 42, 'encrypted' => false], true, false, 12, ['size' => 12, 'encrypted' => true]] + ['/test.txt', ['size' => 42, 'encrypted' => 0, 'fileid' => 1], false, false, 12, ['size' => 42, 'encrypted' => false]], + ['/test.txt', ['size' => 42, 'encrypted' => false, 'fileid' => 1], true, false, 12, ['size' => 12, 'encrypted' => true]] ]; } @@ -293,7 +313,7 @@ class Encryption extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager + $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache ] ) ->setMethods(['getCache', 'verifyUnencryptedSize']) @@ -331,7 +351,7 @@ class Encryption extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager + $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache ] ) ->setMethods(['fixUnencryptedSize']) @@ -521,8 +541,15 @@ class Encryption extends Storage { ->disableOriginalConstructor()->getMock(); $util = $this->getMockBuilder('\OC\Encryption\Util') - ->setConstructorArgs([new View(), new \OC\User\Manager(), $this->groupManager, $this->config]) - ->getMock(); + ->setConstructorArgs( + [ + new View(), + new Manager(), + $this->groupManager, + $this->config, + $this->arrayCache + ] + )->getMock(); $instance = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption') ->setConstructorArgs( @@ -533,7 +560,7 @@ class Encryption extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager + $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache ] ) ->setMethods(['readFirstBlock', 'parseRawHeader']) @@ -582,7 +609,7 @@ class Encryption extends Storage { ->disableOriginalConstructor()->getMock(); $util = $this->getMockBuilder('\OC\Encryption\Util') - ->setConstructorArgs([new View(), new \OC\User\Manager(), $this->groupManager, $this->config]) + ->setConstructorArgs([new View(), new Manager(), $this->groupManager, $this->config, $this->arrayCache]) ->getMock(); $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') @@ -600,7 +627,7 @@ class Encryption extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager + $this->encryptionManager, $util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache ] ) ->setMethods(['readFirstBlock', 'parseRawHeader', 'getCache']) @@ -636,7 +663,7 @@ class Encryption extends Storage { 'mountPoint' => '/', 'mount' => $this->mount ], - $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager + $this->encryptionManager, $this->util, $this->logger, $this->file, null, $this->keyStore, $this->update, $this->mountManager, $this->arrayCache ); @@ -763,6 +790,8 @@ class Encryption extends Storage { $expectedCachePut['encryptedVersion'] = 12345; } + $this->arrayCache->expects($this->never())->method('set'); + $this->cache->expects($this->once()) ->method('put') ->with($sourceInternalPath, $expectedCachePut); @@ -812,7 +841,8 @@ class Encryption extends Storage { null, $this->keyStore, $this->update, - $this->mountManager + $this->mountManager, + $this->arrayCache ] ) ->setMethods(['updateUnencryptedSize', 'getCache']) @@ -825,6 +855,9 @@ class Encryption extends Storage { $instance->expects($this->any())->method('getCache') ->willReturn($cache); + $this->arrayCache->expects($this->once())->method('set') + ->with('encryption_copy_version_' . $sourceInternalPath, true); + if ($copyResult) { $cache->expects($this->once())->method('get') ->with($sourceInternalPath) diff --git a/tests/lib/files/stream/encryption.php b/tests/lib/files/stream/encryption.php index f67dd09bc4d..20a4100d2ff 100644 --- a/tests/lib/files/stream/encryption.php +++ b/tests/lib/files/stream/encryption.php @@ -31,6 +31,7 @@ class Encryption extends \Test\TestCase { $config = $this->getMockBuilder('\OCP\IConfig') ->disableOriginalConstructor() ->getMock(); + $arrayCache = $this->getMock('OC\Memcache\ArrayCache'); $groupManager = $this->getMockBuilder('\OC\Group\Manager') ->disableOriginalConstructor() ->getMock(); @@ -39,7 +40,11 @@ class Encryption extends \Test\TestCase { ->setMethods(['getAccessList']) ->getMock(); $file->expects($this->any())->method('getAccessList')->willReturn([]); - $util = $this->getMock('\OC\Encryption\Util', ['getUidAndFilename'], [new View(), new \OC\User\Manager(), $groupManager, $config]); + $util = $this->getMock( + '\OC\Encryption\Util', + ['getUidAndFilename'], + [new View(), new \OC\User\Manager(), $groupManager, $config, $arrayCache] + ); $util->expects($this->any()) ->method('getUidAndFilename') ->willReturn(['user1', $internalPath]); @@ -306,7 +311,7 @@ class Encryption extends \Test\TestCase { protected function buildMockModule() { $encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') ->disableOriginalConstructor() - ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll']) + ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser']) ->getMock(); $encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE'); diff --git a/tests/lib/files/view.php b/tests/lib/files/view.php index 3e88a5306f8..86413c61aa1 100644 --- a/tests/lib/files/view.php +++ b/tests/lib/files/view.php @@ -2424,4 +2424,24 @@ class View extends \Test\TestCase { $this->assertEquals($expected, $files); } + + public function testFilePutContentsClearsChecksum() { + $storage = new Temporary(array()); + $scanner = $storage->getScanner(); + $storage->file_put_contents('foo.txt', 'bar'); + \OC\Files\Filesystem::mount($storage, array(), '/test/'); + $scanner->scan(''); + + $view = new \OC\Files\View('/test/foo.txt'); + $view->putFileInfo('.', ['checksum' => '42']); + + $this->assertEquals('bar', $view->file_get_contents('')); + $fh = tmpfile(); + fwrite($fh, 'fooo'); + rewind($fh); + $view->file_put_contents('', $fh); + $this->assertEquals('fooo', $view->file_get_contents('')); + $data = $view->getFileInfo('.'); + $this->assertEquals('', $data->getChecksum()); + } } diff --git a/tests/lib/group.php b/tests/lib/group.php index 4bb888ed725..d3ac6d8d69e 100644 --- a/tests/lib/group.php +++ b/tests/lib/group.php @@ -32,7 +32,7 @@ class Test_Group extends \Test\TestCase { public function testSingleBackend() { $userBackend = new \Test\Util\User\Dummy(); \OC::$server->getUserManager()->registerBackend($userBackend); - OC_Group::useBackend(new OC_Group_Dummy()); + OC_Group::useBackend(new \Test\Util\Group\Dummy()); $group1 = $this->getUniqueID(); $group2 = $this->getUniqueID(); @@ -72,7 +72,7 @@ class Test_Group extends \Test\TestCase { public function testNoEmptyGIDs() { - OC_Group::useBackend(new OC_Group_Dummy()); + OC_Group::useBackend(new \Test\Util\Group\Dummy()); $emptyGroup = null; $this->assertFalse(OC_Group::createGroup($emptyGroup)); @@ -80,7 +80,7 @@ class Test_Group extends \Test\TestCase { public function testNoGroupsTwice() { - OC_Group::useBackend(new OC_Group_Dummy()); + OC_Group::useBackend(new \Test\Util\Group\Dummy()); $group = $this->getUniqueID(); OC_Group::createGroup($group); @@ -92,7 +92,7 @@ class Test_Group extends \Test\TestCase { public function testDontDeleteAdminGroup() { - OC_Group::useBackend(new OC_Group_Dummy()); + OC_Group::useBackend(new \Test\Util\Group\Dummy()); $adminGroup = 'admin'; OC_Group::createGroup($adminGroup); @@ -102,7 +102,7 @@ class Test_Group extends \Test\TestCase { public function testDontAddUserToNonexistentGroup() { - OC_Group::useBackend(new OC_Group_Dummy()); + OC_Group::useBackend(new \Test\Util\Group\Dummy()); $groupNonExistent = 'notExistent'; $user = $this->getUniqueID(); @@ -111,7 +111,7 @@ class Test_Group extends \Test\TestCase { } public function testUsersInGroup() { - OC_Group::useBackend(new OC_Group_Dummy()); + OC_Group::useBackend(new \Test\Util\Group\Dummy()); $userBackend = new \Test\Util\User\Dummy(); \OC::$server->getUserManager()->registerBackend($userBackend); @@ -143,8 +143,8 @@ class Test_Group extends \Test\TestCase { public function testMultiBackend() { $userBackend = new \Test\Util\User\Dummy(); \OC::$server->getUserManager()->registerBackend($userBackend); - $backend1 = new OC_Group_Dummy(); - $backend2 = new OC_Group_Dummy(); + $backend1 = new \Test\Util\Group\Dummy(); + $backend2 = new \Test\Util\Group\Dummy(); OC_Group::useBackend($backend1); OC_Group::useBackend($backend2); diff --git a/tests/lib/group/dummy.php b/tests/lib/group/dummy.php index 6836f89d3fe..eaa299c39af 100644 --- a/tests/lib/group/dummy.php +++ b/tests/lib/group/dummy.php @@ -28,6 +28,6 @@ class Test_Group_Dummy extends Test_Group_Backend { protected function setUp() { parent::setUp(); - $this->backend=new OC_Group_Dummy(); + $this->backend=new \Test\Util\Group\Dummy(); } } diff --git a/tests/lib/group/manager.php b/tests/lib/group/manager.php index 6cf473b9156..410e11114c4 100644 --- a/tests/lib/group/manager.php +++ b/tests/lib/group/manager.php @@ -65,7 +65,7 @@ class Manager extends \Test\TestCase { } public function testGetDeleted() { - $backend = new \OC_Group_Dummy(); + $backend = new \Test\Util\Group\Dummy(); $backend->createGroup('group1'); /** diff --git a/tests/lib/hookhelper.php b/tests/lib/hookhelper.php index 93411bd068b..f1cce831477 100644 --- a/tests/lib/hookhelper.php +++ b/tests/lib/hookhelper.php @@ -104,7 +104,7 @@ class HookHelper { } /** - * Callback that sets the run paramter to false + * Callback that sets the run parameter to false */ public static function cancellingCallback($params) { $params[Filesystem::signal_param_run] = false; diff --git a/tests/lib/l10n/factorytest.php b/tests/lib/l10n/factorytest.php index 9f5954d0ee1..e4c0eab2e6a 100644 --- a/tests/lib/l10n/factorytest.php +++ b/tests/lib/l10n/factorytest.php @@ -28,6 +28,9 @@ class FactoryTest extends TestCase { /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject */ protected $userSession; + /** @var string */ + protected $serverRoot; + public function setUp() { parent::setUp(); @@ -42,6 +45,8 @@ class FactoryTest extends TestCase { ->getMock(); $this->userSession = $this->getMock('\OCP\IUserSession'); + + $this->serverRoot = \OC::$SERVERROOT; } /** @@ -54,12 +59,13 @@ class FactoryTest extends TestCase { ->setConstructorArgs([ $this->config, $this->request, - $this->userSession + $this->userSession, + $this->serverRoot, ]) ->setMethods($methods) ->getMock(); } else { - return new Factory($this->config, $this->request, $this->userSession); + return new Factory($this->config, $this->request, $this->userSession, $this->serverRoot); } } @@ -287,6 +293,24 @@ class FactoryTest extends TestCase { ]; } + public function testFindAvailableLanguagesWithThemes() { + $this->serverRoot .= '/tests/data'; + $app = 'files'; + + $factory = $this->getFactory(['findL10nDir']); + $factory->expects($this->once()) + ->method('findL10nDir') + ->with($app) + ->willReturn($this->serverRoot . '/apps/files/l10n/'); + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('theme') + ->willReturn('abc'); + + $this->assertEquals(['en', 'zz'], $factory->findAvailableLanguages($app), '', 0.0, 10, true); + } + /** * @dataProvider dataLanguageExists * diff --git a/tests/lib/l10n/l10nlegacytest.php b/tests/lib/l10n/l10nlegacytest.php index 025f761fe5c..1df22ba36bd 100644 --- a/tests/lib/l10n/l10nlegacytest.php +++ b/tests/lib/l10n/l10nlegacytest.php @@ -124,7 +124,7 @@ class L10nLegacyTest extends \Test\TestCase { } public function testFactoryGetLanguageCode() { - $factory = new \OC\L10N\Factory($this->getMock('OCP\IConfig'), $this->getMock('OCP\IRequest'), $this->getMock('OCP\IUserSession')); + $factory = new \OC\L10N\Factory($this->getMock('OCP\IConfig'), $this->getMock('OCP\IRequest'), $this->getMock('OCP\IUserSession'), \OC::$SERVERROOT); $l = $factory->get('lib', 'de'); $this->assertEquals('de', $l->getLanguageCode()); } diff --git a/tests/lib/l10n/l10ntest.php b/tests/lib/l10n/l10ntest.php index 0d175954bc1..227e07056a8 100644 --- a/tests/lib/l10n/l10ntest.php +++ b/tests/lib/l10n/l10ntest.php @@ -31,7 +31,7 @@ class L10nTest extends TestCase { $request = $this->getMock('OCP\IRequest'); /** @var IUserSession $userSession */ $userSession = $this->getMock('OCP\IUserSession'); - return new Factory($config, $request, $userSession); + return new Factory($config, $request, $userSession, \OC::$SERVERROOT); } public function testGermanPluralTranslations() { diff --git a/tests/lib/lock/dblockingprovider.php b/tests/lib/lock/dblockingprovider.php index 2032110f4f0..743dbf85613 100644 --- a/tests/lib/lock/dblockingprovider.php +++ b/tests/lib/lock/dblockingprovider.php @@ -64,7 +64,7 @@ class DBLockingProvider extends LockingProvider { */ protected function getInstance() { $this->connection = \OC::$server->getDatabaseConnection(); - return new \OC\Lock\DBLockingProvider($this->connection, \OC::$server->getLogger(), $this->timeFactory); + return new \OC\Lock\DBLockingProvider($this->connection, \OC::$server->getLogger(), $this->timeFactory, 3600); } public function tearDown() { @@ -81,7 +81,7 @@ class DBLockingProvider extends LockingProvider { $this->instance->acquireLock('bar', ILockingProvider::LOCK_EXCLUSIVE); $this->instance->changeLock('asd', ILockingProvider::LOCK_SHARED); - $this->currentTime = 150 + \OC\Lock\DBLockingProvider::TTL; + $this->currentTime = 150 + 3600; $this->assertEquals(3, $this->getLockEntryCount()); diff --git a/tests/lib/lock/lockingprovider.php b/tests/lib/lock/lockingprovider.php index ca72c1bb7f3..49742baa561 100644 --- a/tests/lib/lock/lockingprovider.php +++ b/tests/lib/lock/lockingprovider.php @@ -112,12 +112,14 @@ abstract class LockingProvider extends TestCase { $this->instance->acquireLock('foo', ILockingProvider::LOCK_SHARED); $this->instance->acquireLock('bar', ILockingProvider::LOCK_SHARED); $this->instance->acquireLock('asd', ILockingProvider::LOCK_EXCLUSIVE); + $this->instance->acquireLock('fizz#A=23', ILockingProvider::LOCK_EXCLUSIVE); $this->instance->releaseAll(); $this->assertFalse($this->instance->isLocked('foo', ILockingProvider::LOCK_SHARED)); $this->assertFalse($this->instance->isLocked('bar', ILockingProvider::LOCK_SHARED)); $this->assertFalse($this->instance->isLocked('asd', ILockingProvider::LOCK_EXCLUSIVE)); + $this->assertFalse($this->instance->isLocked('fizz#A=23', ILockingProvider::LOCK_EXCLUSIVE)); } public function testReleaseAllAfterChange() { diff --git a/tests/lib/notification/notificationtest.php b/tests/lib/notification/notificationtest.php index ee9454c77a0..c6ededf0142 100644 --- a/tests/lib/notification/notificationtest.php +++ b/tests/lib/notification/notificationtest.php @@ -517,6 +517,7 @@ class NotificationTest extends TestCase { ->setMethods([ 'isValidCommon', 'getSubject', + 'getParsedSubject', ]) ->getMock(); @@ -548,6 +549,7 @@ class NotificationTest extends TestCase { ->setMethods([ 'isValidCommon', 'getParsedSubject', + 'getSubject', ]) ->getMock(); diff --git a/tests/lib/share/hooktests.php b/tests/lib/share/hooktests.php deleted file mode 100644 index 7e6aaa259f2..00000000000 --- a/tests/lib/share/hooktests.php +++ /dev/null @@ -1,115 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * - * @copyright Copyright (c) 2015, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OC\Tests\Share; - - -use Test\TestCase; - -/** - * Class HookTests - * - * @group DB - * - * @package OC\Tests\Share - */ -class HookTests extends TestCase { - - protected function setUp() { - parent::setUp(); - } - - protected function tearDown() { - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `item_type` = ?'); - $query->execute(array('test')); - - parent::tearDown(); - } - - public function testPostAddToGroup() { - - /** @var \OC\DB\Connection $connection */ - $connection = \OC::$server->getDatabaseConnection(); - $query = $connection->createQueryBuilder(); - $expr = $query->expr(); - - // add some dummy values to the private $updateTargets variable - $this->invokePrivate( - new \OC\Share\Hooks(), - 'updateTargets', - [ - [ - 'group1' => - [ - [ - '`item_type`' => $expr->literal('test'), - '`item_source`' => $expr->literal('42'), - '`item_target`' => $expr->literal('42'), - '`file_target`' => $expr->literal('test'), - '`share_type`' => $expr->literal('2'), - '`share_with`' => $expr->literal('group1'), - '`uid_owner`' => $expr->literal('owner'), - '`permissions`' => $expr->literal('0'), - '`stime`' => $expr->literal('676584'), - '`file_source`' => $expr->literal('42'), - ], - [ - '`item_type`' => $expr->literal('test'), - '`item_source`' => $expr->literal('42'), - '`item_target`' => $expr->literal('42 (2)'), - '`share_type`' => $expr->literal('2'), - '`share_with`' => $expr->literal('group1'), - '`uid_owner`' => $expr->literal('owner'), - '`permissions`' => $expr->literal('0'), - '`stime`' => $expr->literal('676584'), - ] - ], - 'group2' => - [ - [ - '`item_type`' => $expr->literal('test'), - '`item_source`' => $expr->literal('42'), - '`item_target`' => $expr->literal('42'), - '`share_type`' => $expr->literal('2'), - '`share_with`' => $expr->literal('group2'), - '`uid_owner`' => $expr->literal('owner'), - '`permissions`' => $expr->literal('0'), - '`stime`' => $expr->literal('676584'), - ] - ] - ] - ] - ); - - // add unique targets for group1 to database - \OC\Share\Hooks::post_addToGroup(['gid' => 'group1']); - - - $query->select('`share_with`')->from('`*PREFIX*share`'); - $result = $query->execute()->fetchAll(); - $this->assertSame(2, count($result)); - foreach ($result as $r) { - $this->assertSame('group1', $r['share_with']); - } - } - -} diff --git a/tests/lib/share/share.php b/tests/lib/share/share.php index 4519c33f9d1..a07e90effc3 100644 --- a/tests/lib/share/share.php +++ b/tests/lib/share/share.php @@ -63,7 +63,7 @@ class Test_Share extends \Test\TestCase { \OC::$server->getUserManager()->createUser($this->groupAndUser, 'pass'); OC_User::setUserId($this->user1); OC_Group::clearBackends(); - OC_Group::useBackend(new OC_Group_Dummy); + OC_Group::useBackend(new \Test\Util\Group\Dummy()); $this->group1 = $this->getUniqueID('group1_'); $this->group2 = $this->getUniqueID('group2_'); OC_Group::createGroup($this->group1); @@ -611,162 +611,6 @@ class Test_Share extends \Test\TestCase { ); } - public function testShareWithGroup() { - // Invalid shares - $message = 'Sharing test.txt failed, because the group foobar does not exist'; - try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, 'foobar', \OCP\Constants::PERMISSION_READ); - $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { - $this->assertEquals($message, $exception->getMessage()); - } - $policy = \OC::$server->getAppConfig()->getValue('core', 'shareapi_only_share_with_group_members', 'no'); - \OC::$server->getAppConfig()->setValue('core', 'shareapi_only_share_with_group_members', 'yes'); - $message = 'Sharing test.txt failed, because '.$this->user1.' is not a member of the group '.$this->group2; - try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group2, \OCP\Constants::PERMISSION_READ); - $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { - $this->assertEquals($message, $exception->getMessage()); - } - \OC::$server->getAppConfig()->setValue('core', 'shareapi_only_share_with_group_members', $policy); - - // Valid share - $this->shareUserOneTestFileWithGroupOne(); - - // check if only the group share was created and not a single db-entry for each user - $statement = \OCP\DB::prepare('select `id` from `*PREFIX*share`'); - $query = $statement->execute(); - $result = $query->fetchAll(); - $this->assertSame(1, count($result)); - - - // Attempt to share again - OC_User::setUserId($this->user1); - $message = 'Sharing test.txt failed, because this item is already shared with '.$this->group1; - try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ); - $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { - $this->assertEquals($message, $exception->getMessage()); - } - - // Attempt to share back to owner of group share - OC_User::setUserId($this->user2); - $message = 'Sharing failed, because the user '.$this->user1.' is the original sharer'; - try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user1, \OCP\Constants::PERMISSION_READ); - $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { - $this->assertEquals($message, $exception->getMessage()); - } - - // Attempt to share back to group - $message = 'Sharing test.txt failed, because this item is already shared with '.$this->group1; - try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ); - $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { - $this->assertEquals($message, $exception->getMessage()); - } - - // Attempt to share back to member of group - $message ='Sharing test.txt failed, because this item is already shared with '.$this->user3; - try { - OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user3, \OCP\Constants::PERMISSION_READ); - $this->fail('Exception was expected: '.$message); - } catch (Exception $exception) { - $this->assertEquals($message, $exception->getMessage()); - } - - // Unshare - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::unshare('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1)); - - // Valid share with same person - user then group - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_SHARE)); - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE)); - OC_User::setUserId($this->user2); - $this->assertEquals(array('test.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_SHARE), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); - OC_User::setUserId($this->user3); - $this->assertEquals(array('test.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); - - // Valid reshare - OC_User::setUserId($this->user2); - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_READ)); - OC_User::setUserId($this->user4); - $this->assertEquals(array('test.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - - // Unshare from user only - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::unshare('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2)); - OC_User::setUserId($this->user2); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); - OC_User::setUserId($this->user4); - $this->assertEquals(array('test.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - - // Valid share with same person - group then user - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::shareItem('test', 'test.txt', OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE)); - OC_User::setUserId($this->user2); - $this->assertEquals(array('test.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); - - // Unshare from group only - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::unshare('test', 'test.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1)); - OC_User::setUserId($this->user2); - $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE), OCP\Share::getItemSharedWith('test', 'test.txt', Test_Share_Backend::FORMAT_PERMISSIONS)); - - // Attempt user specific target conflict - OC_User::setUserId($this->user3); - \OCP\Util::connectHook('OCP\\Share', 'post_shared', 'DummyHookListener', 'listen'); - - $this->assertTrue(OCP\Share::shareItem('test', 'share.txt', OCP\Share::SHARE_TYPE_GROUP, $this->group1, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE)); - $this->assertEquals(OCP\Share::SHARE_TYPE_GROUP, DummyHookListener::$shareType); - OC_User::setUserId($this->user2); - $to_test = OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET); - $this->assertEquals(2, count($to_test)); - $this->assertTrue(in_array('test.txt', $to_test)); - $this->assertTrue(in_array('test1.txt', $to_test)); - - // Valid reshare - $this->assertTrue(OCP\Share::shareItem('test', 'share.txt', OCP\Share::SHARE_TYPE_USER, $this->user4, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE)); - OC_User::setUserId($this->user4); - $this->assertEquals(array('test1.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - - // Remove user from group - OC_Group::removeFromGroup($this->user2, $this->group1); - OC_User::setUserId($this->user2); - $this->assertEquals(array('test.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - OC_User::setUserId($this->user4); - $this->assertEquals(array(), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - - // Add user to group - OC_Group::addToGroup($this->user4, $this->group1); - $this->assertEquals(array('test.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - - // Unshare from self - $this->assertTrue(OCP\Share::unshareFromSelf('test', 'test.txt')); - $this->assertEquals(array(), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - OC_User::setUserId($this->user2); - $this->assertEquals(array('test.txt'), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - - // Unshare from self via source - OC_User::setUserId($this->user1); - $this->assertTrue(OCP\Share::unshareFromSelf('test', 'share.txt', true)); - $this->assertEquals(array(), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - - // Remove group - OC_Group::deleteGroup($this->group1); - OC_User::setUserId($this->user4); - $this->assertEquals(array(), OCP\Share::getItemsSharedWith('test', Test_Share_Backend::FORMAT_TARGET)); - OC_User::setUserId($this->user3); - $this->assertEquals(array(), OCP\Share::getItemsShared('test')); - } - /** * Test that unsharing from group will also delete all * child entries diff --git a/tests/lib/share20/defaultshareprovidertest.php b/tests/lib/share20/defaultshareprovidertest.php index 60024989681..44a48535b9b 100644 --- a/tests/lib/share20/defaultshareprovidertest.php +++ b/tests/lib/share20/defaultshareprovidertest.php @@ -123,7 +123,8 @@ class DefaultShareProviderTest extends \Test\TestCase { ->values([ 'share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_USER), 'share_with' => $qb->expr()->literal('sharedWith'), - 'uid_owner' => $qb->expr()->literal('sharedBy'), + 'uid_owner' => $qb->expr()->literal('shareOwner'), + 'uid_initiator' => $qb->expr()->literal('sharedBy'), 'item_type' => $qb->expr()->literal('file'), 'file_source' => $qb->expr()->literal(42), 'file_target' => $qb->expr()->literal('myTarget'), @@ -133,27 +134,18 @@ class DefaultShareProviderTest extends \Test\TestCase { $id = $qb->getLastInsertId(); - $sharedWith = $this->getMock('OCP\IUser'); $sharedBy = $this->getMock('OCP\IUser'); $sharedBy->method('getUID')->willReturn('sharedBy'); $shareOwner = $this->getMock('OCP\IUser'); $shareOwner->method('getUID')->willReturn('shareOwner'); - $sharedByPath = $this->getMock('\OCP\Files\File'); $ownerPath = $this->getMock('\OCP\Files\File'); - - $sharedByPath->method('getOwner')->willReturn($shareOwner); - - $sharedByFolder = $this->getMock('\OCP\Files\Folder'); - $sharedByFolder->method('getById')->with(42)->willReturn([$sharedByPath]); - $shareOwnerFolder = $this->getMock('\OCP\Files\Folder'); $shareOwnerFolder->method('getById')->with(42)->willReturn([$ownerPath]); $this->rootFolder ->method('getUserFolder') ->will($this->returnValueMap([ - ['sharedBy', $sharedByFolder], ['shareOwner', $shareOwnerFolder], ])); @@ -257,7 +249,8 @@ class DefaultShareProviderTest extends \Test\TestCase { ->values([ 'share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_GROUP), 'share_with' => $qb->expr()->literal('sharedWith'), - 'uid_owner' => $qb->expr()->literal('sharedBy'), + 'uid_owner' => $qb->expr()->literal('shareOwner'), + 'uid_initiator' => $qb->expr()->literal('sharedBy'), 'item_type' => $qb->expr()->literal('file'), 'file_source' => $qb->expr()->literal(42), 'file_target' => $qb->expr()->literal('myTarget'), @@ -268,27 +261,13 @@ class DefaultShareProviderTest extends \Test\TestCase { // Get the id $id = $qb->getLastInsertId(); - $sharedWith = $this->getMock('OCP\IGroup'); - $sharedBy = $this->getMock('OCP\IUser'); - $sharedBy->method('getUID')->willReturn('sharedBy'); - $shareOwner = $this->getMock('OCP\IUser'); - $shareOwner->method('getUID')->willReturn('shareOwner'); - - $sharedByPath = $this->getMock('\OCP\Files\Folder'); $ownerPath = $this->getMock('\OCP\Files\Folder'); - - $sharedByPath->method('getOwner')->willReturn($shareOwner); - - $sharedByFolder = $this->getMock('\OCP\Files\Folder'); - $sharedByFolder->method('getById')->with(42)->willReturn([$sharedByPath]); - $shareOwnerFolder = $this->getMock('\OCP\Files\Folder'); $shareOwnerFolder->method('getById')->with(42)->willReturn([$ownerPath]); $this->rootFolder ->method('getUserFolder') ->will($this->returnValueMap([ - ['sharedBy', $sharedByFolder], ['shareOwner', $shareOwnerFolder], ])); @@ -351,7 +330,8 @@ class DefaultShareProviderTest extends \Test\TestCase { ->values([ 'share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_LINK), 'share_with' => $qb->expr()->literal('sharedWith'), - 'uid_owner' => $qb->expr()->literal('sharedBy'), + 'uid_owner' => $qb->expr()->literal('shareOwner'), + 'uid_initiator' => $qb->expr()->literal('sharedBy'), 'item_type' => $qb->expr()->literal('file'), 'file_source' => $qb->expr()->literal(42), 'file_target' => $qb->expr()->literal('myTarget'), @@ -363,36 +343,16 @@ class DefaultShareProviderTest extends \Test\TestCase { $id = $qb->getLastInsertId(); - $sharedBy = $this->getMock('OCP\IUser'); - $sharedBy->method('getUID')->willReturn('sharedBy'); - $shareOwner = $this->getMock('OCP\IUser'); - $shareOwner->method('getUID')->willReturn('shareOwner'); - - $sharedByPath = $this->getMock('\OCP\Files\Folder'); $ownerPath = $this->getMock('\OCP\Files\Folder'); - - $sharedByPath->method('getOwner')->willReturn($shareOwner); - - $sharedByFolder = $this->getMock('\OCP\Files\Folder'); - $sharedByFolder->method('getById')->with(42)->willReturn([$sharedByPath]); - $shareOwnerFolder = $this->getMock('\OCP\Files\Folder'); $shareOwnerFolder->method('getById')->with(42)->willReturn([$ownerPath]); $this->rootFolder ->method('getUserFolder') ->will($this->returnValueMap([ - ['sharedBy', $sharedByFolder], ['shareOwner', $shareOwnerFolder], ])); - $this->userManager - ->method('get') - ->will($this->returnValueMap([ - ['sharedBy', $sharedBy], - ['shareOwner', $shareOwner], - ])); - $share = $this->provider->getShareById($id); $this->assertEquals($id, $share->getId()); @@ -544,7 +504,8 @@ class DefaultShareProviderTest extends \Test\TestCase { ->values([ 'share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_USER), 'share_with' => $qb->expr()->literal('sharedWith'), - 'uid_owner' => $qb->expr()->literal('sharedBy'), + 'uid_owner' => $qb->expr()->literal('shareOwner'), + 'uid_initiator' => $qb->expr()->literal('sharedBy'), 'item_type' => $qb->expr()->literal('file'), 'file_source' => $qb->expr()->literal(42), 'file_target' => $qb->expr()->literal('myTarget'), @@ -553,22 +514,15 @@ class DefaultShareProviderTest extends \Test\TestCase { $qb->execute(); // Get the id - $qb = $this->dbConn->getQueryBuilder(); - $cursor = $qb->select('id') - ->from('share') - ->setMaxResults(1) - ->orderBy('id', 'DESC') - ->execute(); - $id = $cursor->fetch(); - $id = $id['id']; - $cursor->closeCursor(); + $id = $qb->getLastInsertId(); $qb = $this->dbConn->getQueryBuilder(); $qb->insert('share') ->values([ 'share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_USER), 'share_with' => $qb->expr()->literal('user1'), - 'uid_owner' => $qb->expr()->literal('user2'), + 'uid_owner' => $qb->expr()->literal('shareOwner'), + 'uid_initiator' => $qb->expr()->literal('user2'), 'item_type' => $qb->expr()->literal('file'), 'file_source' => $qb->expr()->literal(1), 'file_target' => $qb->expr()->literal('myTarget1'), @@ -582,7 +536,8 @@ class DefaultShareProviderTest extends \Test\TestCase { ->values([ 'share_type' => $qb->expr()->literal(\OCP\Share::SHARE_TYPE_GROUP), 'share_with' => $qb->expr()->literal('group1'), - 'uid_owner' => $qb->expr()->literal('user3'), + 'uid_owner' => $qb->expr()->literal('shareOwner'), + 'uid_initiator' => $qb->expr()->literal('user3'), 'item_type' => $qb->expr()->literal('folder'), 'file_source' => $qb->expr()->literal(3), 'file_target' => $qb->expr()->literal('myTarget2'), @@ -591,30 +546,6 @@ class DefaultShareProviderTest extends \Test\TestCase { ]); $qb->execute(); - $shareOwner = $this->getMock('OCP\IUser'); - $shareOwner->method('getUID')->willReturn('shareOwner'); - $user1 = $this->getMock('OCP\IUser'); - $user2 = $this->getMock('OCP\IUser'); - $user2->method('getUID')->willReturn('user2'); - $user3 = $this->getMock('OCP\IUser'); - $user3->method('getUID')->willReturn('user3'); - - $user2Path = $this->getMock('\OCP\Files\File'); - $user2Path->expects($this->once())->method('getOwner')->willReturn($shareOwner); - $user2Folder = $this->getMock('\OCP\Files\Folder'); - $user2Folder->expects($this->once()) - ->method('getById') - ->with(1) - ->willReturn([$user2Path]); - - $user3Path = $this->getMock('\OCP\Files\Folder'); - $user3Path->expects($this->once())->method('getOwner')->willReturn($shareOwner); - $user3Folder = $this->getMock('\OCP\Files\Folder'); - $user3Folder->expects($this->once()) - ->method('getById') - ->with(3) - ->willReturn([$user3Path]); - $ownerPath = $this->getMock('\OCP\Files\Folder'); $ownerFolder = $this->getMock('\OCP\Files\Folder'); $ownerFolder->method('getById')->willReturn([$ownerPath]); @@ -623,23 +554,6 @@ class DefaultShareProviderTest extends \Test\TestCase { ->method('getUserFolder') ->will($this->returnValueMap([ ['shareOwner', $ownerFolder], - ['user2', $user2Folder], - ['user3', $user3Folder], - ])); - - $this->userManager - ->method('get') - ->will($this->returnValueMap([ - ['user1', $user1], - ['user2', $user2], - ['user3', $user3], - ])); - - $group1 = $this->getMock('OCP\IGroup'); - $this->groupManager - ->method('get') - ->will($this->returnValueMap([ - ['group1', $group1] ])); $share = $this->getMock('\OCP\Share\IShare'); @@ -1055,7 +969,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertCount(1, $share); $share = $share[0]; - $this->assertSame($id, $share->getId()); + $this->assertSame((string)$id, $share->getId()); $this->assertSame('sharedWith', $share->getSharedWith()); $this->assertSame('shareOwner', $share->getShareOwner()); $this->assertSame('sharedBy', $share->getSharedBy()); @@ -1958,4 +1872,283 @@ class DefaultShareProviderTest extends \Test\TestCase { $share = $this->provider->getShareById($id, 'user0'); $this->assertSame('/ultraNewTarget', $share->getTarget()); } + + public function dataDeleteUser() { + return [ + [\OCP\Share::SHARE_TYPE_USER, 'a', 'b', 'c', 'a', true], + [\OCP\Share::SHARE_TYPE_USER, 'a', 'b', 'c', 'b', false], + [\OCP\Share::SHARE_TYPE_USER, 'a', 'b', 'c', 'c', true], + [\OCP\Share::SHARE_TYPE_USER, 'a', 'b', 'c', 'd', false], + [\OCP\Share::SHARE_TYPE_GROUP, 'a', 'b', 'c', 'a', true], + [\OCP\Share::SHARE_TYPE_GROUP, 'a', 'b', 'c', 'b', false], + // The group c is still valid but user c is deleted so group share stays + [\OCP\Share::SHARE_TYPE_GROUP, 'a', 'b', 'c', 'c', false], + [\OCP\Share::SHARE_TYPE_GROUP, 'a', 'b', 'c', 'd', false], + [\OCP\Share::SHARE_TYPE_LINK, 'a', 'b', 'c', 'a', true], + // To avoid invisible link shares delete initiated link shares as well (see #22327) + [\OCP\Share::SHARE_TYPE_LINK, 'a', 'b', 'c', 'b', true], + [\OCP\Share::SHARE_TYPE_LINK, 'a', 'b', 'c', 'c', false], + [\OCP\Share::SHARE_TYPE_LINK, 'a', 'b', 'c', 'd', false], + ]; + } + + /** + * @dataProvider dataDeleteUser + * + * @param int $type The shareType (user/group/link) + * @param string $owner The owner of the share (uid) + * @param string $initiator The initiator of the share (uid) + * @param string $recipient The recipient of the share (uid/gid/pass) + * @param string $deletedUser The user that is deleted + * @param bool $rowDeleted Is the row deleted in this setup + */ + public function testDeleteUser($type, $owner, $initiator, $recipient, $deletedUser, $rowDeleted) { + $qb = $this->dbConn->getQueryBuilder(); + $qb->insert('share') + ->setValue('share_type', $qb->createNamedParameter($type)) + ->setValue('uid_owner', $qb->createNamedParameter($owner)) + ->setValue('uid_initiator', $qb->createNamedParameter($initiator)) + ->setValue('share_with', $qb->createNamedParameter($recipient)) + ->setValue('item_type', $qb->createNamedParameter('file')) + ->setValue('item_source', $qb->createNamedParameter(42)) + ->setValue('file_source', $qb->createNamedParameter(42)) + ->execute(); + + $id = $qb->getLastInsertId(); + + $this->provider->userDeleted($deletedUser, $type); + + $qb = $this->dbConn->getQueryBuilder(); + $qb->select('*') + ->from('share') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($id)) + ); + $cursor = $qb->execute(); + $data = $cursor->fetchAll(); + $cursor->closeCursor(); + + $this->assertCount($rowDeleted ? 0 : 1, $data); + } + + public function dataDeleteUserGroup() { + return [ + ['a', 'b', 'c', 'a', true, true], + ['a', 'b', 'c', 'b', false, false], + ['a', 'b', 'c', 'c', false, true], + ['a', 'b', 'c', 'd', false, false], + ]; + } + + /** + * @dataProvider dataDeleteUserGroup + * + * @param string $owner The owner of the share (uid) + * @param string $initiator The initiator of the share (uid) + * @param string $recipient The recipient of the usergroup share (uid) + * @param string $deletedUser The user that is deleted + * @param bool $groupShareDeleted + * @param bool $userGroupShareDeleted + */ + public function testDeleteUserGroup($owner, $initiator, $recipient, $deletedUser, $groupShareDeleted, $userGroupShareDeleted) { + $qb = $this->dbConn->getQueryBuilder(); + $qb->insert('share') + ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)) + ->setValue('uid_owner', $qb->createNamedParameter($owner)) + ->setValue('uid_initiator', $qb->createNamedParameter($initiator)) + ->setValue('share_with', $qb->createNamedParameter('group')) + ->setValue('item_type', $qb->createNamedParameter('file')) + ->setValue('item_source', $qb->createNamedParameter(42)) + ->setValue('file_source', $qb->createNamedParameter(42)) + ->execute(); + $groupId = $qb->getLastInsertId(); + + $qb = $this->dbConn->getQueryBuilder(); + $qb->insert('share') + ->setValue('share_type', $qb->createNamedParameter(2)) + ->setValue('uid_owner', $qb->createNamedParameter($owner)) + ->setValue('uid_initiator', $qb->createNamedParameter($initiator)) + ->setValue('share_with', $qb->createNamedParameter($recipient)) + ->setValue('item_type', $qb->createNamedParameter('file')) + ->setValue('item_source', $qb->createNamedParameter(42)) + ->setValue('file_source', $qb->createNamedParameter(42)) + ->execute(); + $userGroupId = $qb->getLastInsertId(); + + $this->provider->userDeleted($deletedUser, \OCP\Share::SHARE_TYPE_GROUP); + + $qb = $this->dbConn->getQueryBuilder(); + $qb->select('*') + ->from('share') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($userGroupId)) + ); + $cursor = $qb->execute(); + $data = $cursor->fetchAll(); + $cursor->closeCursor(); + $this->assertCount($userGroupShareDeleted ? 0 : 1, $data); + + $qb = $this->dbConn->getQueryBuilder(); + $qb->select('*') + ->from('share') + ->where( + $qb->expr()->eq('id', $qb->createNamedParameter($groupId)) + ); + $cursor = $qb->execute(); + $data = $cursor->fetchAll(); + $cursor->closeCursor(); + $this->assertCount($groupShareDeleted ? 0 : 1, $data); + } + + public function dataGroupDeleted() { + return [ + [ + [ + 'type' => \OCP\Share::SHARE_TYPE_USER, + 'recipient' => 'user', + 'children' => [] + ], 'group', false + ], + [ + [ + 'type' => \OCP\Share::SHARE_TYPE_USER, + 'recipient' => 'user', + 'children' => [] + ], 'user', false + ], + [ + [ + 'type' => \OCP\Share::SHARE_TYPE_LINK, + 'recipient' => 'user', + 'children' => [] + ], 'group', false + ], + [ + [ + 'type' => \OCP\Share::SHARE_TYPE_GROUP, + 'recipient' => 'group1', + 'children' => [ + 'foo', + 'bar' + ] + ], 'group2', false + ], + [ + [ + 'type' => \OCP\Share::SHARE_TYPE_GROUP, + 'recipient' => 'group1', + 'children' => [ + 'foo', + 'bar' + ] + ], 'group1', true + ], + ]; + } + + /** + * @dataProvider dataGroupDeleted + * + * @param $shares + * @param $groupToDelete + * @param $shouldBeDeleted + */ + public function testGroupDeleted($shares, $groupToDelete, $shouldBeDeleted) { + $qb = $this->dbConn->getQueryBuilder(); + $qb->insert('share') + ->setValue('share_type', $qb->createNamedParameter($shares['type'])) + ->setValue('uid_owner', $qb->createNamedParameter('owner')) + ->setValue('uid_initiator', $qb->createNamedParameter('initiator')) + ->setValue('share_with', $qb->createNamedParameter($shares['recipient'])) + ->setValue('item_type', $qb->createNamedParameter('file')) + ->setValue('item_source', $qb->createNamedParameter(42)) + ->setValue('file_source', $qb->createNamedParameter(42)) + ->execute(); + $ids = [$qb->getLastInsertId()]; + + foreach ($shares['children'] as $child) { + $qb = $this->dbConn->getQueryBuilder(); + $qb->insert('share') + ->setValue('share_type', $qb->createNamedParameter(2)) + ->setValue('uid_owner', $qb->createNamedParameter('owner')) + ->setValue('uid_initiator', $qb->createNamedParameter('initiator')) + ->setValue('share_with', $qb->createNamedParameter($child)) + ->setValue('item_type', $qb->createNamedParameter('file')) + ->setValue('item_source', $qb->createNamedParameter(42)) + ->setValue('file_source', $qb->createNamedParameter(42)) + ->setValue('parent', $qb->createNamedParameter($ids[0])) + ->execute(); + $ids[] = $qb->getLastInsertId(); + } + + $this->provider->groupDeleted($groupToDelete); + + $qb = $this->dbConn->getQueryBuilder(); + $cursor = $qb->select('*') + ->from('share') + ->where($qb->expr()->in('id', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY))) + ->execute(); + $data = $cursor->fetchAll(); + $cursor->closeCursor(); + + $this->assertCount($shouldBeDeleted ? 0 : count($ids), $data); + } + + public function dataUserDeletedFromGroup() { + return [ + ['group1', 'user1', true], + ['group1', 'user2', false], + ['group2', 'user1', false], + ]; + } + + /** + * Given a group share with 'group1' + * And a user specific group share with 'user1'. + * User $user is deleted from group $gid. + * + * @dataProvider dataUserDeletedFromGroup + * + * @param string $group + * @param string $user + * @param bool $toDelete + */ + public function testUserDeletedFromGroup($group, $user, $toDelete) { + $qb = $this->dbConn->getQueryBuilder(); + $qb->insert('share') + ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)) + ->setValue('uid_owner', $qb->createNamedParameter('owner')) + ->setValue('uid_initiator', $qb->createNamedParameter('initiator')) + ->setValue('share_with', $qb->createNamedParameter('group1')) + ->setValue('item_type', $qb->createNamedParameter('file')) + ->setValue('item_source', $qb->createNamedParameter(42)) + ->setValue('file_source', $qb->createNamedParameter(42)); + $qb->execute(); + $id1 = $qb->getLastInsertId(); + + $qb = $this->dbConn->getQueryBuilder(); + $qb->insert('share') + ->setValue('share_type', $qb->createNamedParameter(2)) + ->setValue('uid_owner', $qb->createNamedParameter('owner')) + ->setValue('uid_initiator', $qb->createNamedParameter('initiator')) + ->setValue('share_with', $qb->createNamedParameter('user1')) + ->setValue('item_type', $qb->createNamedParameter('file')) + ->setValue('item_source', $qb->createNamedParameter(42)) + ->setValue('file_source', $qb->createNamedParameter(42)) + ->setValue('parent', $qb->createNamedParameter($id1)); + $qb->execute(); + $id2 = $qb->getLastInsertId(); + + $this->provider->userDeletedFromGroup($user, $group); + + $qb = $this->dbConn->getQueryBuilder(); + $qb->select('*') + ->from('share') + ->where($qb->expr()->eq('id', $qb->createNamedParameter($id2))); + $cursor = $qb->execute(); + $data = $cursor->fetchAll(); + $cursor->closeCursor(); + + $this->assertCount($toDelete ? 0 : 1, $data); + } } diff --git a/tests/lib/share20/managertest.php b/tests/lib/share20/managertest.php index 4f23dd0e6d0..7d79150449c 100644 --- a/tests/lib/share20/managertest.php +++ b/tests/lib/share20/managertest.php @@ -579,7 +579,7 @@ class ManagerTest extends \Test\TestCase { $share->method('getShareType')->willReturn($type); $share->method('getSharedWith')->willReturn($sharedWith); $share->method('getSharedBy')->willReturn($sharedBy); - $share->method('getSharedOwner')->willReturn($shareOwner); + $share->method('getShareOwner')->willReturn($shareOwner); $share->method('getNode')->willReturn($path); $share->method('getPermissions')->willReturn($permissions); $share->method('getExpirationDate')->willReturn($expireDate); @@ -640,10 +640,21 @@ class ManagerTest extends \Test\TestCase { $data[] = [$this->createShare(null, \OCP\Share::SHARE_TYPE_GROUP, $limitedPermssions, $group0, $user0, $user0, null, null, null), 'A share requires permissions', true]; $data[] = [$this->createShare(null, \OCP\Share::SHARE_TYPE_LINK, $limitedPermssions, null, $user0, $user0, null, null, null), 'A share requires permissions', true]; + $mount = $this->getMock('OC\Files\Mount\MoveableMount'); + $limitedPermssions->method('getMountPoint')->willReturn($mount); + $data[] = [$this->createShare(null, \OCP\Share::SHARE_TYPE_USER, $limitedPermssions, $user2, $user0, $user0, 31, null, null), 'Cannot increase permissions of path', true]; $data[] = [$this->createShare(null, \OCP\Share::SHARE_TYPE_GROUP, $limitedPermssions, $group0, $user0, $user0, 17, null, null), 'Cannot increase permissions of path', true]; $data[] = [$this->createShare(null, \OCP\Share::SHARE_TYPE_LINK, $limitedPermssions, null, $user0, $user0, 3, null, null), 'Cannot increase permissions of path', true]; + $nonMoveableMountPermssions = $this->getMock('\OCP\Files\Folder'); + $nonMoveableMountPermssions->method('isShareable')->willReturn(true); + $nonMoveableMountPermssions->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_READ); + $nonMoveableMountPermssions->method('getPath')->willReturn('path'); + + $data[] = [$this->createShare(null, \OCP\Share::SHARE_TYPE_USER, $nonMoveableMountPermssions, $user2, $user0, $user0, 11, null, null), 'Cannot increase permissions of path', false]; + $data[] = [$this->createShare(null, \OCP\Share::SHARE_TYPE_GROUP, $nonMoveableMountPermssions, $group0, $user0, $user0, 11, null, null), 'Cannot increase permissions of path', false]; + $rootFolder = $this->getMock('\OCP\Files\Folder'); $rootFolder->method('isShareable')->willReturn(true); $rootFolder->method('getPermissions')->willReturn(\OCP\Constants::PERMISSION_ALL); @@ -1149,6 +1160,22 @@ class ManagerTest extends \Test\TestCase { /** * @expectedException Exception + * @expectedExceptionMessage Group sharing is now allowed + */ + public function testGroupCreateChecksShareWithGroupMembersGroupSharingNotAllowed() { + $share = $this->manager->newShare(); + + $this->config + ->method('getAppValue') + ->will($this->returnValueMap([ + ['core', 'shareapi_allow_group_sharing', 'yes', 'no'], + ])); + + $this->invokePrivate($this->manager, 'groupCreateChecks', [$share]); + } + + /** + * @expectedException Exception * @expectedExceptionMessage Only sharing within your own groups is allowed */ public function testGroupCreateChecksShareWithGroupMembersOnlyNotInGroup() { @@ -1167,6 +1194,7 @@ class ManagerTest extends \Test\TestCase { ->method('getAppValue') ->will($this->returnValueMap([ ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'], + ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'], ])); $this->invokePrivate($this->manager, 'groupCreateChecks', [$share]); @@ -1195,6 +1223,7 @@ class ManagerTest extends \Test\TestCase { ->method('getAppValue') ->will($this->returnValueMap([ ['core', 'shareapi_only_share_with_group_members', 'no', 'yes'], + ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'], ])); $this->invokePrivate($this->manager, 'groupCreateChecks', [$share]); @@ -1222,6 +1251,12 @@ class ManagerTest extends \Test\TestCase { ->with($path) ->willReturn([$share2]); + $this->config + ->method('getAppValue') + ->will($this->returnValueMap([ + ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'], + ])); + $this->invokePrivate($this->manager, 'groupCreateChecks', [$share]); } @@ -1240,6 +1275,12 @@ class ManagerTest extends \Test\TestCase { ->with($path) ->willReturn([$share2]); + $this->config + ->method('getAppValue') + ->will($this->returnValueMap([ + ['core', 'shareapi_allow_group_sharing', 'yes', 'yes'], + ])); + $this->invokePrivate($this->manager, 'groupCreateChecks', [$share]); } @@ -2001,6 +2042,46 @@ class ManagerTest extends \Test\TestCase { $this->assertSame($share, $ret); } + public function testGetShareByTokenWithException() { + $factory = $this->getMock('\OCP\Share\IProviderFactory'); + + $manager = new Manager( + $this->logger, + $this->config, + $this->secureRandom, + $this->hasher, + $this->mountManager, + $this->groupManager, + $this->l, + $factory, + $this->userManager, + $this->rootFolder + ); + + $share = $this->getMock('\OCP\Share\IShare'); + + $factory->expects($this->at(0)) + ->method('getProviderForType') + ->with(\OCP\Share::SHARE_TYPE_LINK) + ->willReturn($this->defaultProvider); + $factory->expects($this->at(1)) + ->method('getProviderForType') + ->with(\OCP\Share::SHARE_TYPE_REMOTE) + ->willReturn($this->defaultProvider); + + $this->defaultProvider->expects($this->at(0)) + ->method('getShareByToken') + ->with('token') + ->will($this->throwException(new ShareNotFound())); + $this->defaultProvider->expects($this->at(1)) + ->method('getShareByToken') + ->with('token') + ->willReturn($share); + + $ret = $manager->getShareByToken('token'); + $this->assertSame($share, $ret); + } + /** * @expectedException \OCP\Share\Exceptions\ShareNotFound */ @@ -2043,6 +2124,25 @@ class ManagerTest extends \Test\TestCase { $this->assertSame($share, $res); } + public function testGetShareByTokenPublicSharingDisabled() { + $share = $this->manager->newShare(); + $share->setShareType(\OCP\Share::SHARE_TYPE_LINK) + ->setPermissions(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE); + + $this->config->method('getAppValue')->will($this->returnValueMap([ + ['core', 'shareapi_allow_public_upload', 'yes', 'no'], + ])); + + $this->defaultProvider->expects($this->once()) + ->method('getShareByToken') + ->willReturn('validToken') + ->willReturn($share); + + $res = $this->manager->getShareByToken('validToken'); + + $this->assertSame(\OCP\Constants::PERMISSION_READ, $res->getPermissions()); + } + public function testCheckPasswordNoLinkShare() { $share = $this->getMock('\OCP\Share\IShare'); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_USER); @@ -2377,7 +2477,9 @@ class ManagerTest extends \Test\TestCase { public function testMoveShareUser() { $share = $this->manager->newShare(); - $share->setShareType(\OCP\Share::SHARE_TYPE_USER); + $share->setShareType(\OCP\Share::SHARE_TYPE_USER) + ->setId('42') + ->setProviderId('foo'); $share->setSharedWith('recipient'); @@ -2408,7 +2510,9 @@ class ManagerTest extends \Test\TestCase { public function testMoveShareGroup() { $share = $this->manager->newShare(); - $share->setShareType(\OCP\Share::SHARE_TYPE_GROUP); + $share->setShareType(\OCP\Share::SHARE_TYPE_GROUP) + ->setId('42') + ->setProviderId('foo'); $group = $this->getMock('\OCP\IGroup'); $share->setSharedWith('group'); diff --git a/tests/lib/share20/sharetest.php b/tests/lib/share20/sharetest.php new file mode 100644 index 00000000000..fdfc69f6577 --- /dev/null +++ b/tests/lib/share20/sharetest.php @@ -0,0 +1,93 @@ +<?php +/** + * @author Roeland Jago Douma <rullzer@owncloud.com> + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ +namespace Test\Share20; + +use OCP\Files\IRootFolder; + +/** + * Class ShareTest + * + * @package Test\Share20 + */ +class ShareTest extends \Test\TestCase { + + /** @var IRootFolder|\PHPUnit_Framework_MockObject_MockObject */ + protected $rootFolder; + /** @var \OCP\Share\IShare */ + protected $share; + + public function setUp() { + $this->rootFolder = $this->getMock('\OCP\Files\IRootFolder'); + $this->share = new \OC\Share20\Share($this->rootFolder); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage String expected. + */ + public function testSetIdInvalid() { + $this->share->setId(1.2); + } + + public function testSetIdInt() { + $this->share->setId(42); + $this->assertEquals('42', $this->share->getId()); + } + + + public function testSetIdString() { + $this->share->setId('foo'); + $this->assertEquals('foo', $this->share->getId()); + } + + /** + * @expectedException \OCP\Share\Exceptions\IllegalIDChangeException + * @expectedExceptionMessage Not allowed to assign a new internal id to a share + */ + public function testSetIdOnce() { + $this->share->setId('foo'); + $this->share->setId('bar'); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage String expected. + */ + public function testSetProviderIdInt() { + $this->share->setProviderId(42); + } + + + public function testSetProviderIdString() { + $this->share->setProviderId('foo'); + $this->share->setId('bar'); + $this->assertEquals('foo:bar', $this->share->getFullId()); + } + + /** + * @expectedException \OCP\Share\Exceptions\IllegalIDChangeException + * @expectedExceptionMessage Not allowed to assign a new provider id to a share + */ + public function testSetProviderIdOnce() { + $this->share->setProviderId('foo'); + $this->share->setProviderId('bar'); + } +} diff --git a/tests/lib/systemtag/systemtagmanagertest.php b/tests/lib/systemtag/systemtagmanagertest.php index 64220205ade..1afb147f08a 100644 --- a/tests/lib/systemtag/systemtagmanagertest.php +++ b/tests/lib/systemtag/systemtagmanagertest.php @@ -124,7 +124,7 @@ class SystemTagManagerTest extends TestCase { null, [] ], - // filter by visibile only + // filter by visible only [ // none visible [ diff --git a/tests/lib/systemtag/systemtagobjectmappertest.php b/tests/lib/systemtag/systemtagobjectmappertest.php index 861eb240674..69cf7e8f816 100644 --- a/tests/lib/systemtag/systemtagobjectmappertest.php +++ b/tests/lib/systemtag/systemtagobjectmappertest.php @@ -119,7 +119,7 @@ class SystemTagObjectMapperTest extends TestCase { $query->delete(SystemTagManager::TAG_TABLE)->execute(); } - public function testGetTagsForObjects() { + public function testGetTagIdsForObjects() { $tagIdMapping = $this->tagMapper->getTagIdsForObjects( ['1', '2', '3', '4'], 'testtype' @@ -133,6 +133,15 @@ class SystemTagObjectMapperTest extends TestCase { ], $tagIdMapping); } + public function testGetTagIdsForNoObjects() { + $tagIdMapping = $this->tagMapper->getTagIdsForObjects( + [], + 'testtype' + ); + + $this->assertEquals([], $tagIdMapping); + } + public function testGetObjectsForTags() { $objectIds = $this->tagMapper->getObjectIdsForTags( [$this->tag1->getId(), $this->tag2->getId(), $this->tag3->getId()], diff --git a/tests/lib/testcase.php b/tests/lib/testcase.php index 008b96b3417..d7573337f87 100644 --- a/tests/lib/testcase.php +++ b/tests/lib/testcase.php @@ -22,10 +22,15 @@ namespace Test; +use DOMDocument; +use DOMNode; use OC\Command\QueueBus; use OC\Files\Filesystem; +use OC\Template\Base; +use OC_Defaults; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +use OCP\IL10N; use OCP\Security\ISecureRandom; abstract class TestCase extends \PHPUnit_Framework_TestCase { @@ -34,6 +39,8 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase { /** @var IDBConnection */ static protected $realDatabase = null; + + /** @var bool */ static private $wasDatabaseAllowed = false; /** @var array */ @@ -349,7 +356,7 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase { $user = null; } - \OC_Util::tearDownFS(); // command cant reply on the fs being setup + \OC_Util::tearDownFS(); // command can't reply on the fs being setup $this->commandBus->run(); \OC_Util::tearDownFS(); @@ -408,4 +415,65 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase { return false; } + + /** + * @param string $expectedHtml + * @param string $template + * @param array $vars + */ + protected function assertTemplate($expectedHtml, $template, $vars = []) { + + require_once __DIR__.'/../../lib/private/template/functions.php'; + + $requestToken = 12345; + $theme = new OC_Defaults(); + /** @var IL10N | \PHPUnit_Framework_MockObject_MockObject $l10n */ + $l10n = $this->getMockBuilder('\OCP\IL10N') + ->disableOriginalConstructor()->getMock(); + $l10n + ->expects($this->any()) + ->method('t') + ->will($this->returnCallback(function($text, $parameters = array()) { + return vsprintf($text, $parameters); + })); + + $t = new Base($template, $requestToken, $l10n, $theme); + $buf = $t->fetchPage($vars); + $this->assertHtmlStringEqualsHtmlString($expectedHtml, $buf); + } + + /** + * @param string $expectedHtml + * @param string $actualHtml + * @param string $message + */ + protected function assertHtmlStringEqualsHtmlString($expectedHtml, $actualHtml, $message = '') { + $expected = new DOMDocument(); + $expected->preserveWhiteSpace = false; + $expected->formatOutput = true; + $expected->loadHTML($expectedHtml); + + $actual = new DOMDocument(); + $actual->preserveWhiteSpace = false; + $actual->formatOutput = true; + $actual->loadHTML($actualHtml); + $this->removeWhitespaces($actual); + + $expectedHtml1 = $expected->saveHTML(); + $actualHtml1 = $actual->saveHTML(); + self::assertEquals($expectedHtml1, $actualHtml1, $message); + } + + + private function removeWhitespaces(DOMNode $domNode) { + foreach ($domNode->childNodes as $node) { + if($node->hasChildNodes()) { + $this->removeWhitespaces($node); + } else { + if ($node instanceof \DOMText && $node->isWhitespaceInElementContent() ) { + $domNode->removeChild($node); + } + } + } + } } diff --git a/tests/lib/traits/encryptiontrait.php b/tests/lib/traits/encryptiontrait.php index 7fad5d826ed..5e2ca4e561f 100644 --- a/tests/lib/traits/encryptiontrait.php +++ b/tests/lib/traits/encryptiontrait.php @@ -8,8 +8,8 @@ namespace Test\Traits; -use OC\Encryption\Util; -use OC\Files\View; +use OC\Encryption\EncryptionWrapper; +use OC\Memcache\ArrayCache; use OCA\Encryption\AppInfo\Application; use OCA\Encryption\KeyManager; use OCA\Encryption\Users\Setup; @@ -68,13 +68,13 @@ trait EncryptionTrait { } protected function postLogin() { - $util = new Util( - new View(), - \OC::$server->getUserManager(), - \OC::$server->getGroupManager(), - \OC::$server->getConfig() + $encryptionWrapper = new EncryptionWrapper( + new ArrayCache(), + \OC::$server->getEncryptionManager(), + \OC::$server->getLogger() ); - $this->registerStorageWrapper('oc_encryption', array($util, 'wrapStorage')); + + $this->registerStorageWrapper('oc_encryption', array($encryptionWrapper, 'wrapStorage')); } protected function setUpEncryptionTrait() { diff --git a/tests/lib/updater.php b/tests/lib/updater.php index 8ee77b9f81e..f97eb3ac139 100644 --- a/tests/lib/updater.php +++ b/tests/lib/updater.php @@ -29,8 +29,6 @@ use OC\IntegrityCheck\Checker; class UpdaterTest extends \Test\TestCase { /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ private $config; - /** @var HTTPHelper */ - private $httpHelper; /** @var ILogger */ private $logger; /** @var Updater */ @@ -43,9 +41,6 @@ class UpdaterTest extends \Test\TestCase { $this->config = $this->getMockBuilder('\\OCP\\IConfig') ->disableOriginalConstructor() ->getMock(); - $this->httpHelper = $this->getMockBuilder('\\OC\\HTTPHelper') - ->disableOriginalConstructor() - ->getMock(); $this->logger = $this->getMockBuilder('\\OCP\\ILogger') ->disableOriginalConstructor() ->getMock(); @@ -54,7 +49,6 @@ class UpdaterTest extends \Test\TestCase { ->getMock(); $this->updater = new Updater( - $this->httpHelper, $this->config, $this->checker, $this->logger @@ -184,237 +178,4 @@ class UpdaterTest extends \Test\TestCase { $this->assertSame(false, $this->invokePrivate($this->updater, 'skip3rdPartyAppsDisable')); } - public function testCheckInCache() { - $expectedResult = [ - 'version' => '8.0.4.2', - 'versionstring' => 'ownCloud 8.0.4', - 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', - 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', - ]; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(time())); - $this->config - ->expects($this->at(1)) - ->method('getAppValue') - ->with('core', 'lastupdateResult') - ->will($this->returnValue(json_encode($expectedResult))); - - $this->assertSame($expectedResult, $this->updater->check()); - } - - public function testCheckWithoutUpdateUrl() { - $expectedResult = [ - 'version' => '8.0.4.2', - 'versionstring' => 'ownCloud 8.0.4', - 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', - 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', - ]; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(3)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - $this->config - ->expects($this->at(5)) - ->method('setAppValue') - ->with('core', 'lastupdateResult', json_encode($expectedResult)); - - $updateXml = '<?xml version="1.0"?> -<owncloud> - <version>8.0.4.2</version> - <versionstring>ownCloud 8.0.4</versionstring> - <url>https://download.owncloud.org/community/owncloud-8.0.4.zip</url> - <web>http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html</web> -</owncloud>'; - $this->httpHelper - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame($expectedResult, $this->updater->check()); - } - - public function testCheckWithInvalidXml() { - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(3)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - $this->config - ->expects($this->at(5)) - ->method('setAppValue') - ->with('core', 'lastupdateResult', 'false'); - - $updateXml = 'Invalid XML Response!'; - $this->httpHelper - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame([], $this->updater->check()); - } - - public function testCheckWithUpdateUrl() { - $expectedResult = [ - 'version' => '8.0.4.2', - 'versionstring' => 'ownCloud 8.0.4', - 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', - 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', - ]; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(3)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - $this->config - ->expects($this->at(5)) - ->method('setAppValue') - ->with('core', 'lastupdateResult', json_encode($expectedResult)); - - $updateXml = '<?xml version="1.0"?> -<owncloud> - <version>8.0.4.2</version> - <versionstring>ownCloud 8.0.4</versionstring> - <url>https://download.owncloud.org/community/owncloud-8.0.4.zip</url> - <web>http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html</web> -</owncloud>'; - $this->httpHelper - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://myupdater.com/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame($expectedResult, $this->updater->check('https://myupdater.com/')); - } - - public function testCheckWithEmptyValidXmlResponse() { - $expectedResult = [ - 'version' => '', - 'versionstring' => '', - 'url' => '', - 'web' => '', - ]; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(3)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - - $updateXml = '<?xml version="1.0"?> -<owncloud> - <version></version> - <versionstring></versionstring> - <url></url> - <web></web> -</owncloud>'; - $this->httpHelper - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame($expectedResult, $this->updater->check()); - } - - public function testCheckWithEmptyInvalidXmlResponse() { - $expectedResult = []; - - $this->config - ->expects($this->at(0)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue(0)); - $this->config - ->expects($this->at(1)) - ->method('setAppValue') - ->with('core', 'lastupdatedat', $this->isType('integer')); - $this->config - ->expects($this->at(3)) - ->method('getAppValue') - ->with('core', 'installedat') - ->will($this->returnValue('installedat')); - $this->config - ->expects($this->at(4)) - ->method('getAppValue') - ->with('core', 'lastupdatedat') - ->will($this->returnValue('lastupdatedat')); - $this->config - ->expects($this->at(5)) - ->method('setAppValue') - ->with('core', 'lastupdateResult', json_encode($expectedResult)); - - $updateXml = ''; - $this->httpHelper - ->expects($this->once()) - ->method('getUrlContent') - ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) - ->will($this->returnValue($updateXml)); - - $this->assertSame($expectedResult, $this->updater->check()); - } } diff --git a/tests/lib/updater/versioncheck.php b/tests/lib/updater/versioncheck.php new file mode 100644 index 00000000000..4613581a75f --- /dev/null +++ b/tests/lib/updater/versioncheck.php @@ -0,0 +1,289 @@ +<?php +/** + * @author Lukas Reschke <lukas@owncloud.com> + * @author Victor Dubiniuk <dubiniuk@owncloud.com> + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace OC; + +use OC\Updater\VersionCheck; +use OCP\IConfig; +use OCP\Util; + +class VersionCheckTest extends \Test\TestCase { + /** @var IConfig| \PHPUnit_Framework_MockObject_MockObject */ + private $config; + /** @var VersionCheck | \PHPUnit_Framework_MockObject_MockObject*/ + private $updater; + + public function setUp() { + parent::setUp(); + $this->config = $this->getMockBuilder('\OCP\IConfig') + ->disableOriginalConstructor() + ->getMock(); + $clientService = $this->getMockBuilder('\OCP\Http\Client\IClientService') + ->disableOriginalConstructor() + ->getMock(); + + $this->updater = $this->getMock('\OC\Updater\VersionCheck', + ['getUrlContent'], [$clientService, $this->config]); + } + + /** + * @param string $baseUrl + * @return string + */ + private function buildUpdateUrl($baseUrl) { + return $baseUrl . '?version='.implode('x', Util::getVersion()).'xinstalledatxlastupdatedatx'.\OC_Util::getChannel().'x'.\OC_Util::getEditionString().'x'; + } + + public function testCheckInCache() { + $expectedResult = [ + 'version' => '8.0.4.2', + 'versionstring' => 'ownCloud 8.0.4', + 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', + 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', + ]; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(time())); + $this->config + ->expects($this->at(1)) + ->method('getAppValue') + ->with('core', 'lastupdateResult') + ->will($this->returnValue(json_encode($expectedResult))); + + $this->assertSame($expectedResult, $this->updater->check()); + } + + public function testCheckWithoutUpdateUrl() { + $expectedResult = [ + 'version' => '8.0.4.2', + 'versionstring' => 'ownCloud 8.0.4', + 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', + 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', + ]; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(3)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + $this->config + ->expects($this->at(5)) + ->method('setAppValue') + ->with('core', 'lastupdateResult', json_encode($expectedResult)); + + $updateXml = '<?xml version="1.0"?> +<owncloud> + <version>8.0.4.2</version> + <versionstring>ownCloud 8.0.4</versionstring> + <url>https://download.owncloud.org/community/owncloud-8.0.4.zip</url> + <web>http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html</web> +</owncloud>'; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame($expectedResult, $this->updater->check()); + } + + public function testCheckWithInvalidXml() { + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(3)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + $this->config + ->expects($this->at(5)) + ->method('setAppValue') + ->with('core', 'lastupdateResult', 'false'); + + $updateXml = 'Invalid XML Response!'; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame([], $this->updater->check()); + } + + public function testCheckWithUpdateUrl() { + $expectedResult = [ + 'version' => '8.0.4.2', + 'versionstring' => 'ownCloud 8.0.4', + 'url' => 'https://download.owncloud.org/community/owncloud-8.0.4.zip', + 'web' => 'http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html', + ]; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(3)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + $this->config + ->expects($this->at(5)) + ->method('setAppValue') + ->with('core', 'lastupdateResult', json_encode($expectedResult)); + + $updateXml = '<?xml version="1.0"?> +<owncloud> + <version>8.0.4.2</version> + <versionstring>ownCloud 8.0.4</versionstring> + <url>https://download.owncloud.org/community/owncloud-8.0.4.zip</url> + <web>http://doc.owncloud.org/server/8.0/admin_manual/maintenance/upgrade.html</web> +</owncloud>'; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://myupdater.com/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame($expectedResult, $this->updater->check('https://myupdater.com/')); + } + + public function testCheckWithEmptyValidXmlResponse() { + $expectedResult = [ + 'version' => '', + 'versionstring' => '', + 'url' => '', + 'web' => '', + ]; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(3)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + + $updateXml = '<?xml version="1.0"?> +<owncloud> + <version></version> + <versionstring></versionstring> + <url></url> + <web></web> +</owncloud>'; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame($expectedResult, $this->updater->check()); + } + + public function testCheckWithEmptyInvalidXmlResponse() { + $expectedResult = []; + + $this->config + ->expects($this->at(0)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue(0)); + $this->config + ->expects($this->at(1)) + ->method('setAppValue') + ->with('core', 'lastupdatedat', $this->isType('integer')); + $this->config + ->expects($this->at(3)) + ->method('getAppValue') + ->with('core', 'installedat') + ->will($this->returnValue('installedat')); + $this->config + ->expects($this->at(4)) + ->method('getAppValue') + ->with('core', 'lastupdatedat') + ->will($this->returnValue('lastupdatedat')); + $this->config + ->expects($this->at(5)) + ->method('setAppValue') + ->with('core', 'lastupdateResult', json_encode($expectedResult)); + + $updateXml = ''; + $this->updater + ->expects($this->once()) + ->method('getUrlContent') + ->with($this->buildUpdateUrl('https://updates.owncloud.com/server/')) + ->will($this->returnValue($updateXml)); + + $this->assertSame($expectedResult, $this->updater->check()); + } +} diff --git a/tests/lib/util/group/dummy.php b/tests/lib/util/group/dummy.php new file mode 100644 index 00000000000..e72be827d8a --- /dev/null +++ b/tests/lib/util/group/dummy.php @@ -0,0 +1,217 @@ +<?php +/** + * @author Arthur Schiwon <blizzz@owncloud.com> + * @author Felix Moeller <mail@felixmoeller.de> + * @author Lukas Reschke <lukas@owncloud.com> + * @author Michael Gapczynski <GapczynskiM@gmail.com> + * @author Morris Jobke <hey@morrisjobke.de> + * @author Robin Appelman <icewind@owncloud.com> + * @author Robin McCorkell <robin@mccorkell.me.uk> + * @author Roeland Jago Douma <rullzer@owncloud.com> + * @author Thomas Müller <thomas.mueller@tmit.eu> + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace Test\Util\Group; + +use OC_Group_Backend; + +/** + * dummy group backend, does not keep state, only for testing use + */ +class Dummy extends OC_Group_Backend { + private $groups=array(); + /** + * Try to create a new group + * @param string $gid The name of the group to create + * @return bool + * + * Tries to create a new group. If the group name already exists, false will + * be returned. + */ + public function createGroup($gid) { + if(!isset($this->groups[$gid])) { + $this->groups[$gid]=array(); + return true; + }else{ + return false; + } + } + + /** + * delete a group + * @param string $gid gid of the group to delete + * @return bool + * + * Deletes a group and removes it from the group_user-table + */ + public function deleteGroup($gid) { + if(isset($this->groups[$gid])) { + unset($this->groups[$gid]); + return true; + }else{ + return false; + } + } + + /** + * is user in group? + * @param string $uid uid of the user + * @param string $gid gid of the group + * @return bool + * + * Checks whether the user is member of a group or not. + */ + public function inGroup($uid, $gid) { + if(isset($this->groups[$gid])) { + return (array_search($uid, $this->groups[$gid])!==false); + }else{ + return false; + } + } + + /** + * Add a user to a group + * @param string $uid Name of the user to add to group + * @param string $gid Name of the group in which add the user + * @return bool + * + * Adds a user to a group. + */ + public function addToGroup($uid, $gid) { + if(isset($this->groups[$gid])) { + if(array_search($uid, $this->groups[$gid])===false) { + $this->groups[$gid][]=$uid; + return true; + }else{ + return false; + } + }else{ + return false; + } + } + + /** + * Removes a user from a group + * @param string $uid Name of the user to remove from group + * @param string $gid Name of the group from which remove the user + * @return bool + * + * removes the user from a group. + */ + public function removeFromGroup($uid, $gid) { + if(isset($this->groups[$gid])) { + if(($index=array_search($uid, $this->groups[$gid]))!==false) { + unset($this->groups[$gid][$index]); + return true; + }else{ + return false; + } + }else{ + return false; + } + } + + /** + * Get all groups a user belongs to + * @param string $uid Name of the user + * @return array an array of group names + * + * This function fetches all groups a user belongs to. It does not check + * if the user exists at all. + */ + public function getUserGroups($uid) { + $groups=array(); + $allGroups=array_keys($this->groups); + foreach($allGroups as $group) { + if($this->inGroup($uid, $group)) { + $groups[]=$group; + } + } + return $groups; + } + + /** + * Get a list of all groups + * @param string $search + * @param int $limit + * @param int $offset + * @return array an array of group names + */ + public function getGroups($search = '', $limit = -1, $offset = 0) { + if(empty($search)) { + return array_keys($this->groups); + } + $result = array(); + foreach(array_keys($this->groups) as $group) { + if(stripos($group, $search) !== false) { + $result[] = $group; + } + } + return $result; + } + + /** + * Get a list of all users in a group + * @param string $gid + * @param string $search + * @param int $limit + * @param int $offset + * @return array an array of user IDs + */ + public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) { + if(isset($this->groups[$gid])) { + if(empty($search)) { + return $this->groups[$gid]; + } + $result = array(); + foreach($this->groups[$gid] as $user) { + if(stripos($user, $search) !== false) { + $result[] = $user; + } + } + return $result; + }else{ + return array(); + } + } + + /** + * get the number of all users in a group + * @param string $gid + * @param string $search + * @param int $limit + * @param int $offset + * @return int + */ + public function countUsersInGroup($gid, $search = '', $limit = -1, $offset = 0) { + if(isset($this->groups[$gid])) { + if(empty($search)) { + return count($this->groups[$gid]); + } + $count = 0; + foreach($this->groups[$gid] as $user) { + if(stripos($user, $search) !== false) { + $count++; + } + } + return $count; + } + } + +} diff --git a/tests/phpunit-autotest-external.xml b/tests/phpunit-autotest-external.xml index 31d2e395a01..1b48c4dc11e 100644 --- a/tests/phpunit-autotest-external.xml +++ b/tests/phpunit-autotest-external.xml @@ -8,7 +8,7 @@ <testsuite name='ownCloud files external'> <directory suffix=".php">../apps/files_external/tests</directory> <!-- exclude backends as they are called separately --> - <exclude>../apps/files_external/tests/backends/</exclude> + <exclude>../apps/files_external/tests/storage/</exclude> </testsuite> <!-- filters for code coverage --> <filter> |