diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 6a81b0f228..4612614995 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -34,9 +34,6 @@ wsmaster/che-core-api-workspace/** @skabashnyuk @mshaposhnik @metlos @nickboldt deploy/** @tolusha @nickboldt deploy/openshift/templates/monitoring/** @skabashnyuk @metlos @nickboldt -# selenium tests -tests/legacy-e2e/** @musienko-maxim @dmytro-ndp @Ohrimenko1988 @rhopp @nickboldt - # e2e tests tests/e2e/** @musienko-maxim @Ohrimenko1988 @rhopp @nickboldt @Katka92 @ScrewTSW diff --git a/tests/.infra/centos-ci/cico_pr_test.sh b/tests/.infra/centos-ci/cico_pr_test.sh deleted file mode 100755 index 720fe3ffe1..0000000000 --- a/tests/.infra/centos-ci/cico_pr_test.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env bash -# Copyright (c) 2020 Red Hat, Inc. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html - -set -ex - -source tests/.infra/centos-ci/functional_tests_utils.sh - -eval "$(./env-toolkit load -f jenkins-env.json -r ^ghprbPullId)" - -export PULL_REQUEST_ID="${ghprbPullId}" -export TAG=PR-${PULL_REQUEST_ID} - -function prepareCustomResourcePatchFile() { - cat > /tmp/custom-resource-patch.yaml <> che_local_conf_dir/selenium.properties - echo "github.password=CheMain2017" >> che_local_conf_dir/selenium.properties - echo "github.auxiliary.username=iedexmain1" >> che_local_conf_dir/selenium.properties - echo "github.auxiliary.password=CodenvyMain15" >> che_local_conf_dir/selenium.properties -} - function installDockerCompose() { echo "Install docker compose" sudo curl -L "https://github.com/docker/compose/releases/download/1.25.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose } -function seleniumTestsSetup() { - echo "======== Start selenium tests ========" - cd /root/payload - - export CHE_INFRASTRUCTURE=openshift - export CHE_OPENSHIFT_PROJECT=eclipse-che - - defineCheRoute - - mvn clean install -pl :che-selenium-test -am -DskipTests=true -U - configureGithubTestUser -} - -function saveSeleniumTestResult() { - mkdir -p /root/payload/report - mkdir -p /root/payload/report/site - cp -r /root/payload/tests/legacy-e2e/che-selenium-test/target/site report -} - -function createIndentityProvider() { - CHE_MULTI_USER_GITHUB_CLIENTID_OCP=04cbc0f8172109322223 - CHE_MULTI_USER_GITHUB_SECRET_OCP=a0a9b8602bb0916d322223e71b7ed92036563b7a - keycloakPodName=$(oc get pod --namespace=eclipse-che | grep keycloak | awk '{print $1}') - /tmp/oc exec $keycloakPodName --namespace=eclipse-che -- /opt/jboss/keycloak/bin/kcadm.sh create identity-provider/instances -r che -s alias=github -s providerId=github -s enabled=true -s storeToken=true -s addReadTokenRoleOnCreate=true -s 'config.useJwksUrl="true"' -s config.clientId=$CHE_MULTI_USER_GITHUB_CLIENTID_OCP -s config.clientSecret=$CHE_MULTI_USER_GITHUB_SECRET_OCP -s 'config.defaultScope="repo,user,write:public_key"' --no-config --server http://localhost:8080/auth --user admin --password admin --realm master -} - function runDevfileTestSuite() { defineCheRoute ### Create directory for report diff --git a/tests/.infra/centos-ci/nightly/cico-multiuser-all-tests.sh b/tests/.infra/centos-ci/nightly/cico-multiuser-all-tests.sh deleted file mode 100755 index 8593b43e25..0000000000 --- a/tests/.infra/centos-ci/nightly/cico-multiuser-all-tests.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env bash -# Copyright (c) 2018 Red Hat, Inc. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -set -e - -echo "========Starting nigtly test job $(date)========" - -source tests/.infra/centos-ci/functional_tests_utils.sh -source .ci/cico_common.sh - -function prepareCustomResourcePatchFile() { - cat > /tmp/custom-resource-patch.yaml < /tmp/custom-resource-patch.yaml < /tmp/custom-resource-patch.yaml < /tmp/custom-resource-patch.yaml < /tmp/custom-resource-patch.yaml <(CLASSES.CheApiRequestHandler).to(CheApiR e2eContainer.bind(CLASSES.CheGitApi).to(CheGitApi); e2eContainer.bind(CLASSES.GitHubUtil).to(GitHubUtil); e2eContainer.bind(CLASSES.OpenshiftPlugin).to(OpenshiftPlugin); -e2eContainer.bind(CLASSES.GetStarted).to(GetStarted); +e2eContainer.bind(CLASSES.CreateWorkspace).to(CreateWorkspace); e2eContainer.bind(CLASSES.OpenDialogWidget).to(OpenDialogWidget); e2eContainer.bind(CLASSES.UpdateAccountInformationPage).to(UpdateAccountInformationPage); e2eContainer.bind(CLASSES.KubernetesPlugin).to(KubernetesPlugin); diff --git a/tests/e2e/inversify.types.ts b/tests/e2e/inversify.types.ts index b991b502c7..3955834168 100644 --- a/tests/e2e/inversify.types.ts +++ b/tests/e2e/inversify.types.ts @@ -51,7 +51,7 @@ const CLASSES = { NotificationCenter: 'NotificationCenter', PreferencesHandler: 'PreferencesHandler', CheApiRequestHandler: 'CheApiRequestHandler', - GetStarted: 'GetStarted', + CreateWorkspace: 'CreateWorkspace', OpenDialogWidget: 'OpenDialogWidget', UpdateAccountInformationPage: 'UpdateAccountInformationPage', KubernetesPlugin: 'KubernetesPlugin', diff --git a/tests/e2e/pageobjects/dashboard/GetStarted.ts b/tests/e2e/pageobjects/dashboard/CreateWorkspace.ts similarity index 82% rename from tests/e2e/pageobjects/dashboard/GetStarted.ts rename to tests/e2e/pageobjects/dashboard/CreateWorkspace.ts index d2f848aa43..e39eb1674f 100644 --- a/tests/e2e/pageobjects/dashboard/GetStarted.ts +++ b/tests/e2e/pageobjects/dashboard/CreateWorkspace.ts @@ -16,11 +16,11 @@ import { Logger } from '../../utils/Logger'; import { TimeoutConstants } from '../../TimeoutConstants'; @injectable() -export class GetStarted { +export class CreateWorkspace { constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } async waitTitleContains(expectedText: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT) { - Logger.debug(`GetStarted.waitTitleContains text: "${expectedText}"`); + Logger.debug(`CreateWorkspace.waitTitleContains text: "${expectedText}"`); const pageTitleLocator: By = By.xpath(`//h1[contains(text(), '${expectedText}')]`); @@ -28,13 +28,13 @@ export class GetStarted { } async waitPage(timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT) { - Logger.debug('GetStarted.waitPage'); + Logger.debug('CreateWorkspace.waitPage'); await this.waitTitleContains('Getting Started', timeout); } async waitSample(sampleName: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT) { - Logger.debug(`GetStarted.waitSample sampleName: "${sampleName}"`); + Logger.debug(`CreateWorkspace.waitSample sampleName: "${sampleName}"`); const sampleLocator: By = this.getSampleLocator(sampleName); @@ -42,7 +42,7 @@ export class GetStarted { } async clickOnSample(sampleName: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT) { - Logger.debug(`GetStarted.clickOnSample sampleName: "${sampleName}"`); + Logger.debug(`CreateWorkspace.clickOnSample sampleName: "${sampleName}"`); const sampleLocator: By = this.getSampleLocator(sampleName); @@ -50,7 +50,7 @@ export class GetStarted { } private getSampleLocator(sampleName: string): By { - Logger.trace(`GetStarted.getSampleLocator sampleName: ${sampleName}`); + Logger.trace(`CreateWorkspace.getSampleLocator sampleName: ${sampleName}`); return By.xpath(`//article[contains(@class, 'sample-card')]//div[text()='${sampleName}']`); } diff --git a/tests/e2e/pageobjects/dashboard/Dashboard.ts b/tests/e2e/pageobjects/dashboard/Dashboard.ts index 4fec4a8be3..705ba11e58 100644 --- a/tests/e2e/pageobjects/dashboard/Dashboard.ts +++ b/tests/e2e/pageobjects/dashboard/Dashboard.ts @@ -19,8 +19,7 @@ import { Logger } from '../../utils/Logger'; @injectable() export class Dashboard { - private static readonly WORKSPACES_BUTTON_XPATH: string = `//div[@id='page-sidebar']//a[text()='Workspaces']`; - private static readonly GET_STARTED_BUTTON_XPATH: string = `//div[@id='page-sidebar']//a[text()='Get Started']`; + private static readonly WORKSPACES_BUTTON_XPATH: string = `//div[@id='page-sidebar']//a[contains(text(), 'Workspaces (')]`; private static readonly CREATE_WORKSPACE_BUTTON_XPATH: string = `//div[@id='page-sidebar']//a[text()='Create Workspace']`; private static readonly LOADER_PAGE_CSS: string = '.main-page-loader'; @@ -79,7 +78,6 @@ export class Dashboard { Logger.debug('Dashboard.waitPage'); await this.driverHelper.waitVisibility(By.xpath(Dashboard.WORKSPACES_BUTTON_XPATH), timeout); - await this.driverHelper.waitVisibility(By.xpath(Dashboard.GET_STARTED_BUTTON_XPATH), timeout); await this.driverHelper.waitVisibility(By.xpath(Dashboard.CREATE_WORKSPACE_BUTTON_XPATH), timeout); } @@ -95,12 +93,6 @@ export class Dashboard { await this.driverHelper.waitAndClick(By.xpath(Dashboard.CREATE_WORKSPACE_BUTTON_XPATH), timeout); } - async clickGetStartedButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT) { - Logger.debug('Dashboard.clickGetStartedButton'); - - await this.driverHelper.waitAndClick(By.xpath(Dashboard.GET_STARTED_BUTTON_XPATH), timeout); - } - async waitLoader(timeout: number = TimeoutConstants.TS_WAIT_LOADER_PRESENCE_TIMEOUT) { Logger.debug('Dashboard.waitLoader'); diff --git a/tests/e2e/tests/devfiles/CSlashCPlusPlus.spec.ts b/tests/e2e/tests/devfiles/CSlashCPlusPlus.spec.ts index 5f0ba6c417..0511217f73 100644 --- a/tests/e2e/tests/devfiles/CSlashCPlusPlus.spec.ts +++ b/tests/e2e/tests/devfiles/CSlashCPlusPlus.spec.ts @@ -9,7 +9,7 @@ **********************************************************************/ import 'reflect-metadata'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; import * as codeExecutionTests from '../../testsLibrary/CodeExecutionTests'; import { e2eContainer } from '../../inversify.config'; diff --git a/tests/e2e/tests/devfiles/DevfileSmoke.spec.ts b/tests/e2e/tests/devfiles/DevfileSmoke.spec.ts index 80158437be..206ee09ff7 100644 --- a/tests/e2e/tests/devfiles/DevfileSmoke.spec.ts +++ b/tests/e2e/tests/devfiles/DevfileSmoke.spec.ts @@ -10,7 +10,7 @@ import 'reflect-metadata'; import { WorkspaceNameHandler} from '../..'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; const workspaceSampleName: string = 'console-java-simple'; const workspaceRootFolderName: string = 'src'; diff --git a/tests/e2e/tests/devfiles/DotNetCore.spec.ts b/tests/e2e/tests/devfiles/DotNetCore.spec.ts index de4c6c0da5..a9e1953829 100644 --- a/tests/e2e/tests/devfiles/DotNetCore.spec.ts +++ b/tests/e2e/tests/devfiles/DotNetCore.spec.ts @@ -12,7 +12,7 @@ import { WorkspaceNameHandler, Editor, CLASSES } from '../..'; import { e2eContainer } from '../../inversify.config'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as codeExecutionTests from '../../testsLibrary/CodeExecutionTests'; const editor: Editor = e2eContainer.get(CLASSES.Editor); diff --git a/tests/e2e/tests/devfiles/Go.spec.ts b/tests/e2e/tests/devfiles/Go.spec.ts index 44ef3e7288..dfa971712a 100644 --- a/tests/e2e/tests/devfiles/Go.spec.ts +++ b/tests/e2e/tests/devfiles/Go.spec.ts @@ -13,7 +13,7 @@ import 'reflect-metadata'; import * as codeExecutionHelper from '../../testsLibrary/CodeExecutionTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; import * as projectManager from '../../testsLibrary/ProjectAndFileTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import { Logger } from '../../utils/Logger'; import { PreferencesHandler } from '../../utils/PreferencesHandler'; diff --git a/tests/e2e/tests/devfiles/JavaMaven.spec.ts b/tests/e2e/tests/devfiles/JavaMaven.spec.ts index 74120cdd29..7f976e7c9e 100644 --- a/tests/e2e/tests/devfiles/JavaMaven.spec.ts +++ b/tests/e2e/tests/devfiles/JavaMaven.spec.ts @@ -11,7 +11,7 @@ import 'reflect-metadata'; import { WorkspaceNameHandler} from '../..'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as codeExecutionTests from '../../testsLibrary/CodeExecutionTests'; const workspaceSampleName: string = 'console-java-simple'; diff --git a/tests/e2e/tests/devfiles/JavaSpringBoot.spec.ts b/tests/e2e/tests/devfiles/JavaSpringBoot.spec.ts index 805313bbda..0b5535fbb5 100644 --- a/tests/e2e/tests/devfiles/JavaSpringBoot.spec.ts +++ b/tests/e2e/tests/devfiles/JavaSpringBoot.spec.ts @@ -11,7 +11,7 @@ import 'reflect-metadata'; import { WorkspaceNameHandler } from '../..'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as codeExecutionTests from '../../testsLibrary/CodeExecutionTests'; const stack: string = 'Java Spring Boot'; diff --git a/tests/e2e/tests/devfiles/JavaVertx.spec.ts b/tests/e2e/tests/devfiles/JavaVertx.spec.ts index 8cebc7013c..0d7d7900e8 100644 --- a/tests/e2e/tests/devfiles/JavaVertx.spec.ts +++ b/tests/e2e/tests/devfiles/JavaVertx.spec.ts @@ -9,7 +9,7 @@ **********************************************************************/ import 'reflect-metadata'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; import * as codeExecutionTests from '../../testsLibrary/CodeExecutionTests'; import { WorkspaceNameHandler } from '../..'; diff --git a/tests/e2e/tests/devfiles/NodeJS.spec.ts b/tests/e2e/tests/devfiles/NodeJS.spec.ts index b9e4ba44cc..851066a2f8 100644 --- a/tests/e2e/tests/devfiles/NodeJS.spec.ts +++ b/tests/e2e/tests/devfiles/NodeJS.spec.ts @@ -12,7 +12,7 @@ import 'reflect-metadata'; import * as codeExecutionHelper from '../../testsLibrary/CodeExecutionTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; import * as projectManager from '../../testsLibrary/ProjectAndFileTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; const workspaceStack: string = 'NodeJS Express Web Application'; const workspaceSampleName: string = 'nodejs-web-app'; diff --git a/tests/e2e/tests/devfiles/PHPSimple.spec.ts b/tests/e2e/tests/devfiles/PHPSimple.spec.ts index d9a48764d6..f450089b0f 100644 --- a/tests/e2e/tests/devfiles/PHPSimple.spec.ts +++ b/tests/e2e/tests/devfiles/PHPSimple.spec.ts @@ -9,7 +9,7 @@ **********************************************************************/ import 'reflect-metadata'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; import * as codeExecutionTests from '../../testsLibrary/CodeExecutionTests'; import { e2eContainer } from '../../inversify.config'; diff --git a/tests/e2e/tests/devfiles/Python.spec.ts b/tests/e2e/tests/devfiles/Python.spec.ts index e1f9ed4ced..5e0d0fd185 100644 --- a/tests/e2e/tests/devfiles/Python.spec.ts +++ b/tests/e2e/tests/devfiles/Python.spec.ts @@ -13,7 +13,7 @@ import * as codeExecutionHelper from '../../testsLibrary/CodeExecutionTests'; import * as projectManager from '../../testsLibrary/ProjectAndFileTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; const workspaceStack: string = 'Python'; const workspaceSampleName: string = 'python-hello-world'; diff --git a/tests/e2e/tests/devfiles/PythonDjango.spec.ts b/tests/e2e/tests/devfiles/PythonDjango.spec.ts index 7cff39e831..8b7e64853e 100644 --- a/tests/e2e/tests/devfiles/PythonDjango.spec.ts +++ b/tests/e2e/tests/devfiles/PythonDjango.spec.ts @@ -10,7 +10,7 @@ import { WorkspaceNameHandler } from '../..'; import 'reflect-metadata'; import * as codeExecutionHelper from '../../testsLibrary/CodeExecutionTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as projectManager from '../../testsLibrary/ProjectAndFileTests'; const workspaceStack: string = 'Python Django'; diff --git a/tests/e2e/tests/devfiles/Quarkus.spec.ts b/tests/e2e/tests/devfiles/Quarkus.spec.ts index b519223dc2..4379d7d7cc 100644 --- a/tests/e2e/tests/devfiles/Quarkus.spec.ts +++ b/tests/e2e/tests/devfiles/Quarkus.spec.ts @@ -11,7 +11,7 @@ import { WorkspaceNameHandler } from '../..'; import 'reflect-metadata'; import * as codeExecutionHelper from '../../testsLibrary/CodeExecutionTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as projectManager from '../../testsLibrary/ProjectAndFileTests'; const workspaceStack: string = 'Quarkus CLI'; diff --git a/tests/e2e/tests/devfiles/Scala.spec.ts b/tests/e2e/tests/devfiles/Scala.spec.ts index 9cf09ff11c..56020ecee8 100644 --- a/tests/e2e/tests/devfiles/Scala.spec.ts +++ b/tests/e2e/tests/devfiles/Scala.spec.ts @@ -9,7 +9,7 @@ **********************************************************************/ import 'reflect-metadata'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as commonLsTests from '../../testsLibrary/LsTests'; import * as codeExecutionTests from '../../testsLibrary/CodeExecutionTests'; import { WorkspaceNameHandler } from '../..'; diff --git a/tests/e2e/tests/e2e/DirectUrlFactoryWithKeepDirectoryTest.spec.ts b/tests/e2e/tests/e2e/DirectUrlFactoryWithKeepDirectoryTest.spec.ts index 605659cd47..f5cde12da1 100644 --- a/tests/e2e/tests/e2e/DirectUrlFactoryWithKeepDirectoryTest.spec.ts +++ b/tests/e2e/tests/e2e/DirectUrlFactoryWithKeepDirectoryTest.spec.ts @@ -13,7 +13,7 @@ import { CLASSES } from '../../inversify.types'; import { TestConstants } from '../../TestConstants'; import { DriverHelper } from '../../utils/DriverHelper'; import { WorkspaceNameHandler } from '../..'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; const driverHelper: DriverHelper = e2eContainer.get(CLASSES.DriverHelper); diff --git a/tests/e2e/tests/e2e/DirectUrlFactoryWithRootFolderTest.spec.ts b/tests/e2e/tests/e2e/DirectUrlFactoryWithRootFolderTest.spec.ts index 43c357ae59..845bb9ee70 100644 --- a/tests/e2e/tests/e2e/DirectUrlFactoryWithRootFolderTest.spec.ts +++ b/tests/e2e/tests/e2e/DirectUrlFactoryWithRootFolderTest.spec.ts @@ -13,7 +13,7 @@ import { CLASSES } from '../../inversify.types'; import { TestConstants } from '../../TestConstants'; import { DriverHelper } from '../../utils/DriverHelper'; import { WorkspaceNameHandler } from '../..'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; const driverHelper: DriverHelper = e2eContainer.get(CLASSES.DriverHelper); diff --git a/tests/e2e/tests/e2e/DirectUrlFactoryWithSpecificBranchTest.spec.ts b/tests/e2e/tests/e2e/DirectUrlFactoryWithSpecificBranchTest.spec.ts index 874a507c76..68c9fe5f84 100644 --- a/tests/e2e/tests/e2e/DirectUrlFactoryWithSpecificBranchTest.spec.ts +++ b/tests/e2e/tests/e2e/DirectUrlFactoryWithSpecificBranchTest.spec.ts @@ -13,7 +13,7 @@ import { CLASSES } from '../../inversify.types'; import { TestConstants } from '../../TestConstants'; import { DriverHelper } from '../../utils/DriverHelper'; import { WorkspaceNameHandler } from '../..'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; const driverHelper: DriverHelper = e2eContainer.get(CLASSES.DriverHelper); diff --git a/tests/e2e/tests/e2e/FactoryUrl.spec.ts b/tests/e2e/tests/e2e/FactoryUrl.spec.ts index eeef08d34a..c4b20bcb5f 100644 --- a/tests/e2e/tests/e2e/FactoryUrl.spec.ts +++ b/tests/e2e/tests/e2e/FactoryUrl.spec.ts @@ -13,7 +13,7 @@ import { CLASSES } from '../../inversify.types'; import { TestConstants } from '../../TestConstants'; import { DriverHelper } from '../../utils/DriverHelper'; import { WorkspaceNameHandler } from '../..'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import * as projectAndFileTests from '../../testsLibrary/ProjectAndFileTests'; const driverHelper: DriverHelper = e2eContainer.get(CLASSES.DriverHelper); diff --git a/tests/e2e/tests/plugins/JavaPlugin.spec.ts b/tests/e2e/tests/plugins/JavaPlugin.spec.ts index 1490e592fa..aa83ee5c3d 100644 --- a/tests/e2e/tests/plugins/JavaPlugin.spec.ts +++ b/tests/e2e/tests/plugins/JavaPlugin.spec.ts @@ -9,7 +9,7 @@ **********************************************************************/ import { WorkspaceNameHandler } from '../..'; import 'reflect-metadata'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import { DriverHelper } from '../../utils/DriverHelper'; import { e2eContainer } from '../../inversify.config'; import { CLASSES } from '../../inversify.types'; diff --git a/tests/e2e/tests/plugins/TypescriptPlugin.spec.ts b/tests/e2e/tests/plugins/TypescriptPlugin.spec.ts index 1e97baf42b..2ff8e9753a 100644 --- a/tests/e2e/tests/plugins/TypescriptPlugin.spec.ts +++ b/tests/e2e/tests/plugins/TypescriptPlugin.spec.ts @@ -9,7 +9,7 @@ **********************************************************************/ import { WorkspaceNameHandler } from '../..'; import 'reflect-metadata'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import { DriverHelper } from '../../utils/DriverHelper'; import { e2eContainer } from '../../inversify.config'; import { CLASSES } from '../../inversify.types'; diff --git a/tests/e2e/tests/plugins/VscodeKubernetesPlugin.spec.ts b/tests/e2e/tests/plugins/VscodeKubernetesPlugin.spec.ts index 7e807223d7..bc14df73d6 100644 --- a/tests/e2e/tests/plugins/VscodeKubernetesPlugin.spec.ts +++ b/tests/e2e/tests/plugins/VscodeKubernetesPlugin.spec.ts @@ -9,7 +9,7 @@ **********************************************************************/ import { WorkspaceNameHandler } from '../..'; import 'reflect-metadata'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import { DriverHelper } from '../../utils/DriverHelper'; import { e2eContainer } from '../../inversify.config'; import { CLASSES } from '../../inversify.types'; diff --git a/tests/e2e/tests/plugins/VscodeShellcheckPlugin.spec.ts b/tests/e2e/tests/plugins/VscodeShellcheckPlugin.spec.ts index 7656ae0ffe..c0d272972b 100644 --- a/tests/e2e/tests/plugins/VscodeShellcheckPlugin.spec.ts +++ b/tests/e2e/tests/plugins/VscodeShellcheckPlugin.spec.ts @@ -9,7 +9,7 @@ **********************************************************************/ import { WorkspaceNameHandler } from '../..'; import 'reflect-metadata'; -import * as workspaceHandling from '../../testsLibrary/WorksapceHandlingTests'; +import * as workspaceHandling from '../../testsLibrary/WorkspaceHandlingTests'; import { DriverHelper } from '../../utils/DriverHelper'; import { e2eContainer } from '../../inversify.config'; import { CLASSES } from '../../inversify.types'; diff --git a/tests/e2e/testsLibrary/WorksapceHandlingTests.ts b/tests/e2e/testsLibrary/WorkspaceHandlingTests.ts similarity index 80% rename from tests/e2e/testsLibrary/WorksapceHandlingTests.ts rename to tests/e2e/testsLibrary/WorkspaceHandlingTests.ts index 1f4e28f53b..65cfc23cef 100644 --- a/tests/e2e/testsLibrary/WorksapceHandlingTests.ts +++ b/tests/e2e/testsLibrary/WorkspaceHandlingTests.ts @@ -10,22 +10,22 @@ import { CLASSES, Dashboard } from '..'; import { e2eContainer } from '../inversify.config'; -import { GetStarted } from '../pageobjects/dashboard/GetStarted'; +import { CreateWorkspace as CreateWorkspace } from '../pageobjects/dashboard/CreateWorkspace'; import { Logger } from '../utils/Logger'; const dashboard: Dashboard = e2eContainer.get(CLASSES.Dashboard); -const getStarted: GetStarted = e2eContainer.get(CLASSES.GetStarted); +const createWorkspace: CreateWorkspace = e2eContainer.get(CLASSES.CreateWorkspace); export function createAndOpenWorkspace(stack: string) { test(`Open 'New Workspace' page`, async () => { Logger.trace(`WorkspaceHandlingTests.createAndOpenWorkspace wait for dashboard`); await dashboard.waitPage(); - Logger.trace(`WorkspaceHandlingTests.createAndOpenWorkspace click get started button`); - await dashboard.clickGetStartedButton(); + Logger.trace(`WorkspaceHandlingTests.createAndOpenWorkspace click Create workspace button`); + await dashboard.clickCreateWorkspaceButton(); Logger.trace(`WorkspaceHandlingTests.createAndOpenWorkspace wait for getting started page`); - await getStarted.waitPage(); + await createWorkspace.waitPage(); Logger.trace(`WorkspaceHandlingTests.createAndOpenWorkspace click on sample ${stack}`); - await getStarted.clickOnSample(stack); + await createWorkspace.clickOnSample(stack); }); } diff --git a/tests/legacy-e2e/che-selenium-core/bin/webdriver.sh b/tests/legacy-e2e/che-selenium-core/bin/webdriver.sh deleted file mode 100755 index 8157c225e8..0000000000 --- a/tests/legacy-e2e/che-selenium-core/bin/webdriver.sh +++ /dev/null @@ -1,995 +0,0 @@ -#!/bin/bash -# -# Copyright (c) 2012-2018 Red Hat, Inc. -# This program and the accompanying materials are made -# available under the terms of the Eclipse Public License 2.0 -# which is available at https://www.eclipse.org/legal/epl-2.0/ -# -# SPDX-License-Identifier: EPL-2.0 -# -# Contributors: -# Red Hat, Inc. - initial API and implementation -# - -getRecommendedThreadCount() { - local threadCount=$MIN_THREAD_COUNT - - if [[ "$OSTYPE" == "darwin"* ]]; then - local totalMemory=$(sysctl -a | awk '/hw./' | grep hw.memsize | awk '{print $2}') - if [[ -n "$totalNumber" ]]; then - threadCount=$(( ${totalMemory} / 6000000 )) - fi - else - local freeMemory=$(grep MemFree /proc/meminfo | awk '{print $2}') - if [[ -n "$freeMemory" ]]; then - threadCount=$(( ${freeMemory} / 4000000 )) - fi - fi - - if [[ $threadCount < ${MIN_THREAD_COUNT} ]]; then - threadCount=${MIN_THREAD_COUNT} - - elif [[ $threadCount > ${MAX_THREAD_COUNT} ]]; then - threadCount=${MAX_THREAD_COUNT} - fi - - echo $threadCount -} - -detectDockerInterfaceIp() { - docker run --rm --net host eclipse/che-ip:6.19.0 -} - -initVariables() { - # we need to have at least 2 threads for tests which start several WebDriver instances at once, for example, tests of File Watcher - readonly MIN_THREAD_COUNT=2 - # having more than 5 threads doesn't impact on performance significantly - readonly MAX_THREAD_COUNT=5 - - readonly FAILSAFE_DIR="target/failsafe-reports" - readonly TESTNG_FAILED_SUITE=${FAILSAFE_DIR}"/testng-failed.xml" - readonly FAILSAFE_REPORT="target/site/failsafe-report.html" - - readonly SINGLE_TEST_MSG="single test/package" - - export CHE_MULTIUSER=${CHE_MULTIUSER:-false} - export CHE_INFRASTRUCTURE=${CHE_INFRASTRUCTURE:-docker} - - # CALLER variable contains parent caller script name - # CUR_DIR variable contains the current directory where CALLER is executed - [[ -z ${CALLER+x} ]] && { CALLER=$(basename $0); } - [[ -z ${CUR_DIR+x} ]] && { CUR_DIR=$(cd "$(dirname "$0")"; pwd); } - - [[ -z ${API_SUFFIX+x} ]] && { API_SUFFIX="/api/"; } - - MODE="grid" - GRID_OPTIONS="-Dgrid.mode=true" - RERUN_ATTEMPTS=0 - BROWSER="GOOGLE_CHROME" - WEBDRIVER_VERSION=$(curl -s http://chromedriver.storage.googleapis.com/LATEST_RELEASE) - WEBDRIVER_PORT="9515" - NODE_CHROME_DEBUG_SUFFIX= - THREADS=$(getRecommendedThreadCount) - WORKSPACE_POOL_SIZE=0 - - ACTUAL_RESULTS=() - COMPARE_WITH_CI=false - - PRODUCT_PROTOCOL="http" - PRODUCT_HOST=$(detectDockerInterfaceIp) - PRODUCT_PORT=8080 - INCLUDE_TESTS_UNDER_REPAIR=false - INCLUDE_FLAKY_TESTS=false - FAIL_SCRIPT_ON_FAILED_TESTS=false - - unset DEBUG_OPTIONS - unset MAVEN_OPTIONS - unset TMP_SUITE_PATH - unset ORIGIN_TESTS_SCOPE - unset TMP_DIR - unset EXCLUDE_PARAM - unset TOTAL_FAILS -} - -cleanUpEnvironment() { - if [[ ${MODE} == "grid" ]]; then - stopWebDriver - stopSeleniumDockerContainers - fi -} - -checkParameters() { - for var in "$@"; do - if [[ "$var" =~ --web-driver-version=.* ]]; then : - elif [[ "$var" =~ --web-driver-port=[0-9]+$ ]]; then : - elif [[ "$var" == --http ]]; then : - elif [[ "$var" == --https ]]; then : - elif [[ "$var" == --che ]]; then : - elif [[ "$var" =~ --host=.* ]]; then : - elif [[ "$var" =~ --port=.* ]]; then : - elif [[ "$var" =~ --threads=[0-9]+$ ]]; then : - - elif [[ "$var" == --rerun ]]; then : - elif [[ "$var" =~ ^[0-9]+$ ]] && [[ $@ =~ --rerun[[:space:]]$var ]]; then : - - elif [[ "$var" == --debug ]]; then : - elif [[ "$var" == --all-tests ]]; then - echo "[WARN] '--all-tests' parameter is outdated and is being ignored" - - elif [[ "$var" =~ --test=.* ]]; then - local fileName=$(basename $(echo "$var" | sed -e "s/--test=//g")) - find "target/test-classes" | grep "${fileName}.[class|java]" > /dev/null - [[ $? != 0 ]] && { - echo "[TEST] Test "${fileName}" not found"; - echo "[TEST] Proper way to use --test parameter:"; - echo -e "[TEST] \t--test=DialogAboutTest"; - echo -e "[TEST] \t--test=org.eclipse.che.selenium.miscellaneous.DialogAboutTest"; - echo -e "[TEST] \t--test=org.eclipse.che.selenium.miscellaneous.**"; - exit 1; - } - - elif [[ "$var" =~ --suite=.* ]]; then - local suite=$(basename $(echo "$var" | sed -e "s/--suite=//g")) - find "target/test-classes/suites" | grep ${suite} > /dev/null - [[ $? != 0 ]] && { - echo "[TEST] Suite "${suite}" not found"; - echo "[TEST] Proper way to use --suite parameter:"; - echo -e "[TEST] \t--suite=CheSuite.xml"; - exit 1; - } - - elif [[ "$var" == --failed-tests ]]; then : - elif [[ "$var" == --regression-tests ]]; then : - elif [[ "$var" =~ -M.* ]]; then : - elif [[ "$var" =~ -P.* ]]; then : - elif [[ "$var" == --help ]]; then : - - elif [[ "$var" == --compare-with-ci ]]; then : - elif [[ "$var" =~ ^[0-9]+$ ]] && [[ $@ =~ --compare-with-ci[[:space:]]$var ]]; then : - - elif [[ "$var" =~ ^--workspace-pool-size=(auto|[0-9]+)$ ]]; then : - elif [[ "$var" =~ ^-D.* ]]; then : - elif [[ "$var" =~ ^-[[:alpha:]]$ ]]; then : - elif [[ "$var" == --skip-sources-validation ]]; then : - elif [[ "$var" == --multiuser ]]; then : - elif [[ "$var" =~ --exclude=.* ]]; then : - elif [[ "$var" =~ --include-tests-under-repair ]]; then : - elif [[ "$var" =~ --include-flaky-tests ]]; then : - elif [[ "$var" =~ --fail-script-on-failed-tests ]]; then : - - else - printHelp - echo "[TEST] Unrecognized or misused parameter "${var} - exit 1 - fi - done -} - -applyCustomOptions() { - for var in "$@"; do - if [[ "$var" =~ --web-driver-version=.* ]]; then - if [[ ${MODE} == "local" ]]; then - WEBDRIVER_VERSION=$(echo "$var" | sed -e "s/--web-driver-version=//g") - fi - - elif [[ "$var" =~ --web-driver-port=.* ]]; then - if [[ ${MODE} == "local" ]]; then - WEBDRIVER_PORT=$(echo "$var" | sed -e "s/--web-driver-port=//g") - fi - - elif [[ "$var" == --http ]]; then - PRODUCT_PROTOCOL="http" - - elif [[ "$var" == --https ]]; then - PRODUCT_PROTOCOL="https" - - elif [[ "$var" =~ --host=.* ]]; then - PRODUCT_HOST=$(echo "$var" | sed -e "s/--host=//g") - - elif [[ "$var" =~ --port=.* ]]; then - PRODUCT_PORT=$(echo "$var" | sed -e "s/--port=//g") - - elif [[ "$var" =~ --threads=.* ]]; then - THREADS=$(echo "$var" | sed -e "s/--threads=//g") - - elif [[ "$var" =~ --workspace-pool-size=.* ]]; then - WORKSPACE_POOL_SIZE=$(echo "$var" | sed -e "s/--workspace-pool-size=//g") - - elif [[ "$var" =~ --rerun ]]; then - local rerunAttempts=$(echo $@ | sed 's/.*--rerun\W\+\([0-9]\+\).*/\1/') - if [[ "$rerunAttempts" =~ ^[0-9]+$ ]]; then - RERUN_ATTEMPTS=$rerunAttempts - else - RERUN_ATTEMPTS=1 - fi - - elif [[ "$var" == --debug ]]; then - DEBUG_OPTIONS="-Dmaven.failsafe.debug" - NODE_CHROME_DEBUG_SUFFIX="-debug" - - elif [[ "$var" == --compare-with-ci ]]; then - COMPARE_WITH_CI=true - - elif [[ "$var" == --multiuser ]]; then - CHE_MULTIUSER=true - - elif [[ "$var" =~ --exclude=.* ]]; then - EXCLUDE_PARAM=$(echo "$var" | sed -e "s/--exclude=//g") - - elif [[ "$var" == --include-tests-under-repair ]]; then - INCLUDE_TESTS_UNDER_REPAIR=true - - elif [[ "$var" == --include-flaky-tests ]]; then - INCLUDE_FLAKY_TESTS=true - - elif [[ "$var" == --fail-script-on-failed-tests ]]; then - FAIL_SCRIPT_ON_FAILED_TESTS=true - - fi - done -} - -extractMavenOptions() { - for var in "$@"; do - if [[ "$var" =~ ^-D.* ]]; then - MAVEN_OPTIONS="${MAVEN_OPTIONS} $var" - elif [[ "$var" =~ ^-[[:alpha:]]$ ]]; then : - MAVEN_OPTIONS="${MAVEN_OPTIONS} $var" - elif [[ "$var" == "--skip-sources-validation" ]]; then : - MAVEN_OPTIONS="${MAVEN_OPTIONS} -Dskip-enforce -Dskip-validate-sources" - fi - done -} - - -defineTestsScope() { - for var in "$@"; do - if [[ "$var" =~ --test=.* ]]; then - TESTS_SCOPE="-Dit.test="$(echo "$var" | sed -e "s/--test=//g") - THREADS=1 - - elif [[ "$var" =~ --suite=.* ]]; then - TESTS_SCOPE="-DrunSuite=target/test-classes/suites/"$(echo "$var" | sed -e "s/--suite=//g") - - elif [[ "$var" == --failed-tests ]]; then - generateTestNgFailedReport $(fetchFailedTests) - TESTS_SCOPE="-DrunSuite=${TESTNG_FAILED_SUITE}" - - elif [[ "$var" == --regression-tests ]]; then - generateTestNgFailedReport $(findRegressions) - TESTS_SCOPE="-DrunSuite=${TESTNG_FAILED_SUITE}" - fi - done - - ORIGIN_TESTS_SCOPE=${TESTS_SCOPE} -} - -defineOperationSystemSpecificVariables() { - if [[ "$OSTYPE" == "darwin"* ]]; then - TMP_DIR=$(echo ${TMPDIR}) - else - TMP_DIR="/tmp" - fi -} - -init() { - BLUE='\033[1;34m' - GREEN='\033[0;32m' - RED='\033[0;31m' - YELLOW='\033[0;33m' - NO_COLOUR='\033[0m' -} - -defineRunMode() { - for var in "$@"; do - if [[ "$var" =~ -M.* ]]; then - MODE=$(echo "$var" | sed -e "s/-M//g") - fi - done - - if [[ ${MODE} == "grid" ]]; then - WEBDRIVER_PORT="4444" - - checkDockerRequirements - checkDockerComposeRequirements - - elif [[ ${MODE} == "local" ]]; then - GRID_OPTIONS="-Dgrid.mode=false" - - else - echo "[TEST] Unrecognized mode "${MODE} - echo "[TEST] Available modes: -M[local|grid]" - exit 1 - fi -} - -stopWebDriver() { - if [[ "$OSTYPE" == "darwin"* ]]; then - ps -cf | grep chromedriver | awk '{if(NR>0) print $2}' | while read -r pid; do kill "${pid}" > /dev/null; done - else - ps -fC chromedriver | awk '{if(NR>1) print $2}' | while read -r pid; do kill "${pid}" > /dev/null; done - fi -} - -startWebDriver() { - if [[ "$OSTYPE" == "darwin"* ]]; then - curl -s -o ${TMP_DIR}chromedriver_mac64.zip http://chromedriver.storage.googleapis.com/${WEBDRIVER_VERSION}/chromedriver_mac64.zip - unzip -o ${TMP_DIR}chromedriver_mac64.zip -d ${TMP_DIR} > /dev/null - chmod +x ${TMP_DIR}chromedriver - ${TMP_DIR}chromedriver --port=9515 --no-sandbox > /dev/null & - else - curl -s -o ${TMP_DIR}/chromedriver_linux64.zip http://chromedriver.storage.googleapis.com/${WEBDRIVER_VERSION}/chromedriver_linux64.zip - unzip -o ${TMP_DIR}/chromedriver_linux64.zip -d ${TMP_DIR} > /dev/null - chmod +x ${TMP_DIR}/chromedriver - ${TMP_DIR}/chromedriver --port=9515 --no-sandbox > /dev/null & - fi -} - -initRunMode() { - if [[ ${MODE} == "local" ]]; then - startWebDriver - - elif [[ ${MODE} == "grid" ]]; then - export NODE_CHROME_DEBUG_SUFFIX - docker-compose -p=selenium up -d > /dev/null - docker-compose -p=selenium scale chromenode=${THREADS} > /dev/null - - else - echo "[TEST] Unrecognized mode "${MODE} - exit 1 - fi -} - -stopSeleniumDockerContainers() { - local containers=$(docker ps -qa --filter="name=selenium_*" | wc -l) - if [[ ${containers} != "0" ]]; then - echo "[TEST] Stopping and removing selenium docker containers..." - docker rm -f $(docker ps -qa --filter="name=selenium_*") > /dev/null - fi -} - -checkDockerRequirements() { - command -v docker >/dev/null 2>&1 || { - echo >&2 -e "[TEST] Could not find Docker client, please install it.\n https://docs.docker.com/engine/installation/" - exit 1; - } -} - -checkDockerComposeRequirements() { - command -v docker-compose >/dev/null 2>&1 || { - echo >&2 -e "[TEST] Could not find Docker Compose client, please install it.\n https://docs.docker.com/compose/install/" - exit 1; - } -} - -checkIfProductIsRun() { - local url=${PRODUCT_PROTOCOL}"://"${PRODUCT_HOST}:${PRODUCT_PORT}${API_SUFFIX}; - - curl -s -k -X OPTIONS ${url} > /dev/null - if [[ $? != 0 ]]; then - echo "[TEST] "${url}" is down" - exit 1 - fi -} - -prepareTestSuite() { - local suitePath=${ORIGIN_TESTS_SCOPE:11} - TMP_SUITE_PATH="/tmp/"$(basename "${suitePath}") - rm -f ${TMP_SUITE_PATH} - cp -f ${suitePath} /tmp - - TESTS_SCOPE="-DrunSuite=${TMP_SUITE_PATH}" - - # set number of threads directly in the suite - sed -i -e "s#thread-count=\"[^\"]*\"#thread-count=\"${THREADS}\"#" "$TMP_SUITE_PATH" -} - -printHelp() { - local usage=" -Usage: ${CALLER} [-Mmode] [options] [tests scope] - -Options: - --http Use 'http' protocol to connect to product - --https Use 'https' protocol to connect to product - --host= Set host where product is deployed - --port= Set port of the product, default is 8080 - --multiuser Run tests of Multi User Che - -Modes (defines environment to run tests): - -Mlocal All tests will be run in a Web browser on the developer machine. - Recommended if test visualization is needed and for debugging purpose. - - Options that go with 'local' mode: - --web-driver-version= To use the specific version of the WebDriver, be default the latest will be used: "${WEBDRIVER_VERSION}" - --web-driver-port= To run WebDriver on the specific port, by default: "${WEBDRIVER_PORT}" - --threads= Number of tests that will be run simultaneously. It also means the very same number of - Web browsers will be opened on the developer machine. - Default value is in range [2,5] and depends on available RAM. - - -Mgrid (default) All tests will be run in parallel among several docker containers. - One container per thread. Recommended to run test suite. - - Options that go with 'grid' mode: - --threads= Number of tests that will be run simultaneously. - Default value is in range [2,5] and depends on available RAM. - -Define tests scope: - --test= Single test/package to run. - For example: '--test=DialogAboutTest', '--test=org.eclipse.che.selenium.git.**'. - --suite= Test suite to run, found ('CheSuite.xml' is default one): -"$(for x in $(ls -1 target/test-classes/suites); do echo " * "$x; done)" - --exclude= Comma-separated list of test groups to exclude from execution. - For example, use '--exclude=github' to exclude GitHub-related tests. - -Handle failing tests: - --failed-tests Rerun failed tests that left after the previous try - --regression-tests Rerun regression tests that left after the previous try - --rerun [ATTEMPTS] Automatically rerun failing tests. - Default attempts number is 1. - --compare-with-ci [BUILD NUMBER] Compare failed tests with results on CI server. - Default build is the latest. - --fail-script-on-failed-tests Fail webdriver.sh if tests failed. - -Other options: - --debug Run tests in debug mode - --skip-sources-validation Fast build. Skips source validation and enforce plugins - --workspace-pool-size=[|auto] Size of test workspace pool. - Default value is 0, that means that test workspaces are created on demand. - --include-tests-under-repair Include tests which permanently fail and so belong to group 'UNDER REPAIR' - --include-flaky-tests Include tests which randomly fail and so belong to group 'FLAKY' - -HOW TO of usage: - Test Eclipse Che single user assembly: - ${CALLER} - - Test Eclipse Che multi user assembly: - ${CALLER} --multiuser - - Test Eclipse Che assembly and automatically rerun failing tests: - ${CALLER} --rerun [ATTEMPTS] - - Run single test or package of tests: - ${CALLER} <...> --test= - - Run suite: - ${CALLER} <...> --suite= - - Include tests which belong to groups 'UNDER REPAIR' and 'FLAKY' - ./selenium-tests.sh --include-tests-under-repair --include-flaky-tests - - Rerun failed tests: - ${CALLER} <...> --failed-tests - ${CALLER} <...> --failed-tests --rerun [ATTEMPTS] - - Debug selenium test: - ${CALLER} -Mlocal --test= --debug - - Analyse tests results: - ${CALLER} --compare-with-ci [BUILD NUMBER] -" - - printf "%s" "${usage}" -} - -printRunOptions() { - echo "[TEST]" - echo "[TEST] =========== RUN OPTIONS ===========================" - echo "[TEST] Mode : ${MODE}" - echo "[TEST] Rerun attempts : ${RERUN_ATTEMPTS}" - echo "[TEST] ===================================================" - echo "[TEST] Product Protocol : ${PRODUCT_PROTOCOL}" - echo "[TEST] Product Host : ${PRODUCT_HOST}" - echo "[TEST] Product Port : ${PRODUCT_PORT}" - echo "[TEST] Product Config : $(getProductConfig)" - echo "[TEST] Tests scope : ${TESTS_SCOPE}" - echo "[TEST] Tests to exclude : $(getExcludedGroups)" - echo "[TEST] Threads : ${THREADS}" - echo "[TEST] Workspace pool size : ${WORKSPACE_POOL_SIZE}" - echo "[TEST] Web browser : ${BROWSER}" - echo "[TEST] Web driver ver : ${WEBDRIVER_VERSION}" - echo "[TEST] Web driver port : ${WEBDRIVER_PORT}" - echo "[TEST] Additional opts : ${GRID_OPTIONS} ${DEBUG_OPTIONS} ${MAVEN_OPTIONS}" - echo "[TEST] ===================================================" -} - -# convert failed tests methods in the unique list of test classes -# a.b.c.SomeTest.someMethod1 -# a.b.c.SomeTest.someMethod2 -# |------> a.b.c.SomeTest -getTestClasses() { - local tests=$@ - for t in ${tests[*]} - do - echo $(echo ${t} | sed 's/\(.*\)[.][^.]*/\1/') - done -} - -fetchRunTestsNumber() { - local run=0 - for report in target/failsafe-reports/*.txt - do - if [[ -f ${report} ]]; then - run=$((run + $(cat ${report} | grep "Tests run" | sed 's/Tests run:[[:space:]]\([0-9]*\).*/\1/'))) - fi - done - echo ${run} -} - -# Returns unique records. -fetchFailedTests() { - local fails=() - for report in target/failsafe-reports/*.txt - do - if [[ -f ${report} ]]; then - for item in $(cat ${report} | grep "<<< FAILURE!" | grep -e '(.*).*' | tr ' ' '_') - do - local method=$(echo ${item} | sed 's/\(.*\)(.*)_.*/\1/') - local class=$(echo ${item} | sed 's/.*(\(.*\))_.*/\1/') - fails+=(${class}'.'${method}) - done - fi - done - - for f in $(echo ${fails[@]} | tr ' ' '\n' | sort | uniq) - do - echo ${f} - done -} - -fetchFailedTestsNumber() { - echo $(fetchFailedTests) | wc -w -} - -detectLatestResultsUrl() { - local build=$(curl -s ${BASE_ACTUAL_RESULTS_URL} | tr '\n' ' ' | sed 's/.*Last build (#\([0-9]\+\)).*/\1/') - echo ${BASE_ACTUAL_RESULTS_URL}${build}"/testReport/" -} - -# Fetches list of failed tests and failed configurations. -# Combines them into a single unique list. -fetchActualResults() { - unset ACTUAL_RESULTS - unset ACTUAL_RESULTS_URL - - # define the URL of CI job to compare local result with result on CI - local multiuserToken=$([[ "$CHE_MULTIUSER" == true ]] && echo "-multiuser") - local infrastructureToken=$([[ "$CHE_INFRASTRUCTURE" == "openshift" ]] && echo "-ocp" || echo "-$CHE_INFRASTRUCTURE") - local nameOfCIJob="che-integration-tests${multiuserToken}-master${infrastructureToken}" - - [[ -z ${BASE_ACTUAL_RESULTS_URL+x} ]] && { BASE_ACTUAL_RESULTS_URL="https://ci.codenvycorp.com/view/qa/job/${nameOfCIJob}/"; } - - local build=$(echo $@ | sed 's/.*--compare-with-ci\W\+\([0-9]\+\).*/\1/') - if [[ ! ${build} =~ ^[0-9]+$ ]]; then - ACTUAL_RESULTS_URL=$(detectLatestResultsUrl) - else - ACTUAL_RESULTS_URL=${BASE_ACTUAL_RESULTS_URL}${build}"/testReport/" - fi - - # get list of failed tests from CI server, remove duplicates from it and sort - ACTUAL_RESULTS=$(echo $( curl -s ${ACTUAL_RESULTS_URL} | \ - tr '>' '\n' | tr '<' '\n' | tr '"' '\n' | \ - grep --extended-regexp "^[a-z_$][a-z0-9_$.]*\.[A-Z_$][a-zA-Z0-9_$]*\.[a-z_$][a-zA-Z0-9_$]*$" | \ - tr ' ' '\n' | sort | uniq )) -} - -findRegressions() { - local expected=(${ACTUAL_RESULTS[*]}) - local failed=$(fetchFailedTests) - - for f in ${failed[*]} - do - local skip=false - for e in ${expected[*]} - do - [[ ${f} == ${e} ]] && { skip=true; break; } - done - [[ ${skip} == true ]] || echo ${f} - done -} - -# Analyses tests results by comparing with the actual ones. -analyseTestsResults() { - echo "[TEST]" - echo -e "[TEST] "${YELLOW}"RESULTS ANALYSE:"${NO_COLOUR} - - echo "[TEST]" - echo -e "[TEST] Command line: ${BLUE}${CUR_DIR}/${CALLER} $@${NO_COLOUR}" - echo "[TEST]" - - if [[ ${COMPARE_WITH_CI} == true ]]; then - echo -e "[TEST] CI results ${BLUE}${ACTUAL_RESULTS_URL}${NO_COLOUR}" - echo -e "[TEST] \t- Failed: $(printf "%5s" "$(echo ${ACTUAL_RESULTS[@]} | wc -w)") (unique tests)" - echo "[TEST]" - fi - - local run=$(fetchRunTestsNumber) - local runToDisplay=$(printf "%7s" "${run}") - local fails=$(fetchFailedTests) - TOTAL_FAILS=$(echo ${fails[@]} | wc -w) - local totalFailsToDisplay=$(printf "%5s" "${TOTAL_FAILS}") - - echo "[TEST] Local results:" - echo -e "[TEST] \t- Run: \t${runToDisplay}" - echo -e "[TEST] \t- Failed: ${totalFailsToDisplay}" - - if [[ ${COMPARE_WITH_CI} == true ]]; then - if [[ ! ${TOTAL_FAILS} -eq 0 ]]; then - for r in $(echo ${fails[@]} | tr ' ' '\n' | sort) - do - echo -e "[TEST] \t"${r} - done - fi - echo "[TEST]" - - echo -e -n "[TEST] Comparing with "${BLUE}${ACTUAL_RESULTS_URL}${NO_COLOUR} - if [[ ${ACTUAL_RESULTS_URL} != $(detectLatestResultsUrl) ]]; then - echo -e ${RED}" (not the latest results)"${NO_COLOUR} - else - echo - fi - echo "[TEST] If a test failed then it is NOT marked as regression." - fi - - echo "[TEST]" - - if [[ ${run} == "0" ]]; then - echo -e "[TEST] "${RED}"NO RESULTS"${NO_COLOUR} - else - local regressions=$(findRegressions) - local totalRegressions=$(echo ${regressions[@]} | wc -w) - if [[ ${totalRegressions} -eq 0 ]]; then - echo -e -n "[TEST] "${GREEN}"NO REGRESSION! "${NO_COLOUR} - if [[ ! ${TOTAL_FAILS} -eq 0 ]]; then - echo -e ${RED}"CHECK THE FAILED TESTS. THEY MIGHT FAIL DUE TO DIFFERENT REASON."${NO_COLOUR} - else - echo -e ${GREEN}"NO FAILED TESTS, GREAT JOB!"${NO_COLOUR} - fi - else - echo -e "[TEST] "${RED}"REGRESSION"${NO_COLOUR}" ("${totalRegressions}"):" - - for r in $(echo ${regressions[@]} | tr ' ' '\n' | sort) - do - echo -e "[TEST] \t"${r} - done - fi - fi - - echo "[TEST]" - echo "[TEST]" -} - -printProposals() { - echo -e "[TEST] "${YELLOW}"PROPOSALS:"${NO_COLOUR} - local cmd=$(echo $@ | sed -e "s/--rerun\W*[0-9]*//g" | \ - sed -e "s/-M[^ ]*//g" | \ - sed -e "s/--failed-tests//g" | \ - sed -e "s/--regression-tests//g" | \ - sed -e "s/--suite=[^ ]*//g " | \ - sed -e "s/--test*=[^ ]*//g " | \ - sed -e "s/--compare-with-ci\W*[0-9]*//g" | \ - sed -e "s/--threads=[0-9]*//g" | \ - sed -e "s/--workspace-pool-size=auto|[0-9]*//g") - - local regressions=$(findRegressions) - local total=$(echo ${regressions[@]} | wc -w) - - if [[ ! ${total} -eq 0 ]]; then - echo "[TEST]" - echo "[TEST] Try rerun all tests:" - echo -e "[TEST] \t${BLUE}${CUR_DIR}/${CALLER} ${cmd} --threads=${THREADS} -Mlocal --failed-tests${NO_COLOUR}" - echo -e "[TEST] \t${BLUE}${CUR_DIR}/${CALLER} ${cmd} --threads=${THREADS} -Mgrid --failed-tests${NO_COLOUR}" - - echo "[TEST]" - if [[ ${total} -lt 50 ]]; then - echo "[TEST] Or run them one by one:" - for r in $(echo ${regressions[@]} | tr ' ' '\n' | sed 's/\(.*\)[.][^.]*/\1/' | sort | uniq) - do - echo -e "[TEST] \t${BLUE}${CUR_DIR}/${CALLER} ${cmd} -Mlocal --test=${r}${NO_COLOUR}" - done - echo "[TEST]" - echo -e "[TEST] You might need add ${BLUE}--debug${NO_COLOUR} option for debugging purpose." - fi - fi - - echo "[TEST]" - echo "[TEST] To compare tests results with the latest results on CI job" - echo -e "[TEST] \t${BLUE}${CUR_DIR}/${CALLER} ${cmd} --compare-with-ci${NO_COLOUR}" - echo "[TEST]" - echo "[TEST] To compare local tests results with certain build on CI job" - echo -e "[TEST] \t${BLUE}${CUR_DIR}/${CALLER} ${cmd} --compare-with-ci [BUILD NUMBER]${NO_COLOUR}" - echo "[TEST]" - echo "[TEST]" -} - -printElapsedTime() { - local totalTime=$(($(date +%s)-${START_TIME})) - echo "[TEST]" - echo "[TEST] Elapsed time: "$((${totalTime} / 3600))"hrs "$(( $((${totalTime} / 60)) % 60))"min "$((${totalTime} % 60))"sec" -} - -runTests() { - if [[ ${TESTS_SCOPE} =~ -DrunSuite ]]; then - prepareTestSuite - fi - - printRunOptions - - mvn clean verify -Pselenium-test \ - ${TESTS_SCOPE} \ - -Dche.host=${PRODUCT_HOST} \ - -Dche.port=${PRODUCT_PORT} \ - -Dche.protocol=${PRODUCT_PROTOCOL} \ - -Ddocker.interface.ip=$(detectDockerInterfaceIp) \ - -Ddriver.port=${WEBDRIVER_PORT} \ - -Ddriver.version=${WEBDRIVER_VERSION} \ - -Dbrowser=${BROWSER} \ - -Dche.threads=${THREADS} \ - -Dche.workspace_pool_size=${WORKSPACE_POOL_SIZE} \ - -DexcludedGroups="$(getExcludedGroups)" \ - ${DEBUG_OPTIONS} \ - ${GRID_OPTIONS} \ - ${MAVEN_OPTIONS} -} - -# Return list of product features -getProductConfig() { - local testGroups=${CHE_INFRASTRUCTURE} - - if [[ ${CHE_MULTIUSER} == true ]]; then - testGroups=${testGroups},multiuser - else - testGroups=${testGroups},singleuser - fi - - echo ${testGroups} -} - -# Prepare list of test groups to exclude. -getExcludedGroups() { - local excludeParamArray=(${EXCLUDE_PARAM//,/ }) - - if [[ ${INCLUDE_TESTS_UNDER_REPAIR} == false ]]; then - excludeParamArray+=( 'under_repair' ) - fi - - if [[ ${INCLUDE_FLAKY_TESTS} == false ]]; then - excludeParamArray+=( 'flaky' ) - fi - - echo $(IFS=$','; echo "${excludeParamArray[*]}") -} - -# Reruns failed tests -rerunTests() { - local regressions=$(findRegressions) - local total=$(echo ${regressions[@]} | wc -w) - - if [[ ! ${total} -eq 0 ]]; then - local rerunCounter=$1 && shift - - analyseTestsResults $@ - generateFailSafeReport - printProposals $@ - storeTestReport - printElapsedTime - - echo -e "[TEST]" - echo -e "[TEST] ${YELLOW}---------------------------------------------------${NO_COLOUR}" - echo -e "[TEST] ${YELLOW}RERUNNING FAILED TESTS IN ONE THREAD: ATTEMPT #${rerunCounter}${NO_COLOUR}" - echo -e "[TEST] ${YELLOW}---------------------------------------------------${NO_COLOUR}" - - defineTestsScope "--failed-tests" - runTests - - if [[ ${rerunCounter} < ${RERUN_ATTEMPTS} ]]; then - rerunTests $(($rerunCounter+1)) $@ - fi - fi -} - -# Finds regressions and generates testng-failed.xml suite bases on them. -generateTestNgFailedReport() { - local failsClasses=$(getTestClasses $@) - - if [[ -d ${FAILSAFE_DIR} ]]; then - echo "" > ${TESTNG_FAILED_SUITE} - echo "" >> ${TESTNG_FAILED_SUITE} - echo -e "\t" >> ${TESTNG_FAILED_SUITE} - echo -e "\t\t" >> ${TESTNG_FAILED_SUITE} - - for f in $(echo ${failsClasses[@]} | tr ' ' '\n' | sort | uniq) - do - echo -e -n "\t\t\t> ${TESTNG_FAILED_SUITE} - echo -e -n ${f} >> ${TESTNG_FAILED_SUITE} - echo -e "\"/>" >> ${TESTNG_FAILED_SUITE} - done - echo -e "\t\t" >> ${TESTNG_FAILED_SUITE} - echo -e "\t" >> ${TESTNG_FAILED_SUITE} - echo -e "" >> ${TESTNG_FAILED_SUITE} - fi -} - -# generates and updates failsafe report -generateFailSafeReport () { - mvn -q surefire-report:failsafe-report-only - mvn -q site -DgenerateReports=false - - echo "[TEST]" - echo -e "[TEST] ${YELLOW}REPORT:${NO_COLOUR}" - - if [[ ! -f ${FAILSAFE_REPORT} ]]; then - echo -e "[TEST] Failsafe report: ${BLUE}file://${CUR_DIR}/${FAILSAFE_REPORT}${NO_COLOUR} not found." - echo "[TEST] Either maven surefire report plugin failed or tests haven't been run at all." - echo "[TEST]" - echo "[TEST] To regenerate report manually use the command below:" - echo -e "[TEST] \t${BLUE}${CUR_DIR}/${CALLER} --compare-with-ci${NO_COLOUR}" - echo "[TEST]" - echo "[TEST]" - exit 1 - fi - - local regressions=$(findRegressions) - - # add REGRESSION marks - for r in ${regressions[*]} - do - local test=$(basename $(echo ${r} | tr '.' '/') | sed 's/\(.*\)_.*/\1/') - - local aTag=""${test}"<\/a>" - local divRegTag="

REGRESSION<\/h2>"${aTag} - sed -i "s/${aTag}/${divRegTag}/" ${FAILSAFE_REPORT} - done - - # pack logs of workspaces which failed on start when injecting into test object and add link into the 'Summary' section of failsafe report - local dirWithFailedWorkspacesLogs="target/site/workspace-logs/injecting_workspaces_which_did_not_start" - if [[ -d ${dirWithFailedWorkspacesLogs} ]]; then - cd ${dirWithFailedWorkspacesLogs} - zip -qr "../injecting_workspaces_which_did_not_start_logs.zip" . - cd - > /dev/null - rm -rf ${dirWithFailedWorkspacesLogs} - summaryTag="Summary<\/h2><\/a>" - linkToFailedWorkspacesLogsTag="

\[Injecting workspaces which didn't start logs<\/a>\]<\/p>" - sed -i "s/${summaryTag}/${summaryTag}${linkToFailedWorkspacesLogsTag}/" ${FAILSAFE_REPORT} - fi - - # add link the che server logs archive into the 'Summary' section of failsafe report - local summaryTag="Summary<\/h2><\/a>" - local linkToCheServerLogsTag="

\[Eclipse Che Server logs<\/a>\]<\/p>" - sed -i "s/${summaryTag}/${summaryTag}${linkToCheServerLogsTag}/" ${FAILSAFE_REPORT} - - # attach screenshots - if [[ -d "target/site/screenshots" ]]; then - for file in $(ls target/site/screenshots/* | sort -r) - do - local test=$(basename ${file} | sed 's/\(.*\)_.*/\1/') - local testDetailTag="

" - local screenshotTag="

" - sed -i "s/${testDetailTag}/${testDetailTag}${screenshotTag}/" ${FAILSAFE_REPORT} - done - fi - - attachLinkToTestReport workspace-logs "Workspace logs" - attachLinkToTestReport webdriver-logs "Browser logs" - attachLinkToTestReport htmldumps "Web page source" - - echo "[TEST]" - echo "[TEST] Failsafe report" - echo -e "[TEST] \t${BLUE}file://${CUR_DIR}/${FAILSAFE_REPORT}${NO_COLOUR}" - echo "[TEST]" - echo "[TEST]" -} - -# first argument - relative path to directory inside target/site -# second argument - title of the link -attachLinkToTestReport() { - # attach links to resource related to failed test - local relativePathToResource=$1 - local titleOfLink=$2 - local dirWithResources="target/site/$relativePathToResource" - - # return if directory doesn't exist - [[ ! -d ${dirWithResources} ]] && return - - # return if directory is empty - [[ -z "$(ls -A ${dirWithResources})" ]] && return - - for file in $(ls ${dirWithResources}/* | sort -r) - do - local test=$(basename ${file} | sed 's/\(.*\)_.*/\1/') - local testDetailTag="

" - local filename=$(basename ${file}) - local linkTag="

  • $titleOfLink<\/b>: $filename<\/a><\/li><\/p>" - sed -i "s/${testDetailTag}/${testDetailTag}${linkTag}/" ${FAILSAFE_REPORT} - done -} - -storeTestReport() { - mkdir -p ${TMP_DIR}/webdriver - local report="${TMP_DIR}/webdriver/report$(date +%s).zip" - - rm -rf ${TMP_DIR}/webdriver/tmp - mkdir target/suite - if [[ -f ${TMP_SUITE_PATH} ]]; then - cp ${TMP_SUITE_PATH} target/suite; - fi - zip -qr ${report} target/screenshots target/htmldumps target/workspace-logs target/webdriver-logs target/site target/failsafe-reports target/log target/bin target/suite - - echo -e "[TEST] Tests results and reports are saved to ${BLUE}${report}${NO_COLOUR}" - echo "[TEST]" - echo "[TEST] If target directory is accidentally cleaned it is possible to restore it: " - echo -e "[TEST] \t${BLUE}rm -rf ${CUR_DIR}/target && unzip -q ${report} -d ${CUR_DIR}${NO_COLOUR}" - echo "[TEST]" -} - -checkBuild() { - mvn package ${MAVEN_OPTIONS} - [[ $? != 0 ]] && { exit 1; } -} - -prepareToFirstRun() { - checkIfProductIsRun - cleanUpEnvironment - initRunMode -} - -getKeycloakContainerId() { - if [[ "${CHE_INFRASTRUCTURE}" == "openshift" ]]; then - echo $(docker ps | grep 'keycloak_keycloak-' | cut -d ' ' -f1) - else - echo $(docker ps | grep che_keycloak | cut -d ' ' -f1) - fi -} - -testProduct() { - runTests - - if [[ ${RERUN_ATTEMPTS} > 0 ]]; then - MAVEN_OPTIONS="${MAVEN_OPTIONS} -o" - rerunTests 1 $@ - fi -} - -run() { - if [[ $@ =~ --help ]]; then - printHelp - exit - fi - - START_TIME=$(date +%s) - - trap cleanUpEnvironment EXIT - - initVariables - init - extractMavenOptions $@ - checkBuild - - checkParameters $@ - defineOperationSystemSpecificVariables - defineRunMode $@ - - defineTestsScope $@ - applyCustomOptions $@ - - if [[ ${COMPARE_WITH_CI} == true ]]; then - fetchActualResults $@ - else - prepareToFirstRun - testProduct $@ - fi - - analyseTestsResults $@ - - if [[ ${COMPARE_WITH_CI} == false ]]; then - generateFailSafeReport - printProposals $@ - storeTestReport - printElapsedTime - fi -} - -run "$@" - -if [[ ${TOTAL_FAILS} -ne 0 && ${FAIL_SCRIPT_ON_FAILED_TESTS} == true ]]; then - exit 1 -fi diff --git a/tests/legacy-e2e/che-selenium-core/pom.xml b/tests/legacy-e2e/che-selenium-core/pom.xml deleted file mode 100644 index 9e6fef1621..0000000000 --- a/tests/legacy-e2e/che-selenium-core/pom.xml +++ /dev/null @@ -1,168 +0,0 @@ - - - - 4.0.0 - - che-selenium-parent - org.eclipse.che.selenium - 7.29.0-SNAPSHOT - - che-selenium-core - jar - Che Legacy E2E :: Core - - - com.google.code.gson - gson - - - com.google.guava - guava - - - com.google.inject - guice - - - com.google.inject.extensions - guice-assistedinject - - - commons-io - commons-io - - - javax.annotation - javax.annotation-api - - - javax.inject - javax.inject - - - javax.validation - validation-api - - - org.eclipse.che.core - che-core-api-core - - - org.eclipse.che.core - che-core-api-dto - - - org.eclipse.che.core - che-core-api-factory-shared - - - org.eclipse.che.core - che-core-api-model - - - org.eclipse.che.core - che-core-api-ssh-shared - - - org.eclipse.che.core - che-core-api-user-shared - - - org.eclipse.che.core - che-core-api-workspace-shared - - - org.eclipse.che.core - che-core-commons-annotations - - - org.eclipse.che.core - che-core-commons-json - - - org.eclipse.che.core - che-core-commons-lang - - - org.eclipse.che.multiuser - che-multiuser-api-organization-shared - - - org.eclipse.che.multiuser - che-multiuser-api-permission-shared - - - org.kohsuke - github-api - - - org.seleniumhq.selenium - selenium-api - - - org.seleniumhq.selenium - selenium-chrome-driver - - - org.seleniumhq.selenium - selenium-remote-driver - - - org.seleniumhq.selenium - selenium-support - - - org.slf4j - slf4j-api - - - org.testng - testng - - - org.eclipse.che.core - che-core-commons-inject - provided - - - ch.qos.logback - logback-classic - test - - - org.mockito - mockito-core - test - - - org.mockito - mockito-testng - test - - - - - - bin - - - src/main/java - - - src/main/resources - - - - diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/SeleniumWebDriver.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/SeleniumWebDriver.java deleted file mode 100644 index b73103d510..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/SeleniumWebDriver.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.APPLICATION_START_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOADER_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.utils.WaitUtils.sleepQuietly; -import static org.openqa.selenium.support.ui.ExpectedConditions.frameToBeAvailableAndSwitchToIt; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.io.Closeable; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Scanner; -import java.util.Set; -import java.util.logging.Level; -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.ConflictException; -import org.eclipse.che.api.core.ForbiddenException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.core.UnauthorizedException; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.commons.annotation.Nullable; -import org.eclipse.che.selenium.core.constant.TestBrowser; -import org.eclipse.che.selenium.core.utils.DockerUtil; -import org.openqa.selenium.By; -import org.openqa.selenium.Dimension; -import org.openqa.selenium.JavascriptExecutor; -import org.openqa.selenium.OutputType; -import org.openqa.selenium.TakesScreenshot; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebDriverException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.chrome.ChromeOptions; -import org.openqa.selenium.interactions.HasInputDevices; -import org.openqa.selenium.interactions.Keyboard; -import org.openqa.selenium.interactions.Mouse; -import org.openqa.selenium.logging.LogType; -import org.openqa.selenium.logging.LoggingPreferences; -import org.openqa.selenium.remote.CapabilityType; -import org.openqa.selenium.remote.DesiredCapabilities; -import org.openqa.selenium.remote.RemoteWebDriver; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.WebDriverWait; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Wrapper for {@link WebDriver} to have ability to use in Guice container. - * - * @author Anatolii Bazko - */ -@Singleton -public class SeleniumWebDriver - implements Closeable, WebDriver, JavascriptExecutor, TakesScreenshot, HasInputDevices { - private static final Logger LOG = LoggerFactory.getLogger(SeleniumWebDriver.class); - private static final int MAX_ATTEMPTS = 5; - private static final int DELAY_IN_SECONDS = 5; - - private TestBrowser browser; - private boolean gridMode; - private String gridNodeContainerId; - private String webDriverPort; - private final RemoteWebDriver driver; - private final HttpJsonRequestFactory httpJsonRequestFactory; - private final DockerUtil dockerUtil; - private final String downloadDir; - - @Inject - public SeleniumWebDriver( - @Named("sys.browser") TestBrowser browser, - @Named("sys.driver.port") String webDriverPort, - @Named("sys.grid.mode") boolean gridMode, - HttpJsonRequestFactory httpJsonRequestFactory, - DockerUtil dockerUtil, - @Named("tests.tmp_dir") String downloadDir) { - this.browser = browser; - this.webDriverPort = webDriverPort; - this.gridMode = gridMode; - this.httpJsonRequestFactory = httpJsonRequestFactory; - this.dockerUtil = dockerUtil; - this.downloadDir = downloadDir; - - try { - URL webDriverUrl = - new URL(format("http://localhost:%s%s", webDriverPort, gridMode ? "/wd/hub" : "")); - this.driver = createDriver(webDriverUrl); - } catch (MalformedURLException e) { - throw new RuntimeException("Error of construction URL to web driver.", e); - } - } - - @Override - public void get(String url) { - driver.get(url); - } - - @Override - public String getCurrentUrl() { - return driver.getCurrentUrl(); - } - - @Override - public String getTitle() { - return driver.getTitle(); - } - - @Override - public List findElements(By by) { - return driver.findElements(by); - } - - @Override - public WebElement findElement(By by) { - return driver.findElement(by); - } - - @Override - public String getPageSource() { - return driver.getPageSource(); - } - - @Override - public void close() { - driver.close(); - } - - @Override - public void quit() { - driver.quit(); - } - - @Override - public Set getWindowHandles() { - return driver.getWindowHandles(); - } - - @Override - public String getWindowHandle() { - return driver.getWindowHandle(); - } - - @Override - public TargetLocator switchTo() { - return driver.switchTo(); - } - - @Override - public Navigation navigate() { - return driver.navigate(); - } - - @Override - public Options manage() { - return driver.manage(); - } - - @Override - public Object executeScript(String script, Object... args) { - return driver.executeScript(script, args); - } - - @Override - public Object executeAsyncScript(String script, Object... args) { - return driver.executeAsyncScript(script, args); - } - - @Override - public X getScreenshotAs(OutputType target) throws WebDriverException { - return driver.getScreenshotAs(target); - } - - @Override - public Keyboard getKeyboard() { - return driver.getKeyboard(); - } - - @Override - public Mouse getMouse() { - return driver.getMouse(); - } - - private RemoteWebDriver createDriver(URL webDriverUrl) { - for (int i = 1; ; ) { - try { - return doCreateDriver(webDriverUrl); - } catch (WebDriverException e) { - if (i++ >= MAX_ATTEMPTS) { - throw e; - } - } - - sleepQuietly(DELAY_IN_SECONDS); - } - } - - /** - * Read supported version info from official site. - * - * @param webDriverOfficialNotes address of official page with Google driver info - * @return string with supported version range (for example, "36-40"), or null if version info - * doesn't found inside the official notes. - * @throws IOException - */ - @Nullable - private String readSupportedVersionInfoForGoogleDriver(URL webDriverOfficialNotes) - throws IOException { - try (Scanner scanner = new Scanner(webDriverOfficialNotes.openStream(), "UTF-8")) { - while (scanner.hasNextLine()) { - String versionLine = scanner.findInLine("Supports Chrome v([\\d-]+)"); - if (versionLine != null) { - return scanner.match().group(1); - } - - scanner.nextLine(); - } - } - - return null; - } - - private RemoteWebDriver doCreateDriver(URL webDriverUrl) { - DesiredCapabilities capability; - - switch (browser) { - case GOOGLE_CHROME: - LoggingPreferences loggingPreferences = new LoggingPreferences(); - loggingPreferences.enable(LogType.PERFORMANCE, Level.ALL); - loggingPreferences.enable(LogType.BROWSER, Level.ALL); - - ChromeOptions options = new ChromeOptions(); - options.addArguments("--no-sandbox"); - options.addArguments("--dns-prefetch-disable"); - options.addArguments("--ignore-certificate-errors"); - - // set parameters required for automatic download capability - Map chromePrefs = new HashMap<>(); - chromePrefs.put("download.default_directory", downloadDir); - chromePrefs.put("download.prompt_for_download", false); - chromePrefs.put("download.directory_upgrade", true); - chromePrefs.put("safebrowsing.enabled", true); - chromePrefs.put("profile.default_content_settings.popups", 0); - chromePrefs.put("plugins.plugins_disabled", "['Chrome PDF Viewer']"); - options.setExperimentalOption("prefs", chromePrefs); - - capability = DesiredCapabilities.chrome(); - capability.setCapability(ChromeOptions.CAPABILITY, options); - capability.setCapability(CapabilityType.LOGGING_PREFS, loggingPreferences); - capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); - break; - - default: - capability = DesiredCapabilities.firefox(); - capability.setCapability("dom.max_script_run_time", 240); - capability.setCapability("dom.max_chrome_script_run_time", 240); - } - - RemoteWebDriver driver = new RemoteWebDriver(webDriverUrl, capability); - if (driver.getErrorHandler().isIncludeServerErrors() - && driver.getCapabilities().getCapability("message") != null) { - String errorMessage = - format( - "Web driver creation error occurred: %s", - driver.getCapabilities().getCapability("message")); - LOG.error(errorMessage); - throw new RuntimeException(errorMessage); - } - - driver.manage().window().setSize(new Dimension(1920, 1080)); - - return driver; - } - - /** wait while in a browser appears more the 1 window */ - public void waitOpenedSomeWin() { - new WebDriverWait(this, 30) - .until( - (ExpectedCondition) - input -> { - Set driverWindows = getWindowHandles(); - return (driverWindows.size() > 1); - }); - } - - /** - * calculate name of workspace from browser url cut symbols from end of slash symbol ("/") to end - */ - public String getWorkspaceNameFromBrowserUrl() { - String currentUrl = getCurrentUrl(); - return currentUrl.substring(currentUrl.lastIndexOf("/") + 1, currentUrl.length()); - } - - /** - * switch to the next browser window (this means that if opened 2 windows, and we are in the - * window 1, we will be switched into the window 2 ) - * - * @param currentWindowHandler - */ - public void switchToNoneCurrentWindow(String currentWindowHandler) { - waitOpenedSomeWin(); - for (String handle : getWindowHandles()) { - if (!currentWindowHandler.equals(handle)) { - switchTo().window(handle); - break; - } - } - } - - public void switchFromDashboardIframeToIde() { - switchFromDashboardIframeToIde(APPLICATION_START_TIMEOUT_SEC); - } - - public void switchFromDashboardIframeToIde(int timeout) { - wait(timeout).until(visibilityOfElementLocated(By.id("ide-application-iframe"))); - - wait(LOADER_TIMEOUT_SEC) - .until( - (ExpectedCondition) - driver -> - (((JavascriptExecutor) driver) - .executeScript("return angular.element('body').scope().showIDE")) - .toString() - .equals("true")); - - wait(timeout).until(frameToBeAvailableAndSwitchToIt(By.id("ide-application-iframe"))); - } - - private WebDriverWait wait(int timeOutInSeconds) { - return new WebDriverWait(this, timeOutInSeconds); - } - - public String getGridNodeContainerId() throws IOException { - if (!gridMode) { - throw new UnsupportedOperationException("We can't get grid node container id in local mode."); - } - - if (gridNodeContainerId == null) { - String getGridNodeInfoUrl = - format( - "http://localhost:%s/grid/api/testsession?session=%s", - webDriverPort, driver.getSessionId()); - - Map gridNodeInfo; - try { - gridNodeInfo = httpJsonRequestFactory.fromUrl(getGridNodeInfoUrl).request().asProperties(); - } catch (ServerException - | UnauthorizedException - | ForbiddenException - | NotFoundException - | ConflictException - | BadRequestException e) { - throw new IOException(e); - } - - if (!gridNodeInfo.containsKey("proxyId")) { - throw new IOException("Proxy ID of grid node wasn't found."); - } - - URL proxyId = new URL(gridNodeInfo.get("proxyId")); - gridNodeContainerId = dockerUtil.findGridNodeContainerByIp(proxyId.getHost()); - } - - return gridNodeContainerId; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/TestGroup.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/TestGroup.java deleted file mode 100644 index 5f0c1c8284..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/TestGroup.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -/** @author Dmytro Nochevnov */ -public interface TestGroup { - String MULTIUSER = "multiuser"; - String SINGLEUSER = "singleuser"; - String OPENSHIFT = "openshift"; - String DOCKER = "docker"; - String GITHUB = "github"; - String OSIO = "osio"; - String K8S = "k8s"; - String UNDER_REPAIR = "under_repair"; - String FLAKY = "flaky"; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/ActionsFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/ActionsFactory.java deleted file mode 100644 index cb2e272b52..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/ActionsFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.action; - -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.interactions.Actions; - -/** - * Main interface for producing new instances of {@link Actions}. - * - * @author Vlad Zhukovskyi - */ -public interface ActionsFactory { - - /** - * Creates a new instance of {@link Actions} based on input {@code webDriver} - * - * @param webDriver instance of {@link WebDriver} - * @return a new instance of {@link Actions} - */ - Actions createAction(WebDriver webDriver); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/GenericActions.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/GenericActions.java deleted file mode 100644 index 4bbcb2f2c6..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/GenericActions.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.action; - -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.interactions.Actions; - -/** - * Generic actions. Default extension of the {@link Actions} which actually doesn't modify a - * behavior of internal {@link Actions}. - * - * @author Vlad Zhukovskyi - * @see Actions - */ -public class GenericActions extends PlatformBasedActions { - public GenericActions(WebDriver driver) { - super(driver); - } - - @Override - protected CharSequence[] modifyCharSequence(CharSequence... keysToSend) { - return keysToSend; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/GenericActionsFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/GenericActionsFactory.java deleted file mode 100644 index bd2393cef9..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/GenericActionsFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.action; - -import com.google.inject.Singleton; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.interactions.Actions; - -/** - * Default actions factory for the generic operation system, linux, windows, etc. - * - * @author Vlad Zhukovskyi - * @see GenericActions - * @see ActionsFactory - */ -@Singleton -public class GenericActionsFactory implements ActionsFactory { - @Override - public Actions createAction(WebDriver webDriver) { - return new GenericActions(webDriver); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/MacOSActions.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/MacOSActions.java deleted file mode 100644 index d9972869a0..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/MacOSActions.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.action; - -import static com.google.common.collect.Lists.newArrayList; - -import java.util.List; -import org.openqa.selenium.Keys; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.interactions.Actions; -import org.openqa.selenium.interactions.SendKeysAction; - -/** - * Mac OS based extension of {@link Actions}. Modifies the behavior of {@link SendKeysAction} by - * replacing key press calls. Unfortunately this may need for that reason, that some of selenium - * tests may send: - * - *
      - *
    • {@link Keys#END} - *
    • {@link Keys#HOME} - *
    • {@link Keys#PAGE_DOWN} - *
    • {@link Keys#PAGE_UP} - *
    - * - * which don't work in current operation system. So some tests may fail. but for above key press in - * Mac OS there are equivalence: - * - *
      - *
    • Command+Right - *
    • Command+Left - *
    • Command+Down - *
    • Command+Up - *
    - * - * and method may look for non-working key presses from the input array of {@link CharSequence} and - * replace them with equivalence. So for test it will looks like it runs transparently on any OS. - * - *

    For more information see {@link #modifyCharSequence(CharSequence...)} - * - * @author Vlad Zhukovskyi - */ -public class MacOSActions extends PlatformBasedActions { - public MacOSActions(WebDriver driver) { - super(driver); - } - - @Override - protected CharSequence[] modifyCharSequence(CharSequence... keysToSend) { - final List modKeysToSend = newArrayList(); - - for (CharSequence charSequence : keysToSend) { - final String key = charSequence.toString(); - - if (Keys.END.toString().equals(key)) { - modKeysToSend.add(Keys.chord(Keys.COMMAND, Keys.RIGHT)); - } else if (Keys.HOME.toString().equals(key)) { - modKeysToSend.add(Keys.chord(Keys.COMMAND, Keys.LEFT)); - } else if (Keys.PAGE_UP.toString().equals(key)) { - modKeysToSend.add(Keys.chord(Keys.COMMAND, Keys.UP)); - } else if (Keys.PAGE_DOWN.toString().equals(key)) { - modKeysToSend.add(Keys.chord(Keys.COMMAND, Keys.DOWN)); - } else { - modKeysToSend.add(charSequence); - } - } - - return modKeysToSend.toArray(new CharSequence[modKeysToSend.size()]); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/MacOSActionsFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/MacOSActionsFactory.java deleted file mode 100644 index c465e6d36a..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/MacOSActionsFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.action; - -import com.google.inject.Singleton; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.interactions.Actions; - -/** - * Mac OS based actions factory. - * - * @author Vlad Zhukovskyi - * @see MacOSActions - * @see ActionsFactory - */ -@Singleton -public class MacOSActionsFactory implements ActionsFactory { - - @Override - public Actions createAction(WebDriver webDriver) { - return new MacOSActions(webDriver); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/PlatformBasedActions.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/PlatformBasedActions.java deleted file mode 100644 index c37dc1a6d3..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/action/PlatformBasedActions.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.action; - -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.interactions.Actions; -import org.openqa.selenium.interactions.SendKeysAction; -import org.openqa.selenium.internal.Locatable; - -/** - * Abstract class for platform based actions. Generify the interface for using selenium action - * independently from the OS on which tests are running. - * - * @author Vlad Zhukovskyi - */ -public abstract class PlatformBasedActions extends Actions { - - public PlatformBasedActions(WebDriver driver) { - super(driver); - } - - @Override - public Actions sendKeys(WebElement element, CharSequence... keysToSend) { - action.addAction( - new SendKeysAction(keyboard, mouse, (Locatable) element, modifyCharSequence(keysToSend))); - return this; - } - - protected abstract CharSequence[] modifyCharSequence(CharSequence... keysToSend); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/AbstractTestWorkspaceServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/AbstractTestWorkspaceServiceClient.java deleted file mode 100644 index 8cb3ab6116..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/AbstractTestWorkspaceServiceClient.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static java.lang.String.format; -import static java.lang.String.valueOf; -import static org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STOPPED; -import static org.eclipse.che.api.core.model.workspace.WorkspaceStatus.STOPPING; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.model.workspace.Workspace; -import org.eclipse.che.api.core.model.workspace.WorkspaceStatus; -import org.eclipse.che.api.core.model.workspace.runtime.Machine; -import org.eclipse.che.api.core.model.workspace.runtime.Server; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.workspace.shared.Constants; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto; -import org.eclipse.che.commons.annotation.Nullable; -import org.eclipse.che.selenium.core.constant.TestTimeoutsConstants; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.TestUserHttpJsonRequestFactoryCreator; -import org.eclipse.che.selenium.core.user.TestUser; -import org.eclipse.che.selenium.core.utils.WaitUtils; -import org.eclipse.che.selenium.core.workspace.MemoryMeasure; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Musienko Maxim - * @author Dmytro Nochevnov - */ -public abstract class AbstractTestWorkspaceServiceClient implements TestWorkspaceServiceClient { - - private static final Logger LOG = - LoggerFactory.getLogger(AbstractTestWorkspaceServiceClient.class); - - protected final TestApiEndpointUrlProvider apiEndpointProvider; - protected final HttpJsonRequestFactory requestFactory; - - public AbstractTestWorkspaceServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, HttpJsonRequestFactory requestFactory) { - this.apiEndpointProvider = apiEndpointProvider; - this.requestFactory = requestFactory; - } - - public AbstractTestWorkspaceServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, - TestUserHttpJsonRequestFactoryCreator userHttpJsonRequestFactoryCreator, - TestUser testUser) { - this(apiEndpointProvider, userHttpJsonRequestFactoryCreator.create(testUser)); - } - - protected String getBaseUrl() { - return apiEndpointProvider.get() + "workspace"; - } - - /** Returns the list of workspaces names that belongs to the user. */ - @Override - public List getAll() throws Exception { - List workspaces = - requestFactory.fromUrl(getBaseUrl()).request().asList(WorkspaceDto.class); - return workspaces.stream().map(ws -> ws.getConfig().getName()).collect(Collectors.toList()); - } - - /** Returns the number of workspaces that belongs to the user. */ - @Override - public int getWorkspacesCount() throws Exception { - List workspaces = - requestFactory.fromUrl(getBaseUrl()).request().asList(WorkspaceDto.class); - return workspaces.size(); - } - - /** Stops workspace. */ - @Override - public void stop(String workspaceName, String userName) throws Exception { - sendStopRequest(workspaceName, userName); - waitStatus(workspaceName, userName, STOPPED); - } - - /** Returns workspace of default user by its name. */ - @Override - public Workspace getByName(String workspace, String username) throws Exception { - return requestFactory - .fromUrl(getNameBasedUrl(workspace, username)) - .request() - .asDto(WorkspaceDto.class); - } - - /** Indicates if workspace exists. */ - @Override - public boolean exists(String workspace, String username) throws Exception { - try { - requestFactory.fromUrl(getNameBasedUrl(workspace, username)).request(); - } catch (NotFoundException e) { - return false; - } - - return true; - } - - /** Deletes workspace of default user. */ - @Override - public void delete(String workspaceName, String userName) throws Exception { - if (!exists(workspaceName, userName)) { - return; - } - - Workspace workspace = getByName(workspaceName, userName); - if (workspace.getStatus() == STOPPING) { - waitStatus(workspaceName, userName, STOPPED); - } else if (workspace.getStatus() != STOPPED) { - stop(workspaceName, userName); - } - - requestFactory.fromUrl(getIdBasedUrl(workspace.getId())).useDeleteMethod().request(); - - WaitUtils.waitSuccessCondition( - () -> { - try { - return !exists(workspaceName, userName); - } catch (Exception e) { - throw new RuntimeException( - format( - "Error of waiting on workspace name='%s', id='%s', username='%s' removal.", - workspaceName, workspace.getId(), userName), - e); - } - }, - TestTimeoutsConstants.PREPARING_WS_TIMEOUT_SEC, - 500, - TimeUnit.SECONDS); - - LOG.info( - "Workspace name='{}', id='{}', username='{}' removed", - workspaceName, - workspace.getId(), - userName); - } - - /** Waits workspace is started. */ - @Override - public void waitWorkspaceStart(String workspaceName, String userName) throws Exception { - WaitUtils.sleepQuietly(5); // delay 5 secs to obtain starting status for sure - WaitUtils.waitSuccessCondition( - () -> { - WorkspaceStatus status; - try { - status = getByName(workspaceName, userName).getStatus(); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - - switch (status) { - case RUNNING: - return true; - - case STARTING: - return false; - - default: - throw new RuntimeException( - format("Workspace with name '%s' didn't start", workspaceName)); - } - }, - 600, - 1000, - TimeUnit.SECONDS); - } - - /** Waits needed status. */ - @Override - public void waitStatus(String workspaceName, String userName, WorkspaceStatus expectedStatus) - throws Exception { - waitStatus(workspaceName, userName, expectedStatus, 600); - } - - public void waitStatus( - String workspaceName, String userName, WorkspaceStatus expectedStatus, int timeoutSeconds) - throws Exception { - WaitUtils.waitSuccessCondition( - () -> { - try { - if (getByName(workspaceName, userName).getStatus() == expectedStatus) { - return true; - } - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - - return false; - }, - timeoutSeconds, - 1000, - TimeUnit.SECONDS); - } - - /** Sends start workspace request. */ - @Override - public void sendStartRequest(String workspaceId, String workspaceName) throws Exception { - requestFactory - .fromUrl(getIdBasedUrl(workspaceId) + "/runtime") - .addQueryParam("environment", workspaceName) - .usePostMethod() - .request(); - } - - /** Gets workspace by its id. */ - @Override - public WorkspaceDto getById(String workspaceId) throws Exception { - return requestFactory.fromUrl(getIdBasedUrl(workspaceId)).request().asDto(WorkspaceDto.class); - } - - /** Gets workspace status by id. */ - @Override - public WorkspaceStatus getStatus(String workspaceId) throws Exception { - return getById(workspaceId).getStatus(); - } - - /** - * Return server URL related with defined port - * - * @deprecated use {@link #getServerFromDevMachineBySymbolicName(String, String)} to retrieve - * server URL from instead - */ - @Override - @Deprecated - @Nullable - public String getServerAddressByPort(String workspaceId, int port) throws Exception { - Workspace workspace = getById(workspaceId); - ensureRunningStatus(workspace); - - Map machines = workspace.getRuntime().getMachines(); - for (Machine machine : machines.values()) { - if (containsWsAgentServer(machine)) { - return machine.getServers().get(valueOf(port) + "/tcp").getUrl(); - } - } - return null; - } - - /** - * Return ServerDto object from runtime by it's symbolic name - * - * @param workspaceId workspace id of current user - * @param serverName server name - * @return ServerDto object - */ - @Override - @Nullable - public Server getServerFromDevMachineBySymbolicName(String workspaceId, String serverName) - throws Exception { - Workspace workspace = - requestFactory.fromUrl(getIdBasedUrl(workspaceId)).request().asDto(WorkspaceDto.class); - - ensureRunningStatus(workspace); - - Map machines = workspace.getRuntime().getMachines(); - for (Machine machine : machines.values()) { - if (containsWsAgentServer(machine)) { - return machine.getServers().get(serverName); - } - } - return null; - } - - /** - * Ensure workspace has running status, or throw IllegalStateException. - * - * @param workspace workspace description to get status and id. - * @throws IllegalStateException if workspace with certain workspaceId doesn't have RUNNING - * status. - */ - @Override - public void ensureRunningStatus(Workspace workspace) throws IllegalStateException { - if (workspace.getStatus() != WorkspaceStatus.RUNNING) { - throw new IllegalStateException( - format( - "Workspace with id='%s' should has '%s' status, but its actual state='%s'", - workspace.getId(), WorkspaceStatus.RUNNING, workspace.getStatus())); - } - } - - /** - * Delete workspaces which could be created from factory - * - * @param originalName name workspace which was used to create factory - */ - @Override - public void deleteFactoryWorkspaces(String originalName, String username) throws Exception { - String workspace2delete = originalName; - for (int i = 1; ; i++) { - if (!exists(workspace2delete, username)) { - break; - } - - delete(workspace2delete, username); - workspace2delete = originalName + "_" + i; - } - } - - // ================= // - // PRIVATE METHODS // - // ================= // - - /** Sends stop workspace request. */ - private void sendStopRequest(String workspaceName, String userName) throws Exception { - if (!exists(workspaceName, userName)) { - return; - } - - Workspace workspace = getByName(workspaceName, userName); - String apiUrl = getIdBasedUrl(workspace.getId()) + "/runtime/"; - - requestFactory.fromUrl(apiUrl).useDeleteMethod().request(); - } - - protected String getNameBasedUrl(String workspaceName, String username) { - return getBaseUrl() + "/" + username + "/" + workspaceName; - } - - protected String getIdBasedUrl(String workspaceId) { - return getBaseUrl() + "/" + workspaceId; - } - - protected long convertToByte(int numberOfMemValue, MemoryMeasure desiredMeasureMemory) { - long calculatedValue = 0; - // represents values of bytes in 1 megabyte (2x20) - final long MEGABYTES_CONST = 1048576; - - // represents values of bytes in 1 gygabyte (2x30) - final long GYGABYTES_CONST = 1073741824; - - switch (desiredMeasureMemory) { - case MB: - calculatedValue = numberOfMemValue * MEGABYTES_CONST; - break; - case GB: - calculatedValue = numberOfMemValue * GYGABYTES_CONST; - break; - } - return calculatedValue; - } - - /** - * Checks whether provided {@link Machine} contains wsagent server. - * - * @param machine machine to check - * @return true when wsagent server is found in provided machine, false otherwise - */ - public static boolean containsWsAgentServer(Machine machine) { - return machine.getServers().keySet().contains(Constants.SERVER_WS_AGENT_HTTP_REFERENCE); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/CheTestUserServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/CheTestUserServiceClient.java deleted file mode 100644 index 0948074ff0..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/CheTestUserServiceClient.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.ConflictException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.TestUserHttpJsonRequestFactory; - -/** @author Anton Korneta */ -@Singleton -public class CheTestUserServiceClient extends TestUserServiceClientImpl { - - @Inject - public CheTestUserServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, - TestUserHttpJsonRequestFactory requestFactory) { - super(apiEndpointProvider, requestFactory); - } - - @Override - public void create(String name, String email, String password) - throws BadRequestException, ConflictException, ServerException {} - - @Override - public void remove(String id) throws ServerException, ConflictException {} -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/CheTestWorkspaceServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/CheTestWorkspaceServiceClient.java deleted file mode 100644 index 34f923ed01..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/CheTestWorkspaceServiceClient.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.Inject; -import com.google.inject.assistedinject.Assisted; -import com.google.inject.assistedinject.AssistedInject; -import org.eclipse.che.api.core.model.workspace.Workspace; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.TestUserHttpJsonRequestFactoryCreator; -import org.eclipse.che.selenium.core.user.TestUser; -import org.eclipse.che.selenium.core.workspace.MemoryMeasure; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CheTestWorkspaceServiceClient extends AbstractTestWorkspaceServiceClient { - - private static final Logger LOG = LoggerFactory.getLogger(CheTestWorkspaceServiceClient.class); - - @Inject - public CheTestWorkspaceServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, HttpJsonRequestFactory requestFactory) { - super(apiEndpointProvider, requestFactory); - } - - @AssistedInject - public CheTestWorkspaceServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, - TestUserHttpJsonRequestFactoryCreator userHttpJsonRequestFactoryCreator, - @Assisted TestUser testUser) { - super(apiEndpointProvider, userHttpJsonRequestFactoryCreator, testUser); - } - - @Override - public Workspace createWorkspace( - String workspaceName, int memory, MemoryMeasure memoryUnit, WorkspaceConfigDto workspace) - throws Exception { - workspace.setName(workspaceName); - workspace.setDefaultEnv(workspaceName); - WorkspaceDto workspaceDto = - requestFactory - .fromUrl(getBaseUrl()) - .usePostMethod() - .setBody(workspace) - .request() - .asDto(WorkspaceDto.class); - - LOG.info("Workspace name='{}' and id='{}' created", workspaceName, workspaceDto.getId()); - - return workspaceDto; - } - - @Override - public void start(String workspaceId, String workspaceName, TestUser workspaceOwner) - throws Exception { - sendStartRequest(workspaceId, workspaceName); - waitWorkspaceStart(workspaceName, workspaceOwner.getName()); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/GitHubKey.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/GitHubKey.java deleted file mode 100644 index b05adb6895..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/GitHubKey.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import org.eclipse.che.dto.shared.DTO; - -@DTO -public class GitHubKey { - private int id; - private String key; - private String url; - private String title; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestAuthServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestAuthServiceClient.java deleted file mode 100644 index 4ab0986111..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestAuthServiceClient.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -/** @author Anatolii Bazko */ -public interface TestAuthServiceClient { - - /** Logs user into the system and returns auth token. */ - String login(String username, String password) throws Exception; - - void logout(String token) throws Exception; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestCommandServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestCommandServiceClient.java deleted file mode 100644 index ab45cc0c4e..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestCommandServiceClient.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.common.collect.ImmutableMap; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.workspace.shared.dto.CommandDto; -import org.eclipse.che.dto.server.DtoFactory; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; - -/** @author Musienko Maxim */ -@Singleton -public class TestCommandServiceClient { - private final String apiEndpoint; - private final HttpJsonRequestFactory requestFactory; - - @Inject - public TestCommandServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, HttpJsonRequestFactory requestFactory) { - this.apiEndpoint = apiEndpointProvider.get().toString(); - this.requestFactory = requestFactory; - } - - public void createCommand(String commandLine, String commandName, String commandType, String wsId) - throws Exception { - CommandDto commandDto = DtoFactory.newDto(CommandDto.class); - commandDto.setName(commandName); - commandDto.setType(commandType); - commandDto.setCommandLine(commandLine); - commandDto.setAttributes(ImmutableMap.of("previewUrl", "")); - createCommand(commandDto, wsId); - } - - public void createCommand(CommandDto command, String wsId) throws Exception { - requestFactory - .fromUrl(apiEndpoint + "workspace/" + wsId + "/command") - .usePostMethod() - .setBody(command) - .request(); - } - - public void deleteCommand(String commandName, String wsId) throws Exception { - requestFactory - .fromUrl(apiEndpoint + "workspace/" + wsId + "/command/" + commandName) - .useDeleteMethod() - .request(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestFactoryServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestFactoryServiceClient.java deleted file mode 100644 index 61dbc3ea86..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestFactoryServiceClient.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static java.lang.String.format; -import static java.util.Collections.emptyList; -import static java.util.Optional.ofNullable; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import java.util.List; -import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.core.rest.HttpJsonResponse; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.provider.TestIdeUrlProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** @author Musienko Maxim */ -@Singleton -public class TestFactoryServiceClient { - private static final Logger LOG = LoggerFactory.getLogger(TestFactoryServiceClient.class); - - private final String factoryApiEndpoint; - private final String ideUrl; - private final HttpJsonRequestFactory requestFactory; - - @Inject - public TestFactoryServiceClient( - TestApiEndpointUrlProvider testApiEndpointUrlProvider, - TestIdeUrlProvider ideUrlProvider, - HttpJsonRequestFactory requestFactory) - throws Exception { - this.factoryApiEndpoint = testApiEndpointUrlProvider.get() + "factory/"; - this.ideUrl = ideUrlProvider.get().toString(); - this.requestFactory = requestFactory; - } - - /** - * Creates factory - * - * @param createFactoryDto DTO object to create the factory - * @return URL for the saved factory - */ - public String createFactory(FactoryDto createFactoryDto) throws Exception { - HttpJsonResponse request = - requestFactory - .fromUrl(factoryApiEndpoint) - .usePostMethod() - .setBody(createFactoryDto) - .request(); - - FactoryDto responseDto = - ofNullable(request.asDto(FactoryDto.class)) - .orElseThrow(() -> new RuntimeException("There is a problem creation of factory.")); - - LOG.debug( - "Factory with name='{}' and id='{}' has been created without errors", - responseDto.getName(), - responseDto.getId()); - - return format("%sf?id=%s", ideUrl, responseDto.getId()); - } - - /** - * Search for factories of certain name. - * - * @param name name of factory to find. - * @return List of factory DTOs with certain name. - * @throws ApiException - * @throws IOException - */ - public List findFactory(String name) throws ApiException, IOException { - String queryParamPrefix = "find?name=" + name; - HttpJsonResponse request; - try { - request = requestFactory.fromUrl(factoryApiEndpoint + queryParamPrefix).request(); - } catch (NotFoundException e) { - return emptyList(); - } - - return request.asList(FactoryDto.class); - } - - public void deleteFactory(String name) { - List factories; - try { - factories = findFactory(name); - if (factories.isEmpty()) { - return; - } - } catch (NotFoundException e) { - // ignore in case of there is no factory with certain name - return; - } catch (ApiException | IOException e) { - LOG.error( - format("Error of getting info about factory with name='%s': %s", name, e.getMessage()), - e); - return; - } - - FactoryDto factory = factories.get(0); - try { - requestFactory.fromUrl(factoryApiEndpoint + factory.getId()).useDeleteMethod().request(); - } catch (IOException | ApiException e) { - LOG.error(format("Error of deletion of factory with name='%s': %s", name, e.getMessage()), e); - return; - } - - LOG.info("Factory name='{}' removed", name); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubKeyUploader.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubKeyUploader.java deleted file mode 100644 index 9a89302a1a..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubKeyUploader.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static org.slf4j.LoggerFactory.getLogger; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import org.eclipse.che.api.core.ConflictException; -import org.slf4j.Logger; - -/** @author Dmytro Nochevnov */ -@Singleton -public class TestGitHubKeyUploader { - public static final String GITHUB_COM = "github.com"; - - private static final Logger LOG = getLogger(TestGitHubKeyUploader.class); - - @Inject private TestGitHubServiceClient testGitHubServiceClient; - - @Inject private TestSshServiceClient testSshServiceClient; - - @Inject - @Named("github.username") - private String gitHubUsername; - - @Inject - @Named("github.password") - private String gitHubPassword; - - public synchronized void updateGithubKey() throws Exception { - testSshServiceClient.deleteVCSKey(GITHUB_COM); - - try { - String publicKey = testSshServiceClient.generateVCSKey(GITHUB_COM); - testGitHubServiceClient.uploadPublicKey( - gitHubUsername, gitHubPassword, publicKey, "Eclipse Che Key"); - } catch (ConflictException e) { - // ignore if ssh-key for github.com has already existed - LOG.debug("Ssh key for {} has already existed.", GITHUB_COM); - return; - } - - LOG.debug("Ssh key for {} has been generated.", GITHUB_COM); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubRepository.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubRepository.java deleted file mode 100644 index 6fe217466e..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubRepository.java +++ /dev/null @@ -1,453 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.utils.WaitUtils.sleepQuietly; - -import com.google.inject.Inject; -import com.google.inject.name.Named; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.PreDestroy; -import org.apache.commons.io.IOUtils; -import org.eclipse.che.commons.lang.NameGenerator; -import org.kohsuke.github.GHCommit; -import org.kohsuke.github.GHContent; -import org.kohsuke.github.GHFileNotFoundException; -import org.kohsuke.github.GHRef; -import org.kohsuke.github.GHRepository; -import org.kohsuke.github.GitHub; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This is facade and helper for {@link GHRepository}. - * - * @author Dmytro Nochevnov - */ -public class TestGitHubRepository { - - private static final int GITHUB_OPERATION_TIMEOUT_SEC = 1; - private static final int REPO_CREATION_ATTEMPTS = 6; - - private final String repoName = NameGenerator.generate("EclipseCheTestRepo-", 5); - private static final Logger LOG = LoggerFactory.getLogger(TestGitHubRepository.class); - - private GHRepository ghRepo; - private final GitHub gitHub; - - private final String gitHubUsername; - private final String gitHubPassword; - - private final List submodules = new ArrayList<>(); - - /** - * Creates repository with semi-random name on GitHub for certain {@code gitHubUsername}. Waits - * until repository is really created. - * - * @param gitHubUsername github user name - * @param gitHubPassword github user password - * @throws IOException - */ - @Inject - public TestGitHubRepository( - @Named("github.username") String gitHubUsername, - @Named("github.password") String gitHubPassword) - throws IOException { - gitHub = GitHub.connectUsingPassword(gitHubUsername, gitHubPassword); - ghRepo = create(); - - this.gitHubUsername = gitHubUsername; - this.gitHubPassword = gitHubPassword; - } - - /** - * Gets repository on GitHub with predefined name for certain {@code gitHubUsername}. - * - * @param gitHubUsername github user name - * @param gitHubPassword github user password - * @param repoName name of repo on GitHub - * @throws IOException - */ - public TestGitHubRepository(String gitHubUsername, String gitHubPassword, String repoName) - throws IOException { - gitHub = GitHub.connectUsingPassword(gitHubUsername, gitHubPassword); - ghRepo = gitHub.getRepository(gitHubUsername + "/" + repoName); - - this.gitHubUsername = gitHubUsername; - this.gitHubPassword = gitHubPassword; - } - - public enum TreeElementMode { - BLOB("100644"), - EXECUTABLE_BLOB("100755"), - SUBDIRECTORY("040000"), - SUBMODULE("160000"), - BLOB_SYMLINK("120000"); - - private final String mode; - - TreeElementMode(String mode) { - this.mode = mode; - } - - public String get() { - return this.mode; - } - } - - public enum GitNodeType { - BLOB("blob"), - TREE("tree"), - COMMIT("commit"); - - private final String nodeType; - - GitNodeType(String nodeType) { - this.nodeType = nodeType; - } - - public String get() { - return this.nodeType; - } - } - - public String getName() { - return repoName; - } - - public String getFullName() { - return ghRepo.getFullName(); - } - - public String getSha1(String branchName) throws IOException { - return ghRepo.getBranch(branchName).getSHA1(); - } - - /** - * Creates reference to the new branch with {@code branch} from default branch. - * - * @param branchName name of the branch which should be created - * @return reference to the new branch - * @throws IOException - */ - public GHRef createBranch(String branchName) throws IOException { - GHRef defaultBranch = getReferenceToDefaultBranch(); - return ghRepo.createRef("refs/heads/" + branchName, defaultBranch.getObject().getSha()); - } - - /** - * Creates reference to the new tag with {@code tagName} from default branch. - * - * @param tagName is a name of new tag - * @return reference to the new tag - * @throws IOException - */ - public GHRef createTag(String tagName) throws IOException { - GHRef defaultBranch = getReferenceToDefaultBranch(); - return ghRepo.createRef("refs/tags/" + tagName, defaultBranch.getObject().getSha()); - } - - private GHRef getReferenceToDefaultBranch() throws IOException { - return ghRepo.getRef("heads/" + ghRepo.getDefaultBranch()); - } - - public void setDefaultBranch(String branchName) throws IOException { - ghRepo.setDefaultBranch(branchName); - ghRepo = gitHub.getRepository(ghRepo.getFullName()); - } - - /** - * Copies content of directory {@code pathToRootContentDirectory} to the GitHub repository. It - * tries to recreate the file ones again in case of FileNotFoundException occurs. - * - * @param pathToRootContentDirectory path to the directory with content - * @throws IOException - */ - public void addContent(Path pathToRootContentDirectory) throws IOException { - addContent(pathToRootContentDirectory, null); - } - - /** - * Copies content of directory {@code pathToRootContentDirectory} to the specified branch in the - * GitHub repository. It tries to recreate the file ones again in case of FileNotFoundException - * occurs. - * - * @param pathToRootContentDirectory path to the directory with content - * @param branch name of the target branch - * @throws IOException - */ - public void addContent(Path pathToRootContentDirectory, String branch) throws IOException { - Files.walk(pathToRootContentDirectory) - .filter(Files::isRegularFile) - .forEach( - pathToFile -> { - try { - createFile(pathToRootContentDirectory, pathToFile, branch); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }); - } - - /** - * Changes content of the file - * - * @param pathToFile path to specified file - * @param content content to change - * @throws IOException - */ - public void changeFileContent(String pathToFile, String content) throws IOException { - changeFileContent(pathToFile, content, format("Change file %s", pathToFile)); - } - - /** - * Changes content of the file - * - * @param pathToFile path to specified file - * @param content content to change - * @param commitMessage message to commit - * @throws IOException - */ - public void changeFileContent(String pathToFile, String content, String commitMessage) - throws IOException { - ghRepo.getFileContent(String.format("/%s", pathToFile)).update(content, commitMessage); - } - - public void deleteFile(String pathToFile) throws IOException { - ghRepo.getFileContent(pathToFile).delete("Delete file " + pathToFile); - } - - /** - * Delete folder with content inside the repository on GitHub. - * - * @param folder folder to delete - * @param deleteCommitMessage commit message which is used to delete the message - * @throws IOException - */ - public void deleteFolder(Path folder, String deleteCommitMessage) throws IOException { - for (GHContent ghContent : ghRepo.getDirectoryContent(folder.toString())) { - ghContent.delete(deleteCommitMessage); - } - } - - @PreDestroy - public void delete() { - try { - ghRepo.delete(); - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); - } - - submodules.forEach(TestGitHubRepository::delete); - LOG.info("GitHub repo {} has been removed", ghRepo.getHtmlUrl()); - } - - public static void deleteAllRepos(String repoPrefix, String gitHubUsername, String gitHubPassword) - throws IOException { - GitHub gitHub = GitHub.connectUsingPassword(gitHubUsername, gitHubPassword); - - gitHub - .getMyself() - .getAllRepositories() - .keySet() - .stream() - .filter(repoName -> repoName.startsWith(repoPrefix)) - .forEach( - repoName -> { - String repoAddress = gitHubUsername + "/" + repoName; - LOG.info("Removing repo " + repoAddress + "..."); - try { - gitHub.getRepository(repoAddress).delete(); - } catch (IOException e) { - e.printStackTrace(); - } - }); - } - - public String getHtmlUrl() { - return ghRepo.getHtmlUrl().toString(); - } - - public String getHttpsTransportUrl() { - return ghRepo.gitHttpTransportUrl(); - } - - public String getSshUrl() { - return ghRepo.getSshUrl(); - } - - private GHRepository create() throws IOException { - GHRepository repo = gitHub.createRepository(repoName).create(); - ensureRepositoryCreated(repo, System.currentTimeMillis()); - - LOG.info("GitHub repo {} has been created", repo.getHtmlUrl()); - return repo; - } - - private void ensureRepositoryCreated(GHRepository repo, long startCreationTimeInMillisec) - throws IOException { - Throwable lastIOException = null; - for (int i = 0; i < REPO_CREATION_ATTEMPTS; i++) { - try { - gitHub.getRepository(repo.getFullName()); - return; - } catch (IOException e) { - lastIOException = e; - LOG.info("Waiting for {} to be created", repo.getHtmlUrl()); - sleepQuietly(GITHUB_OPERATION_TIMEOUT_SEC); // sleep one second - } - } - - long durationOfRepoCreationInSec = - (System.currentTimeMillis() - startCreationTimeInMillisec) / 1000; - - throw new IOException( - format( - "GitHub repo %s hasn't been created in %s seconds", - repo.getHtmlUrl(), durationOfRepoCreationInSec), - lastIOException); - } - - /** - * Creates file in GitHub repository in the specified {@code branch}. - * - * @param pathToRootContentDirectory path to the root directory of file locally - * @param pathToFile path to file locally - * @param branch name of the target branch - * @throws IOException - */ - private void createFile(Path pathToRootContentDirectory, Path pathToFile, String branch) - throws IOException { - byte[] contentBytes = Files.readAllBytes(pathToFile); - String relativePath = pathToRootContentDirectory.relativize(pathToFile).toString(); - String commitMessage = String.format("Add file %s", relativePath); - - try { - ghRepo.createContent(contentBytes, commitMessage, relativePath, branch); - } catch (GHFileNotFoundException e) { - // try to create content once again - LOG.warn( - "Error of creation of {} occurred. Is trying to create it once again...", - ghRepo.getHtmlUrl() + "/" + relativePath); - sleepQuietly(GITHUB_OPERATION_TIMEOUT_SEC); - ghRepo.createContent(contentBytes, commitMessage, relativePath); - } - } - - public String getFileContent(String pathToFile) throws IOException { - return IOUtils.toString(ghRepo.getFileContent(pathToFile).read(), "UTF-8"); - } - - public String getDefaultBranchSha() throws IOException { - return getReferenceToDefaultBranch().getObject().getSha(); - } - - public void addSubmodule(Path pathToRootContentDirectory, String submoduleName) - throws IOException { - - TestGitHubRepository submodule = new TestGitHubRepository(gitHubUsername, gitHubPassword); - submodule.addContent(pathToRootContentDirectory); - createSubmodule(submodule, submoduleName); - submodules.add(submodule); - } - - private void createSubmodule( - TestGitHubRepository pathToRootContentDirectory, String pathForSubmodule) throws IOException { - String submoduleSha = createTreeWithSubmodule(pathToRootContentDirectory, pathForSubmodule); - - GHCommit treeCommit = - ghRepo.createCommit().tree(submoduleSha).message("Create submodule").create(); - - getReferenceToDefaultBranch().updateTo(treeCommit.getSHA1(), true); - setupSubmoduleConfig(pathToRootContentDirectory, pathForSubmodule); - } - - private boolean isGitmodulesFileExist() throws IOException { - return 0 - < ghRepo - .getDirectoryContent("") - .stream() - .filter(item -> item.getName().equals(".gitmodules")) - .count(); - } - - private String createTreeWithSubmodule(TestGitHubRepository submodule, String pathForSubmodule) - throws IOException { - return ghRepo - .createTree() - .baseTree(this.getDefaultBranchSha()) - .entry( - pathForSubmodule, - TreeElementMode.SUBMODULE.get(), - GitNodeType.COMMIT.get(), - submodule.getDefaultBranchSha(), - null) - .create() - .getSha(); - } - - private String getSubmoduleConfig(TestGitHubRepository submodule, String pathToSubmoduleContent) { - String repoName = Paths.get(pathToSubmoduleContent).getFileName().toString(); - String repoUrl = submodule.getHtmlUrl() + ".git"; - String modulePattern = "[submodule \"%s\"]\n\tpath = %s\n\turl = %s"; - - return String.format(modulePattern, repoName, pathToSubmoduleContent, repoUrl); - } - - /** - * Creates ".gitmodules" file or updates if it already exist. - * - * @see gitmodules - */ - private void setupSubmoduleConfig(TestGitHubRepository submodule, String pathToSubmoduleContent) - throws IOException { - final String gitmodulesFileName = ".gitmodules"; - String submoduleConfig = getSubmoduleConfig(submodule, pathToSubmoduleContent); - - if (isGitmodulesFileExist()) { - GHContent submoduleFileContent = ghRepo.getFileContent(gitmodulesFileName); - String newFileContent = getFileContent(gitmodulesFileName) + "\n" + submoduleConfig; - - submoduleFileContent.update(newFileContent, "Update " + gitmodulesFileName); - return; - } - - ghRepo.createContent(submoduleConfig, "Add " + gitmodulesFileName, gitmodulesFileName); - } - - public String getPullRequestTitle(int requestNumber) throws IOException { - return ghRepo.getPullRequest(requestNumber).getTitle(); - } - - public String getPullRequestBaseBranchName(int requestNumber) throws IOException { - return ghRepo.getPullRequest(requestNumber).getBase().getRef(); - } - - public String getPullRequestHeadBranchName(int requestNumber) throws IOException { - return ghRepo.getPullRequest(requestNumber).getHead().getRef(); - } - - public String getPullRequestBody(int requestNumber) throws IOException { - return ghRepo.getPullRequest(requestNumber).getBody(); - } - - public String getPullRequestUserName(int requestNumber) throws IOException { - return ghRepo.getPullRequest(requestNumber).getUser().getLogin(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubServiceClient.java deleted file mode 100644 index d796c75026..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestGitHubServiceClient.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static java.util.Optional.ofNullable; -import static java.util.stream.Collectors.toList; -import static org.eclipse.che.dto.server.DtoFactory.newDto; -import static org.slf4j.LoggerFactory.getLogger; - -import com.google.common.collect.ImmutableMap; -import com.google.common.reflect.TypeToken; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.Base64; -import java.util.List; -import java.util.Map; -import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.core.rest.HttpJsonResponse; -import org.eclipse.che.dto.server.JsonStringMapImpl; -import org.slf4j.Logger; - -/** @author Mihail Kuznyetsov. */ -@Singleton -public class TestGitHubServiceClient { - private static final Logger LOG = getLogger(TestGitHubServiceClient.class); - - private final HttpJsonRequestFactory requestFactory; - - @Inject - public TestGitHubServiceClient(HttpJsonRequestFactory requestFactory) { - this.requestFactory = requestFactory; - } - - public void deletePublicKeys(final String username, final String password, final String keyTitle) - throws Exception { - List keys = getPublicKeys(username, password, keyTitle); - for (GitHubKey key : keys) { - requestFactory - .fromUrl(key.getUrl()) - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .useDeleteMethod() - .request(); - } - } - - public void createPublicKey(final String username, final String password, final GitHubKey key) - throws Exception { - requestFactory - .fromUrl("https://api.github.com/user/keys") - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .usePostMethod() - .setBody(key) - .request(); - } - - public void uploadPublicKey( - final String username, final String password, final String key, String keyTitle) - throws Exception { - - GitHubKey publicSshKey = newDto(GitHubKey.class); - publicSshKey.setTitle(keyTitle); - publicSshKey.setKey(key); - - deletePublicKeys(username, password, keyTitle); - createPublicKey(username, password, publicSshKey); - } - - public List getPublicKeys( - final String username, final String password, final String title) throws Exception { - List keys = - requestFactory - .fromUrl("https://api.github.com/user/keys") - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .useGetMethod() - .request() - .asList(GitHubKey.class); - - return keys.stream().filter(key -> title.equals(key.getTitle())).collect(toList()); - } - - public void hardResetHeadToCommit( - final String repository, final String commitSha, final String username, final String password) - throws Exception { - ImmutableMap m = ImmutableMap.of("sha", commitSha, "force", true); - - String url = - "https://api.github.com/repos/" + username + "/" + repository + "/git/refs/heads/master"; - requestFactory - .fromUrl(url) - .usePostMethod() - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .setBody(new JsonStringMapImpl(m)) - .request(); - } - - @SuppressWarnings("unchecked") - public List getNumbersOfOpenedPullRequests( - final String repository, final String username, final String password) throws Exception { - String url = "https://api.github.com/repos/" + username + "/" + repository + "/pulls"; - HttpJsonResponse response = - requestFactory - .fromUrl(url) - .useGetMethod() - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .request(); - List> prs = - response.as(List.class, new TypeToken>>() {}.getType()); - return prs.stream() - .filter(g -> g.get("state").equals("open")) - .map(g -> g.get("number")) - .collect(toList()); - } - - public void closePullRequest( - final String repo, final String number, final String username, final String password) - throws Exception { - String url = "https://api.github.com/repos/" + username + "/" + repo + "/pulls/" + number; - requestFactory - .fromUrl(url) - .usePostMethod() - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .setBody(ImmutableMap.of("state", "close")) - .request(); - } - - public void deleteBranch( - final String repository, - final String branchName, - final String username, - final String password) - throws Exception { - String url = - "https://api.github.com/repos/" - + username - + "/" - + repository - + "/git/refs/heads/" - + branchName; - requestFactory - .fromUrl(url) - .useDeleteMethod() - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .request(); - } - - public void deleteRepo(final String repository, final String username, final String password) - throws Exception { - String url = "https://api.github.com/repos/" + username + "/" + repository; - requestFactory - .fromUrl(url) - .useDeleteMethod() - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .request(); - } - - public List getAllGrants(final String username, final String password) throws Exception { - String url = "https://api.github.com/applications/grants"; - HttpJsonResponse response = - requestFactory - .fromUrl(url) - .useGetMethod() - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .request(); - @SuppressWarnings("unchecked") - List> grants = - response.as(List.class, new TypeToken>>() {}.getType()); - - return grants.stream().map(g -> g.get("id")).collect(toList()); - } - - public void deleteAllGrants(final String username, final String password) throws Exception { - List grandsId = getAllGrants(username, password); - for (String grandId : grandsId) { - String url = "https://api.github.com/applications/grants/" + grandId; - requestFactory - .fromUrl(url) - .useDeleteMethod() - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .request(); - } - - LOG.debug("Application grants '{}' were removed from github.com", grandsId); - } - - public String getName(final String username, final String password) - throws IOException, ApiException { - String url = "https://api.github.com/users/" + username; - HttpJsonResponse response = - requestFactory - .fromUrl(url) - .useGetMethod() - .setAuthorizationHeader(createBasicAuthHeader(username, password)) - .request(); - - return obtainNameFromResponse(response); - } - - /** - * Obtain name of github user from github response - * - * @param response - * @return name if it presents in response and != null, or login otherwise. - */ - private String obtainNameFromResponse(HttpJsonResponse response) throws IOException { - Map properties = response.asProperties(); - String login = properties.get("login"); - return ofNullable(properties.getOrDefault("name", login)).orElse(login); - } - - private String createBasicAuthHeader(String username, String password) - throws UnsupportedEncodingException { - byte[] nameAndPass = (username + ":" + password).getBytes("UTF-8"); - String base64 = Base64.getEncoder().encodeToString(nameAndPass); - return "Basic " + base64; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestMachineServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestMachineServiceClient.java deleted file mode 100644 index 051a414021..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestMachineServiceClient.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -/** @author Musienko Maxim */ -public interface TestMachineServiceClient { - - /** - * Returns machine token for current workspace - * - * @param authToken the authorization token - * @param workspaceId the workspace id - * @return the machine token for current workspace - */ - String getMachineApiToken(String workspaceId) throws Exception; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestOrganizationServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestOrganizationServiceClient.java deleted file mode 100644 index 4136249226..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestOrganizationServiceClient.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static org.eclipse.che.dto.server.DtoFactory.newDto; - -import com.google.inject.assistedinject.Assisted; -import com.google.inject.assistedinject.AssistedInject; -import java.util.List; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.commons.annotation.Nullable; -import org.eclipse.che.multiuser.api.permission.shared.dto.PermissionsDto; -import org.eclipse.che.multiuser.organization.shared.dto.OrganizationDto; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.TestUserHttpJsonRequestFactoryCreator; -import org.eclipse.che.selenium.core.user.TestUser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** This util is handling the requests to Organization API. */ -public class TestOrganizationServiceClient { - private static final Logger LOG = LoggerFactory.getLogger(TestOrganizationServiceClient.class); - - private final String apiEndpoint; - private final HttpJsonRequestFactory requestFactory; - - public TestOrganizationServiceClient( - TestApiEndpointUrlProvider apiEndpointUrlProvider, HttpJsonRequestFactory requestFactory) { - this.apiEndpoint = apiEndpointUrlProvider.get().toString(); - this.requestFactory = requestFactory; - } - - @AssistedInject - public TestOrganizationServiceClient( - TestApiEndpointUrlProvider apiEndpointUrlProvider, - TestUserHttpJsonRequestFactoryCreator testUserHttpJsonRequestFactoryCreator, - @Assisted TestUser testUser) { - this.apiEndpoint = apiEndpointUrlProvider.get().toString(); - this.requestFactory = testUserHttpJsonRequestFactoryCreator.create(testUser); - } - - public List getAll() throws Exception { - return requestFactory.fromUrl(getApiUrl()).request().asList(OrganizationDto.class); - } - - public List getAllRoot() throws Exception { - List organizations = - requestFactory.fromUrl(getApiUrl()).request().asList(OrganizationDto.class); - - organizations.removeIf(o -> o.getParent() != null); - return organizations; - } - - private String getApiUrl() { - return apiEndpoint + "organization/"; - } - - public OrganizationDto create(String name, @Nullable String parentId) throws Exception { - OrganizationDto data = newDto(OrganizationDto.class).withName(name).withParent(parentId); - - OrganizationDto organizationDto = - requestFactory - .fromUrl(getApiUrl()) - .setBody(data) - .usePostMethod() - .request() - .asDto(OrganizationDto.class); - - LOG.info( - "Organization with name='{}', id='{}', parent's id='{}' created", - name, - organizationDto.getId(), - parentId); - - return organizationDto; - } - - public OrganizationDto create(String name) throws Exception { - return create(name, null); - } - - public void deleteById(String id) throws Exception { - String apiUrl = format("%s%s", getApiUrl(), id); - - try { - requestFactory.fromUrl(apiUrl).useDeleteMethod().request(); - LOG.info("Organization with id='{}' removed", id); - } catch (NotFoundException e) { - // ignore if there is no organization of certain id - } - } - - public void deleteByName(String name) throws Exception { - try { - String organizationId = get(name).getId(); - deleteById(organizationId); - } catch (NotFoundException e) { - // ignore if there is no organization of certain id - } - } - - public void deleteAll() throws Exception { - getAll() - .stream() - .filter(organization -> organization.getParent() != null) - .forEach( - organization -> { - try { - deleteById(organization.getId()); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - }); - } - - public OrganizationDto get(String organizationName) throws Exception { - String apiUrl = format("%sfind?name=%s", getApiUrl(), organizationName); - return requestFactory.fromUrl(apiUrl).request().asDto(OrganizationDto.class); - } - - public void addMember(String organizationId, String userId) throws Exception { - addMember(organizationId, userId, asList("createWorkspaces")); - } - - public void addAdmin(String organizationId, String userId) throws Exception { - addMember( - organizationId, - userId, - asList( - "update", - "setPermissions", - "manageResources", - "manageWorkspaces", - "createWorkspaces", - "delete", - "manageSuborganizations")); - } - - public void addMember(String organizationId, String userId, List actions) - throws Exception { - String apiUrl = apiEndpoint + "permissions"; - PermissionsDto data = - newDto(PermissionsDto.class) - .withDomainId("organization") - .withInstanceId(organizationId) - .withUserId(userId) - .withActions(actions); - - requestFactory.fromUrl(apiUrl).setBody(data).usePostMethod().request(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestOrganizationServiceClientFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestOrganizationServiceClientFactory.java deleted file mode 100644 index 04f0136560..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestOrganizationServiceClientFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.assistedinject.Assisted; -import org.eclipse.che.selenium.core.user.TestUser; - -/** @author Dmytro Nochevnov */ -public interface TestOrganizationServiceClientFactory { - TestOrganizationServiceClient create(@Assisted TestUser testUser); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestProfileServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestProfileServiceClient.java deleted file mode 100644 index cdd4cc1561..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestProfileServiceClient.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.common.collect.ImmutableMap; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.Map; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.user.DefaultTestUser; - -/** @author Musienko Maxim */ -@Singleton -public class TestProfileServiceClient { - private final String apiEndpoint; - private final HttpJsonRequestFactory requestFactory; - private final DefaultTestUser defaultTestUser; - - @Inject - public TestProfileServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, - HttpJsonRequestFactory requestFactory, - DefaultTestUser defaultTestUser) { - this.apiEndpoint = apiEndpointProvider.get().toString(); - this.requestFactory = requestFactory; - this.defaultTestUser = defaultTestUser; - } - - public void setAttributes(Map attributes) throws Exception { - requestFactory - .fromUrl(apiEndpoint + "profile/attributes") - .usePutMethod() - .setBody(attributes) - .request(); - } - - public void setUserNames(String name, String lastName) throws Exception { - Map attributes = - ImmutableMap.of( - "firstName", name, - "lastName", lastName); - - setAttributes(attributes); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestProjectServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestProjectServiceClient.java deleted file mode 100644 index fec22e50a5..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestProjectServiceClient.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static com.google.common.base.Charsets.UTF_8; -import static com.google.common.io.Resources.getResource; -import static com.google.common.io.Resources.toByteArray; -import static java.lang.String.format; -import static java.nio.file.Files.createFile; -import static java.nio.file.Files.write; -import static java.util.Optional.ofNullable; -import static org.eclipse.che.dto.server.DtoFactory.getInstance; -import static org.eclipse.che.selenium.core.project.ProjectTemplates.PLAIN_JAVA; - -import com.google.common.io.Resources; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.zip.ZipOutputStream; -import org.eclipse.che.api.core.model.workspace.config.ProjectConfig; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; -import org.eclipse.che.api.workspace.shared.dto.SourceStorageDto; -import org.eclipse.che.commons.lang.IoUtil; -import org.eclipse.che.commons.lang.ZipUtils; -import org.eclipse.che.selenium.core.provider.TestWorkspaceAgentApiEndpointUrlProvider; - -/** - * @author Musienko Maxim - * @author Mykola Morhun - */ -@Singleton -public class TestProjectServiceClient { - - private static final String BEARER_TOKEN_PREFIX = "Bearer "; - private final TestMachineServiceClient machineServiceClient; - private final HttpJsonRequestFactory requestFactory; - private final TestWorkspaceAgentApiEndpointUrlProvider workspaceAgentApiEndpointUrlProvider; - - @Inject - public TestProjectServiceClient( - TestMachineServiceClient machineServiceClient, - HttpJsonRequestFactory requestFactory, - TestWorkspaceAgentApiEndpointUrlProvider workspaceAgentApiEndpointUrlProvider) { - this.machineServiceClient = machineServiceClient; - this.requestFactory = requestFactory; - this.workspaceAgentApiEndpointUrlProvider = workspaceAgentApiEndpointUrlProvider; - } - - /** Set type for existing project on vfs */ - public void setProjectType(String workspaceId, String template, String projectName) - throws Exception { - InputStream in = getClass().getResourceAsStream("/templates/project/" + template); - String json = IoUtil.readAndCloseQuietly(in); - - ProjectConfigDto project = getInstance().createDtoFromJson(json, ProjectConfigDto.class); - project.setName(projectName); - - requestFactory - .fromUrl(workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/" + projectName) - .usePutMethod() - .setAuthorizationHeader( - BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) - .setBody(project) - .request(); - } - - /** Delete resource. */ - public void deleteResource(String workspaceId, String path) throws Exception { - requestFactory - .fromUrl(workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/" + path) - .setAuthorizationHeader( - BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) - .useDeleteMethod() - .request(); - } - - public void createFolder(String workspaceId, String folder) throws Exception { - String url = workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/folder/" + folder; - requestFactory - .fromUrl(url) - .setAuthorizationHeader( - BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) - .usePostMethod() - .request(); - } - - /** Import zip project from file system into user workspace. */ - public void importZipProject( - String workspaceId, Path zipFile, String projectName, String template) throws Exception { - String url = - workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/import/" + projectName; - // createFolder(workspaceId, projectName); - - HttpURLConnection httpConnection = null; - try { - httpConnection = (HttpURLConnection) new URL(url).openConnection(); - httpConnection.setRequestMethod("POST"); - httpConnection.setRequestProperty("Content-Type", "application/zip"); - httpConnection.addRequestProperty( - "Authorization", - BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)); - httpConnection.setDoOutput(true); - - try (OutputStream outputStream = httpConnection.getOutputStream()) { - Files.copy(zipFile, outputStream); - if (httpConnection.getResponseCode() != 201) { - throw new RuntimeException( - "Cannot deploy requested project using ProjectServiceClient REST API. Server response " - + httpConnection.getResponseCode() - + " " - + IoUtil.readStream(httpConnection.getErrorStream()) - + "REST url: " - + url); - } - } - } finally { - ofNullable(httpConnection).ifPresent(HttpURLConnection::disconnect); - } - - setProjectType(workspaceId, template, projectName); - } - - /** Import project from file system into a user workspace */ - public void importProject( - String workspaceId, Path sourceFolder, String projectName, String template) throws Exception { - - if (!Files.exists(sourceFolder)) { - throw new IOException(format("%s not found", sourceFolder)); - } - - if (!Files.isDirectory(sourceFolder)) { - throw new IOException(format("%s not a directory", sourceFolder)); - } - - Path zip = Files.createTempFile("project", projectName); - try (ZipOutputStream out = ZipUtils.stream(zip)) { - ZipUtils.add(out, sourceFolder, sourceFolder); - if (PLAIN_JAVA.equals(template)) { - Path tmpDir = Files.createTempDirectory("TestProject"); - Path dotClasspath = createFile(tmpDir.resolve(".classpath")); - Path dotProject = Files.createFile(tmpDir.resolve(".project")); - write( - dotProject, - format( - Resources.toString(getResource("projects/jdt-ls-project-files/project"), UTF_8), - projectName) - .getBytes(UTF_8)); - write(dotClasspath, toByteArray(getResource("projects/jdt-ls-project-files/classpath"))); - ZipUtils.add(out, dotClasspath); - ZipUtils.add(out, dotProject); - } - } - - importZipProject(workspaceId, zip, projectName, template); - } - - /** Import project from file system into a user workspace */ - public void importProject( - String workspaceId, - String projectName, - String location, - String type, - Map parameters) - throws Exception { - SourceStorageDto source = getInstance().createDto(SourceStorageDto.class); - source.setLocation(location); - source.setType(type); - source.setParameters(parameters); - - importProject(workspaceId, projectName, source); - } - - /** Import project from file system into a user workspace */ - public void importProject(String workspaceId, String projectName, SourceStorageDto source) - throws Exception { - - requestFactory - .fromUrl( - workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/import/" + projectName) - .usePostMethod() - .setAuthorizationHeader(machineServiceClient.getMachineApiToken(workspaceId)) - .setBody(source) - .request(); - } - - /** Creates file in the project. */ - public void createFileInProject( - String workspaceId, String parentFolder, String fileName, String content) throws Exception { - String apiRESTUrl = - workspaceAgentApiEndpointUrlProvider.get(workspaceId) - + "project/file/" - + parentFolder - + "?name=" - + fileName; - - HttpURLConnection httpConnection = null; - try { - httpConnection = (HttpURLConnection) new URL(apiRESTUrl).openConnection(); - httpConnection.setRequestMethod("POST"); - httpConnection.setRequestProperty("Content-Type", "text/plain"); - httpConnection.addRequestProperty( - "Authorization", - BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)); - httpConnection.setDoOutput(true); - try (OutputStream output = httpConnection.getOutputStream()) { - output.write(content.getBytes("UTF-8")); - if (httpConnection.getResponseCode() != 201) { - throw new RuntimeException( - "Cannot create requested content in the current project: " - + apiRESTUrl - + " something went wrong " - + httpConnection.getResponseCode() - + IoUtil.readStream(httpConnection.getErrorStream())); - } - } - } finally { - ofNullable(httpConnection).ifPresent(HttpURLConnection::disconnect); - } - } - - public ProjectConfigDto getFirstProject(String workspaceId) throws Exception { - String apiUrl = workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project"; - return requestFactory - .fromUrl(apiUrl) - .setAuthorizationHeader( - BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) - .request() - .asList(ProjectConfigDto.class) - .get(0); - } - - /** Updates file content. */ - public void updateFile(String workspaceId, String pathToFile, String content) throws Exception { - String url = - workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/file/" + pathToFile; - - HttpURLConnection httpConnection = null; - try { - httpConnection = (HttpURLConnection) new URL(url).openConnection(); - httpConnection.setRequestMethod("PUT"); - httpConnection.setRequestProperty("Content-Type", "text/plain"); - httpConnection.addRequestProperty( - "Authorization", - BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)); - httpConnection.setDoOutput(true); - - try (OutputStream output = httpConnection.getOutputStream()) { - output.write(content.getBytes("UTF-8")); - if (httpConnection.getResponseCode() != 200) { - throw new RuntimeException( - "Cannot update content in the current file: " - + url - + " something went wrong " - + httpConnection.getResponseCode() - + IoUtil.readStream(httpConnection.getErrorStream())); - } - } - } finally { - ofNullable(httpConnection).ifPresent(HttpURLConnection::disconnect); - } - } - - public boolean checkProjectType(String wokspaceId, String projectName, String projectType) - throws Exception { - return getProject(wokspaceId, projectName).getType().equals(projectType); - } - - public boolean checkProjectLanguage(String workspaceId, String projectName, String language) - throws Exception { - - return getProject(workspaceId, projectName).getAttributes().get("language").contains(language); - } - - public boolean checkProjectLanguage( - String workspaceId, String projectName, List languages) throws Exception { - - return getProject(workspaceId, projectName) - .getAttributes() - .get("language") - .containsAll(languages); - } - - public List getExternalLibraries(String workspaceId, String projectName) - throws Exception { - return requestFactory - .fromUrl( - workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "java/navigation/libraries") - .useGetMethod() - .addQueryParam("projectpath", "/" + projectName) - .request() - .asList(ProjectConfigDto.class) - .stream() - .map(e -> e.getName()) - .collect(Collectors.toList()); - } - - private ProjectConfig getProject(String workspaceId, String projectName) throws Exception { - return requestFactory - .fromUrl(workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/" + projectName) - .useGetMethod() - .setAuthorizationHeader( - BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) - .request() - .asDto(ProjectConfigDto.class); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestSshServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestSshServiceClient.java deleted file mode 100644 index 519e1d6033..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestSshServiceClient.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static java.lang.String.format; -import static org.eclipse.che.dto.server.DtoFactory.newDto; -import static org.slf4j.LoggerFactory.getLogger; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.List; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.core.rest.HttpJsonResponse; -import org.eclipse.che.api.ssh.shared.dto.GenerateSshPairRequest; -import org.eclipse.che.api.ssh.shared.dto.SshPairDto; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.slf4j.Logger; - -/** @author Musienko Maxim */ -@Singleton -public class TestSshServiceClient { - private static final Logger LOG = getLogger(TestSshServiceClient.class); - private static final String MACHINE_SERVICE = "machine"; - private static final String VCS_SERVICE = "vcs"; - - private final String apiEndpoint; - private final HttpJsonRequestFactory requestFactory; - - @Inject - public TestSshServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, HttpJsonRequestFactory requestFactory) { - this.apiEndpoint = apiEndpointProvider.get().toString(); - this.requestFactory = requestFactory; - } - - public String getPrivateMachineKey(String keyName) throws Exception { - HttpJsonResponse request = - requestFactory - .fromUrl(format("%sssh/%s/?name=%s", apiEndpoint, MACHINE_SERVICE, keyName)) - .useGetMethod() - .request(); - List sshPair = request.asList(SshPairDto.class); - return sshPair.isEmpty() ? null : sshPair.get(0).getPrivateKey(); - } - - public String generateVCSKey(String keyName) throws Exception { - GenerateSshPairRequest generateSshKeyData = - newDto(GenerateSshPairRequest.class).withName(keyName).withService(VCS_SERVICE); - - HttpJsonResponse response = - requestFactory - .fromUrl(apiEndpoint + "ssh/generate") - .usePostMethod() - .setBody(generateSshKeyData) - .request(); - return response.asDto(SshPairDto.class).getPublicKey(); - } - - public void deleteVCSKey(String keyName) throws Exception { - deleteKey(VCS_SERVICE, keyName); - } - - private void deleteKey(String serviceName, String keyName) throws Exception { - try { - requestFactory - .fromUrl(format("%sssh/%s/?name=%s", apiEndpoint, serviceName, keyName)) - .useDeleteMethod() - .request(); - } catch (NotFoundException e) { - // ignore absence of key - LOG.debug("Ssh key for '{}' with name '{}' is absent.", serviceName, keyName); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserPreferencesServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserPreferencesServiceClient.java deleted file mode 100644 index d597bf753d..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserPreferencesServiceClient.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.ConflictException; -import org.eclipse.che.api.core.ForbiddenException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.core.UnauthorizedException; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.core.rest.HttpJsonResponse; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; - -/** @author Musienko Maxim */ -@Singleton -public class TestUserPreferencesServiceClient { - - private static final String ACTIVATE_CONTRIBUTION_TAB_BY_PROJECT_SELECTION_PROPERTY = - "git.contribute.activate.projectSelection"; - private final String apiEndpoint; - private final HttpJsonRequestFactory httpRequestFactory; - - @Inject - public TestUserPreferencesServiceClient( - TestApiEndpointUrlProvider apiEndpointProvider, HttpJsonRequestFactory httpRequestFactory) - throws Exception { - this.apiEndpoint = apiEndpointProvider.get().toString(); - this.httpRequestFactory = httpRequestFactory; - - // Set application.confirmExit property to 'never' to avoid web page closing confirmation pop-up - this.setProperty("theia-user-preferences", "{\"application.confirmExit\":\"never\"}"); - } - - public void addGitCommitter(String committerName, String committerEmail) throws Exception { - httpRequestFactory - .fromUrl(apiEndpoint + "preferences") - .usePutMethod() - .setBody( - ImmutableMap.of( - "git.committer.name", committerName, - "git.committer.email", committerEmail)) - .request(); - } - - public HttpJsonResponse setProperty(String propertyName, String propertyValue) throws Exception { - return httpRequestFactory - .fromUrl(apiEndpoint + "preferences") - .usePutMethod() - .setBody(ImmutableMap.of(propertyName, propertyValue)) - .request(); - } - - public String getPreferences() throws Exception { - return httpRequestFactory - .fromUrl(apiEndpoint + "preferences") - .useGetMethod() - .request() - .asString(); - } - - public void restoreDefaultContributionTabPreference() - throws ForbiddenException, BadRequestException, IOException, ConflictException, - NotFoundException, ServerException, UnauthorizedException { - httpRequestFactory - .fromUrl(apiEndpoint + "preferences") - .useDeleteMethod() - .setBody(ImmutableList.of(ACTIVATE_CONTRIBUTION_TAB_BY_PROJECT_SELECTION_PROPERTY)) - .request(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClient.java deleted file mode 100644 index 58e3dee11c..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClient.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.ConflictException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.core.model.user.User; - -/** - * @author Mihail Kuznyetsov - * @author Anton Korneta - */ -public interface TestUserServiceClient { - - /** - * Creates user form provided data. - * - * @param name user name - * @param email user email - * @param password user password - * @throws BadRequestException when user data validation failed - * @throws ConflictException when user with given email/name exists - * @throws ServerException when any other exception occurs - */ - void create(String name, String email, String password) - throws BadRequestException, ConflictException, ServerException; - - /** - * Gets user by id. - * - * @param id user identifier - * @return user with given identifier - * @throws NotFoundException when user with given id not found - * @throws ServerException when any other exception occurs - */ - User getById(String id) throws NotFoundException, ServerException; - - /** - * Gets user by email. - * - * @param email user email - * @return user with given email - * @throws BadRequestException when specified email is null or empty - * @throws NotFoundException User with requested email not found - * @throws ServerException when any other exception occurs - */ - User findByEmail(String email) throws NotFoundException, ServerException, BadRequestException; - - /** - * Gets user by name. - * - * @param name user name - * @return user with given name - * @throws BadRequestException when specified name is null or empty - * @throws NotFoundException User with requested name not found - * @throws ServerException when any other exception occurs - */ - User findByName(String name) throws NotFoundException, ServerException, BadRequestException; - - /** - * Deletes user by its id. - * - * @param id user identifier - * @throws ConflictException when conflicts occurs e.g. user has related entities - * @throws ServerException when any other exception occurs - */ - void remove(String id) throws ServerException, ConflictException; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClientFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClientFactory.java deleted file mode 100644 index a84f37b4a2..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClientFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.assistedinject.Assisted; -import org.eclipse.che.selenium.core.user.TestUser; - -/** @author Dmytro Nochevnov */ -public interface TestUserServiceClientFactory { - TestUserServiceClientImpl create(@Assisted TestUser testUser); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClientImpl.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClientImpl.java deleted file mode 100644 index 3737343b04..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestUserServiceClientImpl.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import static org.eclipse.che.dto.server.DtoFactory.newDto; - -import com.google.inject.assistedinject.Assisted; -import com.google.inject.assistedinject.AssistedInject; -import java.io.IOException; -import java.net.URLEncoder; -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.ConflictException; -import org.eclipse.che.api.core.ForbiddenException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.api.core.UnauthorizedException; -import org.eclipse.che.api.core.model.user.User; -import org.eclipse.che.api.user.shared.dto.UserDto; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.TestHttpJsonRequestFactory; -import org.eclipse.che.selenium.core.requestfactory.TestUserHttpJsonRequestFactory; -import org.eclipse.che.selenium.core.requestfactory.TestUserHttpJsonRequestFactoryCreator; -import org.eclipse.che.selenium.core.user.TestUser; - -/** @author Musienko Maxim */ -public class TestUserServiceClientImpl implements TestUserServiceClient { - - private final String userServiceEndpoint; - private final TestHttpJsonRequestFactory requestFactory; - - public TestUserServiceClientImpl( - TestApiEndpointUrlProvider apiEndpointProvider, - TestUserHttpJsonRequestFactory userHttpJsonRequestFactory) { - this.userServiceEndpoint = apiEndpointProvider.get().toString() + "user/"; - this.requestFactory = userHttpJsonRequestFactory; - } - - @AssistedInject - public TestUserServiceClientImpl( - TestApiEndpointUrlProvider apiEndpointProvider, - TestUserHttpJsonRequestFactoryCreator userHttpJsonRequestFactoryCreator, - @Assisted TestUser testUser) { - this(apiEndpointProvider, userHttpJsonRequestFactoryCreator.create(testUser)); - } - - @Override - public void create(String name, String email, String password) - throws BadRequestException, ConflictException, ServerException { - try { - requestFactory - .fromUrl(userServiceEndpoint) - .usePostMethod() - .setBody(newDto(UserDto.class).withEmail(email).withName(name).withPassword(password)) - .request(); - } catch (IOException | UnauthorizedException | NotFoundException | ForbiddenException ex) { - throw new ServerException(ex); - } - } - - @Override - public User getById(String id) throws NotFoundException, ServerException { - try { - return requestFactory - .fromUrl(userServiceEndpoint + id) - .useGetMethod() - .request() - .asDto(UserDto.class); - } catch (IOException - | BadRequestException - | UnauthorizedException - | ForbiddenException - | ConflictException ex) { - throw new ServerException(ex); - } - } - - @Override - public User findByEmail(String email) - throws BadRequestException, NotFoundException, ServerException { - try { - return requestFactory - .fromUrl(userServiceEndpoint + "find") - .useGetMethod() - .addQueryParam("email", URLEncoder.encode(email, "UTF-8")) - .request() - .asDto(UserDto.class); - } catch (IOException | UnauthorizedException | ForbiddenException | ConflictException ex) { - throw new ServerException(ex); - } - } - - @Override - public User findByName(String name) - throws BadRequestException, NotFoundException, ServerException { - try { - return requestFactory - .fromUrl(userServiceEndpoint + "find") - .useGetMethod() - .addQueryParam("name", name) - .request() - .asDto(UserDto.class); - } catch (IOException | UnauthorizedException | ForbiddenException | ConflictException ex) { - throw new ServerException(ex); - } - } - - @Override - public void remove(String id) throws ConflictException, ServerException { - try { - requestFactory.fromUrl(userServiceEndpoint + id).useDeleteMethod().request(); - } catch (IOException - | BadRequestException - | NotFoundException - | UnauthorizedException - | ForbiddenException ex) { - throw new ServerException(ex); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestWorkspaceServiceClient.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestWorkspaceServiceClient.java deleted file mode 100644 index c551b0a0fa..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestWorkspaceServiceClient.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import java.util.List; -import org.eclipse.che.api.core.model.workspace.Workspace; -import org.eclipse.che.api.core.model.workspace.WorkspaceStatus; -import org.eclipse.che.api.core.model.workspace.runtime.Server; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto; -import org.eclipse.che.commons.annotation.Nullable; -import org.eclipse.che.selenium.core.user.TestUser; -import org.eclipse.che.selenium.core.workspace.MemoryMeasure; - -public interface TestWorkspaceServiceClient { - - List getAll() throws Exception; - - int getWorkspacesCount() throws Exception; - - void stop(String workspaceName, String userName) throws Exception; - - Workspace getByName(String workspace, String username) throws Exception; - - boolean exists(String workspace, String username) throws Exception; - - void delete(String workspaceName, String userName) throws Exception; - - void waitStatus(String workspaceName, String userName, WorkspaceStatus expectedStatus) - throws Exception; - - void waitWorkspaceStart(String workspaceName, String userName) throws Exception; - - /** Creates a new workspace. */ - Workspace createWorkspace( - String workspaceName, int memory, MemoryMeasure memoryUnit, WorkspaceConfigDto workspace) - throws Exception; - - void sendStartRequest(String workspaceId, String workspaceName) throws Exception; - - /** Starts workspace. */ - void start(String workspaceId, String workspaceName, TestUser workspaceOwner) throws Exception; - - WorkspaceDto getById(String workspaceId) throws Exception; - - WorkspaceStatus getStatus(String workspaceId) throws Exception; - - @Deprecated - @Nullable - String getServerAddressByPort(String workspaceId, int port) throws Exception; - - @Nullable - Server getServerFromDevMachineBySymbolicName(String workspaceId, String serverName) - throws Exception; - - void ensureRunningStatus(Workspace workspace) throws IllegalStateException; - - void deleteFactoryWorkspaces(String originalName, String username) throws Exception; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestWorkspaceServiceClientFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestWorkspaceServiceClientFactory.java deleted file mode 100644 index 56799b022d..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/client/TestWorkspaceServiceClientFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.assistedinject.Assisted; -import org.eclipse.che.selenium.core.user.TestUser; - -/** @author Dmytro Nochevnov */ -public interface TestWorkspaceServiceClientFactory { - TestWorkspaceServiceClient create(@Assisted TestUser testUser); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/ConfigurationException.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/ConfigurationException.java deleted file mode 100644 index 711cc8beca..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/ConfigurationException.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.configuration; - -/** - * Exception happen in case of some problems with configuration. - * - * @author Sergii Kabashniuk - */ -public class ConfigurationException extends RuntimeException { - public ConfigurationException(String message) { - super(message); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/InMemoryTestConfiguration.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/InMemoryTestConfiguration.java deleted file mode 100644 index 9260d78c78..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/InMemoryTestConfiguration.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.configuration; - -import com.google.common.collect.ImmutableMap; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import org.eclipse.che.inject.CheBootstrap; - -/** In memory storage of TestConfiguration based on Map config */ -public class InMemoryTestConfiguration implements TestConfiguration { - - private final Map config; - - public InMemoryTestConfiguration() { - this(new HashMap<>()); - } - - public InMemoryTestConfiguration(TestConfiguration... configuration) { - this(); - for (TestConfiguration testConfiguration : configuration) { - addAll(testConfiguration.getMap()); - } - // convert value of CHE_INFRASTRUCTURE to upper case to comply with Infrastructure - // enumeration; - config.put("che.infrastructure", config.get("che.infrastructure").toUpperCase()); - } - - public InMemoryTestConfiguration(Map config) { - this.config = config; - } - - void addAll(Map config) { - this.config.putAll(config); - } - - @Override - public boolean isConfigured(String key) { - return config.containsKey(key); - } - - @Override - public String getString(String key) { - String value = config.get(key); - if (value == null) { - StringBuilder builder = new StringBuilder(); - builder - .append("\n") - .append("======== IMPORTANT =========\n") - .append("Key ") - .append(key) - .append(" is not configured\n") - .append("You can configure it as :\n") - .append("1. System property. Example: \t-D") - .append(key) - .append("=yourvalue \n") - .append("2. Environment variable. Example: \texport CODENVY_") - .append(key.toUpperCase().replace("_", "=").replace('.', '_').replace("=", "__")) - .append("=yourvalue \n") - .append("3. Or configured it in a property file in folder declared as ") - .append(CheBootstrap.CHE_LOCAL_CONF_DIR) - .append(" environment variable\n") - .append("============================\n"); - throw new ConfigurationException(builder.toString()); - } - return value; - } - - @Override - public Boolean getBoolean(String key) { - return Boolean.parseBoolean(config.get(key)); - } - - @Override - public Integer getInt(String key) { - return Integer.parseInt(config.get(key)); - } - - @Override - public Long getLong(String key) { - return Long.parseLong(config.get(key)); - } - - @Override - public Map getMap() { - return ImmutableMap.copyOf(config); - } - - @Override - public Map getMap(String keyPrefix) { - return config - .entrySet() - .stream() - .filter(e -> e.getKey().startsWith(keyPrefix)) - .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/SeleniumTestConfiguration.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/SeleniumTestConfiguration.java deleted file mode 100644 index a405ca5f2f..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/SeleniumTestConfiguration.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.configuration; - -import com.google.common.collect.Maps; -import com.google.common.io.Files; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.File; -import java.io.IOException; -import java.io.Reader; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.AbstractMap; -import java.util.AbstractMap.SimpleEntry; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import org.eclipse.che.inject.CheBootstrap; - -/** - * Represents in memory based storage of the test configuration. - * - *

    Values of configuration are loaded in the following sequence:
    - * 1. Default configuration from target/conf/selenium.properties file.
    - * 2. All properties from CHE_LOCAL_CONF_DIR directory.
    - * 3. From java system properties (will be given prefix "sys.").
    - * 4. From environment variables (will be given prefix "env."). Symbol "_" is replaced by "." and - * "__" is replaced by "_" in names of environment variables.
    - * Variables which start from "che." or "codenvy." don't have an additional prefix "sys." or "env.". - * - * @author Sergii Kabashniuk - */ -@Singleton -public class SeleniumTestConfiguration extends InMemoryTestConfiguration { - - @Inject - public SeleniumTestConfiguration() { - super( - new DefaultConfiguration(), - new PropertiesConfiguration(), - new SystemPropertiesConfiguration(), - new EnvironmentVariablesConfiguration()); - } - - static class SystemPropertiesConfiguration extends InMemoryTestConfiguration { - - SystemPropertiesConfiguration() { - super(); - addAll( - System.getProperties() - .entrySet() - .stream() - .filter(new PropertyNamePrefixPredicate<>("che.", "codenvy.")) - .map(e -> new AbstractMap.SimpleEntry<>((String) e.getKey(), ((String) e.getValue()))) - .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue))); - addAll( - System.getProperties() - .entrySet() - .stream() - .map(e -> new AbstractMap.SimpleEntry<>("sys." + e.getKey(), ((String) e.getValue()))) - .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue))); - } - } - - static class EnvironmentVariablesConfiguration extends InMemoryTestConfiguration { - - EnvironmentVariablesConfiguration() { - super(); - addAll( - System.getenv() - .entrySet() - .stream() - .filter(new PropertyNamePrefixPredicate<>("CHE_", "CODENVY_")) - .map(new EnvironmentVariableToSystemPropertyFormatNameConverter()) - .collect(Collectors.toMap(Entry::getKey, Entry::getValue))); - addAll( - System.getenv() - .entrySet() - .stream() - .map(new EnvironmentVariableToSystemPropertyFormatNameConverter()) - .map(e -> new AbstractMap.SimpleEntry<>("env." + e.getKey(), e.getValue())) - .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue))); - } - } - - static class PropertyNamePrefixPredicate implements Predicate> { - final String[] prefixes; - - PropertyNamePrefixPredicate(String... prefix) { - this.prefixes = prefix; - } - - @Override - public boolean test(Map.Entry entry) { - for (String prefix : prefixes) { - if (((String) entry.getKey()).startsWith(prefix)) { - return true; - } - } - return false; - } - } - - static class EnvironmentVariableToSystemPropertyFormatNameConverter - implements Function, Map.Entry> { - @Override - public Map.Entry apply(Map.Entry entry) { - String name = entry.getKey(); - name = name.toLowerCase(); - // replace single underscore with dot and double underscores with single underscore - // at first replace double underscores with equal sign which is forbidden in env variable name - // then replace single underscores - // then recover underscore from equal sign - name = name.replace("__", "="); - name = name.replace('_', '.'); - name = name.replace("=", "_"); - - return new AbstractMap.SimpleEntry<>(name, entry.getValue()); - } - } - - static class DefaultConfiguration extends PropertiesConfiguration { - DefaultConfiguration() { - URL defaultConfig = getClass().getClassLoader().getResource("conf/selenium.properties"); - if (defaultConfig != null) { - addFile(new File(defaultConfig.getFile())); - } - } - } - - /** Implementation of TestConfiguration based on folder with properties files inside. */ - static class PropertiesConfiguration extends InMemoryTestConfiguration { - - PropertiesConfiguration() { - String extConfig = System.getenv(CheBootstrap.CHE_LOCAL_CONF_DIR); - if (extConfig != null) { - File extConfigFile = new File(extConfig); - if (extConfigFile.isDirectory() && extConfigFile.exists()) { - final File[] files = extConfigFile.listFiles(); - if (files != null) { - for (File file : files) { - addFile(file); - } - } - } - } - } - - void addFile(File file) { - if (!file.isDirectory()) { - if ("properties".equals(Files.getFileExtension(file.getName()))) { - Properties properties = new Properties(); - try (Reader reader = Files.newReader(file, Charset.forName("UTF-8"))) { - properties.load(reader); - } catch (IOException e) { - throw new IllegalStateException( - String.format("Unable to read configuration file %s", file), e); - } - addAll(Maps.fromProperties(properties)); - } - } - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/TestConfiguration.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/TestConfiguration.java deleted file mode 100644 index f759fa79e2..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/configuration/TestConfiguration.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.configuration; - -import java.util.Map; - -/** - * Represents configuration of testing framework - * - * @author Sergii Kabashniuk - */ -public interface TestConfiguration { - - /** - * Test if configuration contains parameter. - * - * @param key configuration key. - * @return - true if key is configured. - */ - boolean isConfigured(String key); - - /** - * @param key - configuration key. - * @return String based value of configuration property. - * @throws ConfigurationException if kys is not configured - */ - String getString(String key) throws ConfigurationException; - - /** - * @param key - configuration key. - * @return Boolean based value of configuration property. - * @throws ConfigurationException if kys is not configured - */ - Boolean getBoolean(String key) throws ConfigurationException; - - /** - * @param key - configuration key. - * @return Integer based value of configuration property. - * @throws ConfigurationException if kys is not configured - */ - Integer getInt(String key) throws ConfigurationException; - - /** - * @param key - configuration key. - * @return Long based value of configuration property. - * @throws ConfigurationException if kys is not configured - */ - Long getLong(String key) throws ConfigurationException; - - /** @return all configuration parameters. */ - Map getMap(); - - /** - * @param keyPrefix - filter all properties with given prefix - * @return - key/value map of configuration. - */ - Map getMap(String keyPrefix); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/Infrastructure.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/Infrastructure.java deleted file mode 100644 index 58d549cfb3..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/Infrastructure.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -import com.google.inject.Singleton; - -/** - * Reflects values of environment variable CHE_INFRASTRUCTURE - * - * @author Dmytro Nochevnov - */ -@Singleton -public enum Infrastructure { - DOCKER, - OPENSHIFT, - K8S, - OSIO -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/TestBrowser.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/TestBrowser.java deleted file mode 100644 index ef2dbc7b9e..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/TestBrowser.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** @author Aleksandr Shmaraev */ -public enum TestBrowser { - GOOGLE_CHROME -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/TestTimeoutsConstants.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/TestTimeoutsConstants.java deleted file mode 100644 index bbbc6db2cf..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/constant/TestTimeoutsConstants.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** Represent of main constants for tests in seconds */ -public final class TestTimeoutsConstants { - public static final int MULTIPLE = 1; - public static final int APPLICATION_START_TIMEOUT_SEC = 300 * MULTIPLE; - public static final int PREPARING_WS_TIMEOUT_SEC = 240 * MULTIPLE; - public static final int UPDATING_PROJECT_TIMEOUT_SEC = 180 * MULTIPLE; - public static final int EXPECTED_MESS_IN_CONSOLE_SEC = 120 * MULTIPLE; - public static final int LOADER_TIMEOUT_SEC = 60 * MULTIPLE; - public static final int WIDGET_TIMEOUT_SEC = 40 * MULTIPLE; - public static final int ELEMENT_TIMEOUT_SEC = 20 * MULTIPLE; - public static final int LOAD_PAGE_TIMEOUT_SEC = 10 * MULTIPLE; - public static final int REDRAW_UI_ELEMENTS_TIMEOUT_SEC = 5 * MULTIPLE; - public static final int ATTACHING_ELEM_TO_DOM_SEC = 3 * MULTIPLE; - public static final int MINIMUM_SEC = MULTIPLE; - public static final int DEFAULT_TIMEOUT = LOAD_PAGE_TIMEOUT_SEC; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/entrance/Entrance.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/entrance/Entrance.java deleted file mode 100644 index 6d18de4c14..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/entrance/Entrance.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.entrance; - -import org.eclipse.che.selenium.core.user.TestUser; - -/** @author Dmytro Nochevnov */ -public interface Entrance { - /** - * Login to product. - * - * @param user user to login - */ - void login(TestUser user); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/FactoryTemplate.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/FactoryTemplate.java deleted file mode 100644 index 41faeff9ea..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/FactoryTemplate.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.factory; - -/** - * Factory templates. - * - * @author Anatolii Bazko - */ -public class FactoryTemplate { - public static final String MINIMAL = "minimal.json"; - - private FactoryTemplate() {} -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/TestFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/TestFactory.java deleted file mode 100644 index bffb6179c6..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/TestFactory.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.factory; - -import org.eclipse.che.api.core.model.workspace.WorkspaceStatus; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.client.TestFactoryServiceClient; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClient; -import org.eclipse.che.selenium.core.entrance.Entrance; -import org.eclipse.che.selenium.core.provider.TestDashboardUrlProvider; -import org.eclipse.che.selenium.core.user.DefaultTestUser; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.WebDriver; - -/** @author Anatolii Bazko */ -public class TestFactory { - private final DefaultTestUser owner; - private final FactoryDto factoryDto; - private final TestDashboardUrlProvider dashboardUrl; - private final TestFactoryServiceClient testFactoryServiceClient; - private final TestWorkspaceServiceClient workspaceServiceClient; - private final Entrance entrance; - private final String factoryUrl; - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - - public TestFactory( - String factoryUrl, - DefaultTestUser owner, - FactoryDto factoryDto, - TestDashboardUrlProvider dashboardUrl, - TestFactoryServiceClient factoryServiceClient, - TestWorkspaceServiceClient workspaceServiceClient, - Entrance entrance, - SeleniumWebDriver seleniumWebDriver, - SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.factoryDto = factoryDto; - this.owner = owner; - this.factoryUrl = factoryUrl; - this.dashboardUrl = dashboardUrl; - this.testFactoryServiceClient = factoryServiceClient; - this.workspaceServiceClient = workspaceServiceClient; - this.entrance = entrance; - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - } - - /** Login to factory and open it by url. */ - public void authenticateAndOpen() { - seleniumWebDriver.get(dashboardUrl.get().toString()); - entrance.login(owner); - seleniumWebDriver.get(factoryUrl); - } - - /** Opens factory url. */ - public void open(WebDriver driver) { - driver.get(factoryUrl); - } - - public void delete() throws Exception { - seleniumWebDriver.quit(); - - workspaceServiceClient.deleteFactoryWorkspaces( - factoryDto.getWorkspace().getName(), owner.getName()); - deleteFactory(); - } - - private void deleteFactory() { - if (isNamedFactory()) { - testFactoryServiceClient.deleteFactory(factoryDto.getName()); - } - } - - private boolean isNamedFactory() { - return factoryDto.getName() != null; - } - - public WorkspaceStatus getWorkspaceStatusAssociatedWithFactory() throws Exception { - return workspaceServiceClient - .getByName(factoryDto.getWorkspace().getName(), owner.getName()) - .getStatus(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/TestFactoryInitializer.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/TestFactoryInitializer.java deleted file mode 100644 index 2003402d86..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/factory/TestFactoryInitializer.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.factory; - -import static java.lang.String.format; -import static java.util.Collections.singletonMap; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import java.io.InputStream; -import java.net.URLEncoder; -import java.util.List; -import javax.inject.Named; -import org.eclipse.che.api.core.rest.HttpJsonRequest; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.core.rest.HttpJsonResponse; -import org.eclipse.che.api.core.rest.shared.dto.Link; -import org.eclipse.che.api.factory.shared.dto.AuthorDto; -import org.eclipse.che.api.factory.shared.dto.FactoryDto; -import org.eclipse.che.api.factory.shared.dto.IdeDto; -import org.eclipse.che.api.factory.shared.dto.PoliciesDto; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.api.workspace.shared.dto.devfile.DevfileDto; -import org.eclipse.che.commons.lang.IoUtil; -import org.eclipse.che.commons.lang.NameGenerator; -import org.eclipse.che.dto.server.DtoFactory; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.client.TestFactoryServiceClient; -import org.eclipse.che.selenium.core.client.TestUserPreferencesServiceClient; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClient; -import org.eclipse.che.selenium.core.constant.Infrastructure; -import org.eclipse.che.selenium.core.entrance.Entrance; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.provider.TestDashboardUrlProvider; -import org.eclipse.che.selenium.core.provider.TestIdeUrlProvider; -import org.eclipse.che.selenium.core.user.DefaultTestUser; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; - -/** @author Anatolii Bazko */ -@Singleton -public class TestFactoryInitializer { - - @Inject private DefaultTestUser defaultUser; - @Inject private TestIdeUrlProvider ideUrlProvider; - @Inject private TestDashboardUrlProvider dashboardUrlProvider; - @Inject private TestApiEndpointUrlProvider apiEndpointProvider; - @Inject private HttpJsonRequestFactory requestFactory; - @Inject private TestFactoryServiceClient testFactoryServiceClient; - @Inject private TestWorkspaceServiceClient workspaceServiceClient; - @Inject private Entrance entrance; - @Inject private SeleniumWebDriver seleniumWebDriver; - @Inject private SeleniumWebDriverHelper seleniumWebDriverHelper; - @Inject private TestUserPreferencesServiceClient testUserPreferencesServiceClient; - - @Inject - @Named("che.infrastructure") - private Infrastructure infrastructure; - - /** - * Initialize {@link TestFactory} base upon template. - * - * @see FactoryTemplate - */ - public TestFactoryBuilder fromTemplate(String template) throws Exception { - String name = NameGenerator.generate("factory", 6); - InputStream resource = TestFactory.class.getResourceAsStream(getTemplateDirectory(template)); - if (resource == null) { - throw new IOException(format("Factory template '%s' not found", template)); - } - - String factoryTemplate = IoUtil.readStream(resource); - FactoryDto factoryDto = - DtoFactory.getInstance() - .createDtoFromJson(factoryTemplate, FactoryDto.class) - .withName(name); - factoryDto.getWorkspace().setName(name); - return new TestFactoryBuilder(factoryDto); - } - - private String getTemplateDirectory(String template) { - String templateDirectoryName; - switch (infrastructure) { - case OSIO: - templateDirectoryName = Infrastructure.OPENSHIFT.toString().toLowerCase(); - break; - - default: - templateDirectoryName = infrastructure.toString().toLowerCase(); - } - - return String.format("/templates/factory/%s/%s", templateDirectoryName, template); - } - - /** Initialize {@link TestFactory} base upon url. Can't be modified. */ - public TestFactory fromUrl(String url) throws Exception { - HttpJsonRequest httpJsonRequest = - requestFactory.fromUrl(apiEndpointProvider.get() + "factory/resolver"); - httpJsonRequest.setBody(singletonMap("url", url)); - HttpJsonResponse response = httpJsonRequest.request(); - - FactoryDto factoryDto = response.asDto(FactoryDto.class); - String factoryUrl = ideUrlProvider.get() + "f?url=" + URLEncoder.encode(url, "UTF8"); - return new TestFactory( - factoryUrl, - defaultUser, - factoryDto, - dashboardUrlProvider, - testFactoryServiceClient, - workspaceServiceClient, - entrance, - seleniumWebDriver, - seleniumWebDriverHelper); - } - - /** Builder for {@link TestFactory}. */ - public class TestFactoryBuilder implements FactoryDto { - private final FactoryDto factoryDto; - - private TestFactoryBuilder(FactoryDto factoryDto) { - this.factoryDto = factoryDto; - } - - public TestFactory build() throws Exception { - String factoryUrl = testFactoryServiceClient.createFactory(factoryDto); - return new TestFactory( - factoryUrl, - defaultUser, - factoryDto, - dashboardUrlProvider, - testFactoryServiceClient, - workspaceServiceClient, - entrance, - seleniumWebDriver, - seleniumWebDriverHelper); - } - - @Override - public List getLinks() { - return factoryDto.getLinks(); - } - - @Override - public void setLinks(List links) { - factoryDto.setLinks(links); - } - - @Override - public List getLinks(String rel) { - return factoryDto.getLinks(rel); - } - - @Override - public Link getLink(String rel) { - return factoryDto.getLink(rel); - } - - @Override - public String getV() { - return factoryDto.getV(); - } - - @Override - public void setV(String v) { - factoryDto.setV(v); - } - - @Override - public FactoryDto withV(String v) { - return factoryDto.withV(v); - } - - @Override - public DevfileDto getDevfile() { - return factoryDto.getDevfile(); - } - - @Override - public void setDevfile(DevfileDto workspace) { - factoryDto.setDevfile(workspace); - } - - @Override - public FactoryDto withDevfile(DevfileDto devfileDto) { - return factoryDto.withDevfile(devfileDto); - } - - @Override - public WorkspaceConfigDto getWorkspace() { - return factoryDto.getWorkspace(); - } - - @Override - public void setWorkspace(WorkspaceConfigDto workspace) { - factoryDto.setWorkspace(workspace); - } - - @Override - public FactoryDto withWorkspace(WorkspaceConfigDto workspace) { - return factoryDto.withWorkspace(workspace); - } - - @Override - public PoliciesDto getPolicies() { - return factoryDto.getPolicies(); - } - - @Override - public void setPolicies(PoliciesDto policies) { - factoryDto.setPolicies(policies); - } - - @Override - public FactoryDto withPolicies(PoliciesDto policies) { - return factoryDto.withPolicies(policies); - } - - @Override - public AuthorDto getCreator() { - return factoryDto.getCreator(); - } - - @Override - public void setCreator(AuthorDto creator) { - factoryDto.setCreator(creator); - } - - @Override - public FactoryDto withCreator(AuthorDto creator) { - return factoryDto.withCreator(creator); - } - - @Override - public IdeDto getIde() { - return factoryDto.getIde(); - } - - @Override - public void setIde(IdeDto ide) { - factoryDto.setIde(ide); - } - - @Override - public FactoryDto withIde(IdeDto ide) { - return factoryDto.withIde(ide); - } - - @Override - public String getId() { - return factoryDto.getId(); - } - - @Override - public void setId(String id) { - factoryDto.setId(id); - } - - @Override - public FactoryDto withId(String id) { - return factoryDto.withId(id); - } - - @Override - public String getName() { - return factoryDto.getName(); - } - - @Override - public void setName(String name) { - factoryDto.setName(name); - } - - @Override - public FactoryDto withName(String name) { - return factoryDto.withName(name); - } - - @Override - public FactoryDto withLinks(List links) { - return factoryDto.withLinks(links); - } - - @Override - public String getSource() { - return factoryDto.getSource(); - } - - @Override - public void setSource(String source) { - factoryDto.setSource(source); - } - - @Override - public FactoryDto withSource(String source) { - return factoryDto.withSource(source); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumClassModule.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumClassModule.java deleted file mode 100644 index 2066ef32f1..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumClassModule.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.inject; - -import static com.google.inject.matcher.Matchers.any; - -import com.google.inject.AbstractModule; -import com.google.inject.Injector; -import com.google.inject.Provider; -import com.google.inject.TypeLiteral; -import com.google.inject.spi.TypeEncounter; -import com.google.inject.spi.TypeListener; -import java.lang.reflect.Field; -import java.util.function.Consumer; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.organization.InjectTestOrganization; -import org.eclipse.che.selenium.core.organization.TestOrganization; -import org.eclipse.che.selenium.core.organization.TestOrganizationInjector; -import org.eclipse.che.selenium.core.workspace.InjectTestWorkspace; -import org.eclipse.che.selenium.core.workspace.TestWorkspace; -import org.eclipse.che.selenium.core.workspace.TestWorkspaceInjector; - -/** - * Guice module per test class. - * - * @author Anatolii Bazko - */ -public class SeleniumClassModule extends AbstractModule { - @Override - public void configure() { - bind(SeleniumWebDriver.class); - - bindListener(any(), new WorkspaceTypeListener(binder().getProvider(Injector.class))); - bindListener(any(), new OrganizationTypeListener(binder().getProvider(Injector.class))); - } - - private class WorkspaceTypeListener implements TypeListener { - private final Provider injectorProvider; - - public WorkspaceTypeListener(Provider injector) { - this.injectorProvider = injector; - } - - @Override - public void hear(TypeLiteral type, TypeEncounter encounter) { - traverseClassHierarchy( - type.getRawType(), - (clazz) -> { - for (Field field : clazz.getDeclaredFields()) { - if (field.getType() == TestWorkspace.class - && field.isAnnotationPresent(InjectTestWorkspace.class)) { - encounter.register( - new TestWorkspaceInjector<>( - field, - field.getAnnotation(InjectTestWorkspace.class), - injectorProvider.get())); - } - } - }); - } - - private void traverseClassHierarchy(Class clazz, Consumer handler) { - if (clazz == null || clazz.equals(Object.class)) { - return; - } - - traverseClassHierarchy(clazz.getSuperclass(), handler); - handler.accept(clazz); - } - } - - private class OrganizationTypeListener implements TypeListener { - private final Provider injectorProvider; - - public OrganizationTypeListener(Provider injector) { - this.injectorProvider = injector; - } - - @Override - public void hear(TypeLiteral type, TypeEncounter encounter) { - Class clazz = type.getRawType(); - for (Field field : clazz.getDeclaredFields()) { - if (field.getType() == TestOrganization.class - && field.isAnnotationPresent(InjectTestOrganization.class)) { - encounter.register( - new TestOrganizationInjector<>( - field, field.getAnnotation(InjectTestOrganization.class), injectorProvider)); - } - } - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumTestHandler.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumTestHandler.java deleted file mode 100644 index b3c93dfe72..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumTestHandler.java +++ /dev/null @@ -1,721 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.inject; - -import static com.google.inject.Guice.createInjector; -import static java.lang.Runtime.getRuntime; -import static java.lang.String.format; - -import com.google.inject.Guice; -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.google.inject.Module; -import com.google.inject.name.Named; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; -import java.util.stream.Stream; -import java.util.zip.ZipOutputStream; -import javax.annotation.PreDestroy; -import javax.validation.constraints.NotNull; -import org.apache.commons.io.FileUtils; -import org.eclipse.che.commons.json.JsonParseException; -import org.eclipse.che.commons.lang.ZipUtils; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.TestGroup; -import org.eclipse.che.selenium.core.client.TestGitHubServiceClient; -import org.eclipse.che.selenium.core.organization.InjectTestOrganization; -import org.eclipse.che.selenium.core.pageobject.InjectPageObject; -import org.eclipse.che.selenium.core.pageobject.PageObjectsInjector; -import org.eclipse.che.selenium.core.user.DefaultTestUser; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverFactory; -import org.eclipse.che.selenium.core.webdriver.log.WebDriverLogsReaderFactory; -import org.eclipse.che.selenium.core.workspace.InjectTestWorkspace; -import org.eclipse.che.selenium.core.workspace.TestWorkspace; -import org.eclipse.che.selenium.core.workspace.TestWorkspaceLogsReader; -import org.eclipse.che.selenium.core.workspace.TestWorkspaceProvider; -import org.openqa.selenium.OutputType; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebDriverException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.IAnnotationTransformer2; -import org.testng.IConfigurationListener; -import org.testng.IExecutionListener; -import org.testng.IInvokedMethod; -import org.testng.IInvokedMethodListener; -import org.testng.ISuite; -import org.testng.ISuiteListener; -import org.testng.ITestContext; -import org.testng.ITestListener; -import org.testng.ITestNGMethod; -import org.testng.ITestResult; -import org.testng.SkipException; -import org.testng.TestException; -import org.testng.annotations.IConfigurationAnnotation; -import org.testng.annotations.IDataProviderAnnotation; -import org.testng.annotations.IFactoryAnnotation; -import org.testng.annotations.ITestAnnotation; - -/** - * Tests lifecycle handler. - * - *

    Adding {@link IConfigurationListener} brings bug when all methods of the listener will be - * invoked twice. - * - * @author Anatolii Bazko - * @author Dmytro Nochevnov - */ -public abstract class SeleniumTestHandler - implements ITestListener, - ISuiteListener, - IInvokedMethodListener, - IExecutionListener, - IAnnotationTransformer2, - IConfigurationListener { - - private static final Logger LOG = LoggerFactory.getLogger(SeleniumTestHandler.class); - private static final AtomicBoolean isCleanUpCompleted = new AtomicBoolean(); - - @Inject private SeleniumWebDriverFactory seleniumWebDriverFactory; - - @Inject - @Named("tests.screenshots_dir") - private String screenshotsDir; - - @Inject - @Named("tests.htmldumps_dir") - private String htmldumpsDir; - - @Inject - @Named("tests.webdriverlogs_dir") - private String webDriverLogsDir; - - @Inject - @Named("tests.workspacelogs_dir") - private String workspaceLogsDir; - - @Inject private PageObjectsInjector pageObjectsInjector; - - @Inject - @Named("github.username") - private String gitHubUsername; - - @Inject - @Named("github.password") - private String gitHubPassword; - - @Inject - @Named("sys.excludedGroups") - private String excludedGroups; - - @Inject private DefaultTestUser defaultTestUser; - @Inject private TestWorkspaceProvider testWorkspaceProvider; - @Inject private TestGitHubServiceClient gitHubClientService; - @Inject private TestWorkspaceLogsReader testWorkspaceLogsReader; - @Inject private SeleniumTestStatistics seleniumTestStatistics; - @Inject private WebDriverLogsReaderFactory webDriverLogsReaderFactory; - @Inject private TestFilter testFilter; - - private final Injector injector; - - // this is the map {thread ID} -> {test instance} - private final Map runningTests = new ConcurrentHashMap<>(); - - // this is the map {test class FQN} -> {failed test method} - private final Map testsWithFailure = new ConcurrentHashMap<>(); - - public SeleniumTestHandler() { - injector = createInjector(getParentModules()); - injector.injectMembers(this); - - getRuntime().addShutdownHook(new Thread(this::shutdown)); - - revokeGithubOauthToken(); - checkWebDriverSessionCreation(); - } - - private void revokeGithubOauthToken() { - // do not revoke if github tests are not being executed - if (excludedGroups != null && excludedGroups.contains(TestGroup.GITHUB)) { - return; - } - - try { - gitHubClientService.deleteAllGrants(gitHubUsername, gitHubPassword); - } catch (Exception e) { - LOG.warn("There was an error of revoking the github oauth token.", e); - } - } - - @Override - public void onTestStart(ITestResult result) { - LOG.info( - "Starting test #{} {}. {}", - seleniumTestStatistics.hitStart(), - getStartingTestLabel(result.getMethod()), - seleniumTestStatistics.toString()); - - skipTestIfNeeded(result); - } - - @Override - public void onTestSuccess(ITestResult result) { - seleniumTestStatistics.hitPass(); - onTestFinish(result); - } - - @Override - public void onTestFailure(ITestResult result) { - seleniumTestStatistics.hitFail(); - onTestFinish(result); - } - - @Override - public void onTestSkipped(ITestResult result) { - seleniumTestStatistics.hitSkip(); - onTestFinish(result); - } - - @Override - public void onTestFailedButWithinSuccessPercentage(ITestResult result) { - seleniumTestStatistics.hitFail(); - onTestFinish(result); - } - - @Override - public void onStart(ITestContext context) {} - - @Override - public void onFinish(ITestContext context) {} - - @Override - public void onStart(ISuite suite) { - suite.setParentInjector(injector); - long numberOfEnabledTests = - suite.getAllMethods().parallelStream().filter(ITestNGMethod::getEnabled).count(); - LOG.info("Starting suite '{}' with {} test methods.", suite.getName(), numberOfEnabledTests); - } - - /** Check if webdriver session can be created without errors. */ - private void checkWebDriverSessionCreation() { - SeleniumWebDriver seleniumWebDriver = null; - try { - seleniumWebDriver = seleniumWebDriverFactory.create(); - } finally { - Optional.ofNullable(seleniumWebDriver) - .ifPresent(SeleniumWebDriver::quit); // finish webdriver session - } - } - - @Override - public void onFinish(ISuite suite) {} - - @Override - public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { - Object invokingTestInstance = method.getTestMethod().getInstance(); - if (runningTests.containsValue(invokingTestInstance)) { - return; - } - - long currentThreadId = Thread.currentThread().getId(); - if (isNewTestInProgress(invokingTestInstance)) { - Object previousTestInstance = runningTests.remove(currentThreadId); - preDestroy(previousTestInstance); - testsWithFailure.remove(previousTestInstance.getClass().getName()); - } - - String testName = invokingTestInstance.getClass().getName(); - - try { - LOG.info("Dependencies injection in {}", testName); - injectDependencies(testResult.getTestContext(), invokingTestInstance); - } catch (Exception e) { - String errorMessage = "Failed to inject fields in " + testName; - LOG.error(errorMessage, e); - throw new TestException(errorMessage, e); - } finally { - runningTests.put(currentThreadId, invokingTestInstance); - } - } - - private boolean isNewTestInProgress(Object testInstance) { - Thread currentThread = Thread.currentThread(); - - return runningTests.containsKey(currentThread.getId()) - && runningTests.get(currentThread.getId()) != testInstance; - } - - @Override - public void afterInvocation(IInvokedMethod method, ITestResult result) {} - - @Override - public void onExecutionStart() {} - - @Override - public void onExecutionFinish() { - shutdown(); - } - - @Override - public void transform( - ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { - testFilter.excludeTestOfImproperGroup(annotation); - } - - @Override - public void transform( - IConfigurationAnnotation annotation, - Class testClass, - Constructor testConstructor, - Method testMethod) { - testFilter.excludeTestOfImproperGroup(annotation); - } - - @Override - public void transform(IDataProviderAnnotation annotation, Method method) {} - - @Override - public void transform(IFactoryAnnotation annotation, Method method) {} - - @Override - public void onConfigurationSuccess(ITestResult result) {} - - @Override - public void onConfigurationFailure(ITestResult result) { - onTestFinish(result); - } - - @Override - public void onConfigurationSkip(ITestResult result) { - onTestFinish(result); - } - - /** Injects dependencies into the given test class using {@link Guice} and custom injectors. */ - private void injectDependencies(ITestContext testContext, Object testInstance) throws Exception { - Injector injector = testContext.getSuite().getParentInjector(); - - List childModules = new ArrayList<>(getChildModules()); - childModules.add(new SeleniumClassModule()); - - Injector classInjector = injector.createChildInjector(childModules); - classInjector.injectMembers(testInstance); - - pageObjectsInjector.injectMembers(testInstance, classInjector); - } - - /** Is invoked when test or configuration is finished. */ - private void onTestFinish(ITestResult result) { - // do not treat SeleniumTestHandler error as test failure - if (testsWithFailure.containsKey(result.getTestClass().getRealClass().getName()) - && testsWithFailure - .get(result.getTestClass().getRealClass().getName()) - .getMethod() - .equals(result.getMethod()) - && result.getMethod().getCurrentInvocationCount() == 1) { - // restore initial test exception - result.setThrowable( - testsWithFailure.get(result.getTestClass().getRealClass().getName()).getThrowable()); - return; - } - - if (result.getStatus() == ITestResult.FAILURE || result.getStatus() == ITestResult.SKIP) { - switch (result.getStatus()) { - case ITestResult.FAILURE: - if (result.getMethod().isTest()) { - String errorDetails = - result.getThrowable() != null - ? " Error: " + result.getThrowable().getLocalizedMessage() - : ""; - - LOG.error("Test {} failed.{}", getCompletedTestLabel(result.getMethod()), errorDetails); - LOG.debug(result.getThrowable().getLocalizedMessage(), result.getThrowable()); - - testsWithFailure.put(result.getTestClass().getRealClass().getName(), result); - } - - captureWebDriver(result); - captureTestWorkspaceLogs(result); - - break; - - case ITestResult.SKIP: - String skipReasonDetails = - result.getThrowable() != null - ? " The reason: " + result.getThrowable().getLocalizedMessage() - : ""; - if (result.getMethod().isTest()) { - LOG.warn( - "Test {} skipped.{}", getCompletedTestLabel(result.getMethod()), skipReasonDetails); - } - - // don't capture test data if test is skipped because of previous test with higher - // priority failed - if (testsWithFailure.containsKey(result.getMethod().getInstance().getClass().getName())) { - return; - } - - break; - - default: - } - } - } - - private void captureTestWorkspaceLogs(ITestResult result) { - Object testInstance = result.getInstance(); - traverseClassHierarchy( - testInstance.getClass(), - (clazz) -> { - for (Field field : clazz.getDeclaredFields()) { - field.setAccessible(true); - - Object obj; - try { - obj = field.get(testInstance); - } catch (IllegalAccessException e) { - LOG.error( - "Field {} is inaccessible in {}.", - field.getName(), - testInstance.getClass().getName()); - continue; - } - - if (!(obj instanceof TestWorkspace)) { - continue; - } - - try { - if (((TestWorkspace) obj).getId() == null) { - continue; - } - } catch (ExecutionException | InterruptedException e) { - continue; - } - - String testReference = getTestReference(result); - Path pathToStoreWorkspaceLogs = Paths.get(workspaceLogsDir, testReference); - testWorkspaceLogsReader.store((TestWorkspace) obj, pathToStoreWorkspaceLogs, false); - Path pathToZipWithWorkspaceLogs = - pathToStoreWorkspaceLogs - .getParent() - .resolve(getTestResultFilename(testReference, "zip")); - - if (!Files.exists(pathToStoreWorkspaceLogs)) { - return; - } - - try { - Path zip = Files.createFile(pathToZipWithWorkspaceLogs); - try (ZipOutputStream out = ZipUtils.stream(zip)) { - ZipUtils.add(out, pathToStoreWorkspaceLogs); - } - - FileUtils.deleteQuietly(pathToStoreWorkspaceLogs.toFile()); - } catch (IOException | IllegalArgumentException e) { - LOG.warn("Error of creation zip-file with workspace logs.", e); - } - } - }); - } - - private boolean isInjectedWorkspace(Field field) { - return field.isAnnotationPresent(com.google.inject.Inject.class) - || field.isAnnotationPresent(javax.inject.Inject.class) - || field.isAnnotationPresent(InjectTestWorkspace.class); - } - - /** Releases resources by invoking methods annotated with {@link PreDestroy} */ - private void preDestroy(Object testInstance) { - LOG.info("Processing @PreDestroy annotation in {}", testInstance.getClass().getName()); - - traverseClassHierarchy( - testInstance.getClass(), - (clazz) -> { - for (Field field : clazz.getDeclaredFields()) { - field.setAccessible(true); - - Object obj; - try { - obj = field.get(testInstance); - } catch (IllegalAccessException e) { - LOG.error( - "Field {} is inaccessible in {}.", - field.getName(), - testInstance.getClass().getName()); - continue; - } - - if (obj == null || !hasInjectAnnotation(field)) { - continue; - } - - for (Method m : obj.getClass().getMethods()) { - if (m.isAnnotationPresent(PreDestroy.class)) { - try { - m.invoke(obj); - } catch (Exception e) { - LOG.error( - format( - "Failed to invoke method %s annotated with @PreDestroy in %s. Test instance: %s", - m.getName(), obj.getClass().getName(), testInstance.getClass().getName()), - e); - } - } - } - } - }); - } - - private boolean hasInjectAnnotation(AccessibleObject f) { - return f.isAnnotationPresent(com.google.inject.Inject.class) - || f.isAnnotationPresent(javax.inject.Inject.class) - || f.isAnnotationPresent(InjectTestWorkspace.class) - || f.isAnnotationPresent(InjectTestOrganization.class) - || f.isAnnotationPresent(InjectPageObject.class); - } - - private void captureWebDriver(ITestResult result) { - Set webDrivers = new HashSet<>(); - Object testInstance = result.getInstance(); - - collectInjectedWebDrivers(testInstance, webDrivers); - webDrivers.forEach(webDriver -> captureWebDriver(result, webDriver)); - } - - /** - * Iterates recursively throw all fields and collects instances of {@link SeleniumWebDriver}. - * - * @param testInstance the based object to examine - * @param webDrivers as the result of the method will contain all {@link WebDriver} - */ - private void collectInjectedWebDrivers(Object testInstance, Set webDrivers) { - traverseClassHierarchy( - testInstance.getClass(), - (clazz) -> { - for (Field field : clazz.getDeclaredFields()) { - field.setAccessible(true); - - Object obj; - try { - obj = field.get(testInstance); - } catch (IllegalAccessException e) { - LOG.error( - "Field {} is inaccessible in {}.", - field.getName(), - testInstance.getClass().getName()); - continue; - } - - if (obj == null) { - continue; - } - - Optional> injectedConstructor = - Stream.of(obj.getClass().getConstructors()) - .filter(this::hasInjectAnnotation) - .findAny(); - - if (!hasInjectAnnotation(field) && !injectedConstructor.isPresent()) { - continue; - } - - if (obj instanceof com.google.inject.Provider || obj instanceof javax.inject.Provider) { - continue; - } - - if (obj instanceof SeleniumWebDriver) { - webDrivers.add((SeleniumWebDriver) obj); - } else { - collectInjectedWebDrivers(obj, webDrivers); - } - } - }); - } - - private void traverseClassHierarchy(Class clazz, Consumer handler) { - if (clazz == null || clazz.equals(Object.class)) { - return; - } - - traverseClassHierarchy(clazz.getSuperclass(), handler); - handler.accept(clazz); - } - - private void captureScreenshotFromCurrentWindow(ITestResult result, SeleniumWebDriver webDriver) { - String testReference = getTestReference(result); - String filename = getTestResultFilename(testReference, "png"); - try { - byte[] data = webDriver.getScreenshotAs(OutputType.BYTES); - Path screenshot = Paths.get(screenshotsDir, filename); - Files.createDirectories(screenshot.getParent()); - Files.copy(new ByteArrayInputStream(data), screenshot); - } catch (WebDriverException | IOException e) { - LOG.error(format("Can't capture screenshot for test %s", testReference), e); - } - } - - private String getTestResultFilename(String testReference, String fileExtension) { - return format("%s_time-%s-millis.%s", testReference, System.currentTimeMillis(), fileExtension); - } - - private String getTestReference(ITestResult result) { - return format("%s.%s", result.getTestClass().getName(), result.getMethod().getMethodName()); - } - - private void captureWebDriver(ITestResult result, SeleniumWebDriver webDriver) { - webDriver - .getWindowHandles() - .forEach( - currentWin -> { - webDriver.switchTo().window(currentWin); - captureScreenshotFromCurrentWindow(result, webDriver); - captureHtmlDumpFromCurrentWindow(result, webDriver); - storeLogsFromCurrentWindow(result, webDriver); - }); - } - - private void storeLogsFromCurrentWindow(ITestResult result, SeleniumWebDriver webDriver) { - String testReference = getTestReference(result); - - try { - String filename = getTestResultFilename(testReference, "log"); - Path webDriverLogsDirectory = Paths.get(webDriverLogsDir, filename); - Files.createDirectories(webDriverLogsDirectory.getParent()); - Files.write( - webDriverLogsDirectory, - webDriverLogsReaderFactory - .create(webDriver) - .getAllLogs() - .getBytes(Charset.forName("UTF-8")), - StandardOpenOption.CREATE); - } catch (WebDriverException | IOException | JsonParseException e) { - LOG.error(format("Can't store web driver logs related to test %s.", testReference), e); - } - } - - private void captureHtmlDumpFromCurrentWindow(ITestResult result, SeleniumWebDriver webDriver) { - String testReference = getTestReference(result); - String filename = getTestResultFilename(testReference, "html"); - try { - String pageSource = webDriver.getPageSource(); - Path dumpDirectory = Paths.get(htmldumpsDir, filename); - Files.createDirectories(dumpDirectory.getParent()); - Files.write( - dumpDirectory, pageSource.getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE); - } catch (WebDriverException | IOException e) { - LOG.error(format("Can't dump of html source for test %s", testReference), e); - } - } - - /** Cleans up test environment. */ - private void shutdown() { - if (isCleanUpCompleted.get()) { - return; - } - - LOG.info("Cleaning up test environment..."); - - for (Object testInstance : runningTests.values()) { - preDestroy(testInstance); - testsWithFailure.remove(testInstance.getClass().getName()); - } - - if (testWorkspaceProvider != null) { - testWorkspaceProvider.shutdown(); - } - - if (defaultTestUser != null) { - try { - defaultTestUser.delete(); - } catch (IOException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - isCleanUpCompleted.set(true); - } - - /** - * Skip test if preceding test with higher priority from the same test class has failed. - * - * @param result holds result of test execution - * @throws SkipException if test should be skipped - */ - private void skipTestIfNeeded(ITestResult result) { - ITestNGMethod testMethodToSkip = result.getMethod(); - - ITestResult failedTestResult = - testsWithFailure.get(testMethodToSkip.getInstance().getClass().getName()); - - // skip test with lower priority value and if it shouldn't always run - if (failedTestResult != null - && testMethodToSkip.getPriority() > failedTestResult.getMethod().getPriority() - && !testMethodToSkip.isAlwaysRun()) { - throw new SkipException( - format( - "Skipping test %s because it depends on test %s which has failed earlier.", - getStartingTestLabel(testMethodToSkip), - getCompletedTestLabel(failedTestResult.getMethod()))); - } - } - - private String getStartingTestLabel(ITestNGMethod test) { - String invocationLabel = ""; - if (test.getCurrentInvocationCount() > 0) { - invocationLabel = format(" (run %d)", test.getCurrentInvocationCount() + 1); - } - - return getTestLabel(test, invocationLabel); - } - - private String getCompletedTestLabel(ITestNGMethod test) { - String invocationLabel = ""; - if (test.getCurrentInvocationCount() > 1) { - invocationLabel = format(" (run %d)", test.getCurrentInvocationCount()); - } - - return getTestLabel(test, invocationLabel); - } - - private String getTestLabel(ITestNGMethod test, String invocationLabel) { - return format( - "%s.%s%s", - test.getInstance().getClass().getSimpleName(), test.getMethodName(), invocationLabel); - } - - /** Returns list of parent modules */ - @NotNull - public abstract List getParentModules(); - - /** Returns list of child modules */ - @NotNull - public abstract List getChildModules(); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumTestStatistics.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumTestStatistics.java deleted file mode 100644 index 2a413387bb..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/SeleniumTestStatistics.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.inject; - -import static java.lang.String.format; - -import java.util.concurrent.atomic.AtomicInteger; - -/** @author Dmytro Nochevnov */ -public class SeleniumTestStatistics { - private static final String statisticsTemplate = "Passed: %d, failed: %d, skipped: %d."; - - private final AtomicInteger runTests = new AtomicInteger(); - private final AtomicInteger failedTests = new AtomicInteger(); - private final AtomicInteger passedTests = new AtomicInteger(); - private final AtomicInteger skippedTests = new AtomicInteger(); - - public int hitStart() { - return runTests.incrementAndGet(); - } - - public int hitPass() { - return passedTests.incrementAndGet(); - } - - public int hitFail() { - return failedTests.incrementAndGet(); - } - - public int hitSkip() { - return skippedTests.incrementAndGet(); - } - - @Override - public String toString() { - synchronized (this) { - return format(statisticsTemplate, passedTests.get(), failedTests.get(), skippedTests.get()); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/TestFilter.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/TestFilter.java deleted file mode 100644 index d422644c45..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/inject/TestFilter.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.inject; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.eclipse.che.selenium.core.TestGroup; -import org.eclipse.che.selenium.core.constant.Infrastructure; -import org.testng.annotations.ITestOrConfiguration; - -/** - * This class is aimed to filter TestNG tests. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class TestFilter { - - private final boolean isMultiuser; - private final Infrastructure infrastructure; - private final String excludedGroups; - - @Inject - public TestFilter( - @Named("sys.excludedGroups") String excludedGroups, - @Named("che.multiuser") boolean isMultiuser, - @Named("che.infrastructure") Infrastructure infrastructure) { - this.isMultiuser = isMultiuser; - this.infrastructure = infrastructure; - this.excludedGroups = excludedGroups; - } - - /** - * This method disable the test which belongs to test group which is being excluded or doesn't - * comply current infrastructure, or doesn't support Singleuser/Multiuser type of Eclipse Che. - * - * @param annotation annotation of test method which reflects {@link org.testng.annotations.Test} - * annotation attributes. - */ - public void excludeTestOfImproperGroup(ITestOrConfiguration annotation) { - if (annotation.getGroups().length == 0) { - return; - } - - List groups = new ArrayList<>(Arrays.asList(annotation.getGroups())); - - // exclude test with group from excludedGroups - if (excludedGroups != null - && Arrays.stream(excludedGroups.split(",")).anyMatch(groups::contains)) { - annotation.setEnabled(false); - return; - } - - // exclude test which doesn't comply multiuser flag - if (isMultiuser - && groups.contains(TestGroup.SINGLEUSER) - && !groups.contains(TestGroup.MULTIUSER)) { - annotation.setEnabled(false); - return; - } - - // exclude test which doesn't comply singleuser flag - if (!isMultiuser - && groups.contains(TestGroup.MULTIUSER) - && !groups.contains(TestGroup.SINGLEUSER)) { - annotation.setEnabled(false); - return; - } - - // exclude test which doesn't support current infrastructure - groups.remove(TestGroup.SINGLEUSER); - groups.remove(TestGroup.MULTIUSER); - groups.remove(TestGroup.GITHUB); - groups.remove(TestGroup.UNDER_REPAIR); - groups.remove(TestGroup.FLAKY); - if (!groups.isEmpty() && !groups.contains(infrastructure.toString().toLowerCase())) { - annotation.setEnabled(false); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/InjectTestOrganization.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/InjectTestOrganization.java deleted file mode 100644 index 2f7fe9b578..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/InjectTestOrganization.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.organization; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -/** - * To instantiate {@link TestOrganization} in test classes. - * - * @author Dmytro Nochevnov - */ -@Target({FIELD}) -@Retention(RUNTIME) -@Documented -public @interface InjectTestOrganization { - /** Organization name prefix. */ - String prefix() default ""; - - /** Parent organization name prefix. */ - String parentPrefix() default ""; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/TestOrganization.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/TestOrganization.java deleted file mode 100644 index 3a6a24189f..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/TestOrganization.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.organization; - -import javax.annotation.PreDestroy; -import org.eclipse.che.multiuser.organization.shared.dto.OrganizationDto; -import org.eclipse.che.selenium.core.client.TestOrganizationServiceClient; - -/** - * Represents organization in a test environment. - * - * @author Dmytro Nochevnov - */ -public class TestOrganization { - private final OrganizationDto organization; - private final TestOrganizationServiceClient testOrganizationServiceClient; - - public TestOrganization(String name, TestOrganizationServiceClient testOrganizationServiceClient) - throws Exception { - this.testOrganizationServiceClient = testOrganizationServiceClient; - organization = testOrganizationServiceClient.create(name); - } - - public TestOrganization( - String name, String parentId, TestOrganizationServiceClient testOrganizationServiceClient) - throws Exception { - this.testOrganizationServiceClient = testOrganizationServiceClient; - organization = testOrganizationServiceClient.create(name, parentId); - } - - /** Returns the name of the organization. */ - public String getName() { - return organization.getName(); - } - - /** Returns the id of the organization. */ - public String getId() { - return organization.getId(); - } - - public void addAdmin(String userId) throws Exception { - testOrganizationServiceClient.addAdmin(getId(), userId); - } - - public void addMember(String userId) throws Exception { - testOrganizationServiceClient.addMember(getId(), userId); - } - - /** Deletes organization. */ - @PreDestroy - public void delete() throws Exception { - testOrganizationServiceClient.deleteById(getId()); - } - - public String getQualifiedName() { - return organization.getQualifiedName(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/TestOrganizationInjector.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/TestOrganizationInjector.java deleted file mode 100644 index d20767689a..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/organization/TestOrganizationInjector.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.organization; - -import static java.lang.String.format; -import static org.eclipse.che.commons.lang.NameGenerator.generate; - -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.MembersInjector; -import com.google.inject.Provider; -import java.lang.reflect.Field; -import org.eclipse.che.selenium.core.client.TestOrganizationServiceClient; -import org.eclipse.che.selenium.core.client.TestOrganizationServiceClientFactory; -import org.eclipse.che.selenium.core.user.AdminTestUser; - -/** - * Injector for custom annotation {@link InjectTestOrganization}. - * - * @author Dmytro Nochevnov - */ -public class TestOrganizationInjector implements MembersInjector { - - private final Field field; - private final InjectTestOrganization injectTestOrganization; - private final Provider injectorProvider; - - public TestOrganizationInjector( - Field field, - InjectTestOrganization injectTestOrganization, - Provider injectorProvider) { - this.field = field; - this.injectTestOrganization = injectTestOrganization; - this.injectorProvider = injectorProvider; - } - - @Override - public void injectMembers(T instance) { - Injector injector = injectorProvider.get(); - - String name = generateName(); - String parentPrefix = injectTestOrganization.parentPrefix(); - - AdminTestUser adminTestUser = injector.getInstance(Key.get(AdminTestUser.class)); - - TestOrganizationServiceClientFactory testOrganizationServiceClient = - injector.getInstance(Key.get(TestOrganizationServiceClientFactory.class)); - - TestOrganizationServiceClient adminOrganizationServiceClient = - testOrganizationServiceClient.create(adminTestUser); - - TestOrganization testOrganization; - try { - if (parentPrefix.isEmpty()) { - testOrganization = new TestOrganization(name, adminOrganizationServiceClient); - } else { - String parentId = findInjectedOrganization(instance, parentPrefix); - testOrganization = new TestOrganization(name, parentId, adminOrganizationServiceClient); - } - - field.setAccessible(true); - field.set(instance, testOrganization); - } catch (Exception e) { - throw new RuntimeException( - format( - "Failed to instantiate organization with name '%s' in class '%s'", - injectTestOrganization.prefix(), instance.getClass().getName()), - e); - } - } - - private String generateName() { - String fieldNamePrefix = field.getName().substring(0, Math.min(field.getName().length(), 12)); - String annotationPrefix = injectTestOrganization.prefix(); - - String prefix = annotationPrefix.isEmpty() ? fieldNamePrefix : annotationPrefix; - - return generate(prefix + "-", 5); - } - - /** - * @return id of organization among the fields of instance with name which starts from - * orgNamePrefix - */ - private String findInjectedOrganization(T instance, String orgNamePrefix) { - for (Field field : instance.getClass().getDeclaredFields()) { - if (field.getType() == TestOrganization.class) { - field.setAccessible(true); - - TestOrganization org; - try { - org = (TestOrganization) field.get(instance); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } - - if (org != null && org.getName().startsWith(orgNamePrefix)) { - return org.getId(); - } - } - } - - throw new IllegalArgumentException( - format( - "Organization with name which starts from '%s' not found or isn't instantiated in class '%s'", - orgNamePrefix, instance.getClass().getName())); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/pageobject/InjectPageObject.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/pageobject/InjectPageObject.java deleted file mode 100644 index 742ac8d843..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/pageobject/InjectPageObject.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.pageobject; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -/** - * To instantiate different instances of the same page object. - * - * @author Anatolii Bazko - */ -@Target({FIELD}) -@Retention(RUNTIME) -@Documented -public @interface InjectPageObject { - int driverId(); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/pageobject/PageObjectsInjector.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/pageobject/PageObjectsInjector.java deleted file mode 100644 index 3a21392b19..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/pageobject/PageObjectsInjector.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.pageobject; - -import static java.lang.String.format; - -import com.google.inject.Inject; -import com.google.inject.Injector; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Stream; -import org.eclipse.che.commons.annotation.Nullable; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Injects fields annotated with {@link InjectPageObject}. All page objects with the same {@link - * InjectPageObject#driverId()} must share a common {@link SeleniumWebDriver} instance. - * - * @author Anatolii Bazko - */ -public abstract class PageObjectsInjector { - - private static final Logger LOG = LoggerFactory.getLogger(PageObjectsInjector.class); - - @Inject private SeleniumWebDriverFactory seleniumWebDriverFactory; - - public void injectMembers(Object testInstance, Injector injector) throws Exception { - Map> toInject = collectFieldsToInject(testInstance); - - for (Integer poIndex : toInject.keySet()) { - Map, Object> container = new HashMap<>(); - SeleniumWebDriver seleniumWebDriver = seleniumWebDriverFactory.create(); - - container.put(SeleniumWebDriver.class, seleniumWebDriver); - container.putAll(getDependenciesWithWebdriver(seleniumWebDriver)); - - for (Field f : toInject.get(poIndex)) { - try { - injectField(f, testInstance, container, injector); - } catch (Exception e) { - throw new RuntimeException( - format("Error of injection member '%s' into test '%s'.", f, testInstance), e); - } - } - } - } - - public abstract Map, Object> getDependenciesWithWebdriver( - SeleniumWebDriver seleniumWebDriver); - - private void injectField( - Field field, Object instance, Map, Object> container, Injector injector) - throws Exception { - Object object = instantiate(field.getType(), container, injector); - field.setAccessible(true); - field.set(instance, object); - } - - private Object instantiate(Class type, Map, Object> container, Injector injector) - throws Exception { - Object obj; - - Optional> constructor = findConstructor(type); - if (!constructor.isPresent()) { - // interface? get instance from a guice container - obj = injector.getInstance(type); - - } else { - Class[] parameterTypes = constructor.get().getParameterTypes(); - Object[] params = new Object[parameterTypes.length]; - - for (int i = 0; i < parameterTypes.length; i++) { - Object pt = container.get(parameterTypes[i]); - if (pt == null) { - pt = instantiate(parameterTypes[i], container, injector); - } - params[i] = pt; - } - - obj = constructor.get().newInstance(params); - } - - container.put(obj.getClass(), obj); - return obj; - } - - @Nullable - private Optional> findConstructor(Class type) { - return Stream.of(type.getConstructors()) - .filter( - c -> - c.isAnnotationPresent(com.google.inject.Inject.class) - || c.isAnnotationPresent(javax.inject.Inject.class)) - .findAny(); - } - - /** Find class fields annotated with {@link InjectPageObject}. */ - private Map> collectFieldsToInject(Object testInstance) { - Map> toInject = new HashMap<>(); - - for (Field f : testInstance.getClass().getDeclaredFields()) { - if (f.isAnnotationPresent(InjectPageObject.class)) { - InjectPageObject pageObject = f.getAnnotation(InjectPageObject.class); - int poIndex = pageObject.driverId(); - - Set fields = toInject.computeIfAbsent(poIndex, k -> new HashSet<>()); - fields.add(f); - } - } - - return toInject; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/project/ProjectTemplates.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/project/ProjectTemplates.java deleted file mode 100644 index 95c927d12f..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/project/ProjectTemplates.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.project; - -/** @author Musienko Maxim */ -public class ProjectTemplates { - public static final String C = "c.json"; - public static final String CPP = "cpp.json"; - public static final String PHP = "php.json"; - public static final String PYTHON = "python.json"; - public static final String NODE_JS = "node_js.json"; - public static final String MAVEN_SPRING = "maven_spring.json"; - public static final String MAVEN_SIMPLE = "maven_simple.json"; - public static final String MAVEN_JAVA_MULTIMODULE = "maven_java_multimodule.json"; - public static final String PLAIN_JAVA = "plain_java.json"; - public static final String CONSOLE_JAVA_SIMPLE = "console_java_simple.json"; - public static final String GO = "go.json"; - public static final String DOT_NET = "dotNet.json"; - public static final String PROJECT_OF_UNDEFINED_TYPE = "undefined.json"; - - private ProjectTemplates() {} -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/AdminTestUserProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/AdminTestUserProvider.java deleted file mode 100644 index 3b49741318..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/AdminTestUserProvider.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import org.eclipse.che.selenium.core.user.AdminTestUser; - -/** - * Admin test user provider. - * - * @author Dmytro Nochevnov - */ -public interface AdminTestUserProvider extends RemovableUserProvider {} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/DefaultTestUserProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/DefaultTestUserProvider.java deleted file mode 100644 index 56c281cb2b..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/DefaultTestUserProvider.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import org.eclipse.che.selenium.core.user.DefaultTestUser; - -/** - * Default test user provider. - * - * @author Dmytro Nochevnov - */ -public interface DefaultTestUserProvider extends RemovableUserProvider {} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/RemovableUserProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/RemovableUserProvider.java deleted file mode 100644 index 73b636dc29..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/RemovableUserProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import com.google.inject.Provider; -import java.io.IOException; -import org.eclipse.che.selenium.core.user.TestUser; - -/** - * Removable user provider. - * - * @author Dmytro Nochevnov - */ -public interface RemovableUserProvider extends Provider { - - /** Deletes user. */ - void delete() throws IOException; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestApiEndpointUrlProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestApiEndpointUrlProvider.java deleted file mode 100644 index 9be4175855..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestApiEndpointUrlProvider.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import com.google.inject.Provider; -import java.net.URL; - -/** - * Api endpoint. - * - * @author Anatolii Bazko - */ -public interface TestApiEndpointUrlProvider extends Provider {} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestDashboardUrlProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestDashboardUrlProvider.java deleted file mode 100644 index e163449d18..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestDashboardUrlProvider.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import com.google.inject.Provider; -import java.net.URL; - -/** - * Url to Dashboard. - * - * @author Anatolii Bazko - */ -public interface TestDashboardUrlProvider extends Provider {} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestIdeUrlProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestIdeUrlProvider.java deleted file mode 100644 index 54b79220db..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestIdeUrlProvider.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import com.google.inject.Provider; -import java.net.URL; - -/** - * Url to IDE. - * - * @author Anatolii Bazko - */ -public interface TestIdeUrlProvider extends Provider {} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestUserProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestUserProvider.java deleted file mode 100644 index 530149f501..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestUserProvider.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import org.eclipse.che.selenium.core.user.TestUser; - -/** - * New test user provider. - * - * @author Dmytro Nochevnov - */ -public interface TestUserProvider extends RemovableUserProvider {} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestWorkspaceAgentApiEndpointUrlProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestWorkspaceAgentApiEndpointUrlProvider.java deleted file mode 100644 index 469238bba0..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/provider/TestWorkspaceAgentApiEndpointUrlProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import java.net.URL; - -/** Workspace agent API endpoint */ -public interface TestWorkspaceAgentApiEndpointUrlProvider { - - /** - * get workspace agent API endpoint - * - * @param workspaceId - * @return workspace agent api endpoint URL - * @throws Exception - */ - URL get(String workspaceId) throws Exception; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestHttpJsonRequestFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestHttpJsonRequestFactory.java deleted file mode 100644 index d0a9c2ea83..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestHttpJsonRequestFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.requestfactory; - -import javax.validation.constraints.NotNull; -import org.eclipse.che.api.core.rest.DefaultHttpJsonRequestFactory; -import org.eclipse.che.api.core.rest.HttpJsonRequest; -import org.eclipse.che.api.core.rest.shared.dto.Link; - -/** @author Dmytro Nochevnov */ -public abstract class TestHttpJsonRequestFactory extends DefaultHttpJsonRequestFactory { - @Override - public HttpJsonRequest fromUrl(@NotNull String url) { - return super.fromUrl(url).setAuthorizationHeader(getAuthToken()); - } - - @Override - public HttpJsonRequest fromLink(@NotNull Link link) { - return super.fromLink(link).setAuthorizationHeader(getAuthToken()); - } - - protected abstract String getAuthToken(); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestUserHttpJsonRequestFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestUserHttpJsonRequestFactory.java deleted file mode 100644 index 98482a1550..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestUserHttpJsonRequestFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.requestfactory; - -import static java.lang.String.format; - -import com.google.inject.assistedinject.Assisted; -import com.google.inject.assistedinject.AssistedInject; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.user.TestUser; - -/** @author Dmytro Nochevnov */ -public class TestUserHttpJsonRequestFactory extends TestHttpJsonRequestFactory { - - private final TestAuthServiceClient authServiceClient; - private final TestUser testUser; - - @AssistedInject - public TestUserHttpJsonRequestFactory( - TestAuthServiceClient authServiceClient, @Assisted TestUser testUser) { - this.authServiceClient = authServiceClient; - this.testUser = testUser; - } - - @Override - protected String getAuthToken() { - try { - return authServiceClient.login(testUser.getName(), testUser.getPassword()); - } catch (Exception ex) { - throw new RuntimeException( - format("Failed to get access token for user '%s'", testUser.getName()), ex); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestUserHttpJsonRequestFactoryCreator.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestUserHttpJsonRequestFactoryCreator.java deleted file mode 100644 index 02ff999fcc..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/requestfactory/TestUserHttpJsonRequestFactoryCreator.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.requestfactory; - -import com.google.inject.assistedinject.Assisted; -import org.eclipse.che.selenium.core.user.TestUser; - -/** @author Dmytro Nochevnov */ -public interface TestUserHttpJsonRequestFactoryCreator { - TestUserHttpJsonRequestFactory create(@Assisted TestUser testUser); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/AdminTestUser.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/AdminTestUser.java deleted file mode 100644 index 6dacc1d413..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/AdminTestUser.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import com.google.inject.assistedinject.Assisted; -import com.google.inject.assistedinject.AssistedInject; -import java.io.IOException; -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.client.TestUserServiceClientFactory; -import org.eclipse.che.selenium.core.provider.RemovableUserProvider; - -/** - * Represents admin user in a test environment. - * - * @author Dmytro Nochevnov - */ -public class AdminTestUser extends TestUserImpl { - - /** To instantiate admin test user with specific name, e-mail, password and offline token. */ - @AssistedInject - public AdminTestUser( - TestUserServiceClientFactory testUserServiceClientFactory, - TestAuthServiceClient authServiceClient, - @Assisted RemovableUserProvider testUserProvider, - @Assisted("name") String name, - @Assisted("email") String email, - @Assisted("password") String password) - throws NotFoundException, ServerException, BadRequestException { - super(testUserServiceClientFactory, authServiceClient, testUserProvider, name, email, password); - } - - @Override - public void delete() throws IOException { - // we shouldn't delete admin user - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/DefaultTestUser.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/DefaultTestUser.java deleted file mode 100644 index c3f9010cc8..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/DefaultTestUser.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import com.google.inject.assistedinject.Assisted; -import com.google.inject.assistedinject.AssistedInject; -import java.io.IOException; -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.client.TestUserServiceClientFactory; -import org.eclipse.che.selenium.core.provider.RemovableUserProvider; - -/** - * Represents default test user in a test environment. - * - * @author Dmytro Nochevnov - */ -public class DefaultTestUser extends TestUserImpl { - - /** To instantiate default test user with specific name, e-mail, password and offline token. */ - @AssistedInject - public DefaultTestUser( - TestUserServiceClientFactory testUserServiceClientFactory, - TestAuthServiceClient authServiceClient, - @Assisted RemovableUserProvider testUserProvider, - @Assisted("name") String name, - @Assisted("email") String email, - @Assisted("password") String password) - throws NotFoundException, ServerException, BadRequestException { - super(testUserServiceClientFactory, authServiceClient, testUserProvider, name, email, password); - } - - @Override - public void delete() throws IOException { - super.delete(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUser.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUser.java deleted file mode 100644 index 752789e98e..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUser.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import java.io.IOException; - -/** - * Represents a user in a test environment. - * - * @author Anatolii Bazko - */ -public interface TestUser { - /** Returns user's email. */ - String getEmail(); - - /** Returns user's password. */ - String getPassword(); - - /** Re-login to product to obtain authentication token of the user. */ - String obtainAuthToken(); - - /** Return user's name. */ - String getName(); - - /** Return user's id. */ - String getId(); - - /** Remove user. */ - void delete() throws IOException; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserFactory.java deleted file mode 100644 index 4849fe85f7..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserFactory.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import com.google.inject.assistedinject.Assisted; -import org.eclipse.che.selenium.core.provider.RemovableUserProvider; - -/** - * @author Anton Korneta - * @author Dmytro Nochevnov - */ -public interface TestUserFactory { - - /** Creates test user instance with given name, e-mail, password and offline token */ - T create( - @Assisted("name") String name, - @Assisted("email") String email, - @Assisted("password") String password, - RemovableUserProvider testUserProvider); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserImpl.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserImpl.java deleted file mode 100644 index d5fcf521ba..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserImpl.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import static java.lang.String.format; - -import com.google.inject.assistedinject.Assisted; -import com.google.inject.assistedinject.AssistedInject; -import java.io.IOException; -import javax.annotation.PreDestroy; -import org.eclipse.che.api.core.BadRequestException; -import org.eclipse.che.api.core.NotFoundException; -import org.eclipse.che.api.core.ServerException; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.client.TestUserServiceClient; -import org.eclipse.che.selenium.core.client.TestUserServiceClientFactory; -import org.eclipse.che.selenium.core.provider.RemovableUserProvider; - -/** - * @author Anatolii Bazko - * @author Dmytro Nochevnov - * @author Anton Korneta - */ -public class TestUserImpl implements TestUser { - private final String email; - private final String password; - private final String name; - private final String id; - - private final TestUserServiceClient userServiceClient; - private final TestAuthServiceClient authServiceClient; - private final RemovableUserProvider testUserProvider; - - /** To instantiate user with specific name, e-mail, password and offline token. */ - @AssistedInject - public TestUserImpl( - TestUserServiceClientFactory testUserServiceClientFactory, - TestAuthServiceClient authServiceClient, - @Assisted RemovableUserProvider testUserProvider, - @Assisted("name") String name, - @Assisted("email") String email, - @Assisted("password") String password) - throws NotFoundException, ServerException, BadRequestException { - this.authServiceClient = authServiceClient; - this.testUserProvider = testUserProvider; - - this.name = name; - this.email = email; - this.password = password; - - this.userServiceClient = testUserServiceClientFactory.create(this); - this.id = userServiceClient.findByEmail(email).getId(); - } - - @Override - public String getEmail() { - return email; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public String obtainAuthToken() { - try { - return authServiceClient.login(name, password); - } catch (Exception e) { - throw new RuntimeException(format("Error of log into the product as user '%s'.", name), e); - } - } - - @Override - public String getName() { - return name; - } - - @Override - public String getId() { - return id; - } - - @Override - public String toString() { - return format( - "%s{name=%s, email=%s, id=%s}", - this.getClass().getSimpleName(), this.getName(), this.getEmail(), this.getId()); - } - - @Override - @PreDestroy - public void delete() throws IOException { - testUserProvider.delete(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserNamespaceResolver.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserNamespaceResolver.java deleted file mode 100644 index c567780a18..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/user/TestUserNamespaceResolver.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -/** @author Anatolii Bazko */ -public interface TestUserNamespaceResolver { - - /** Returns namespace for given user name. */ - String resolve(String username); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/DockerUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/DockerUtil.java deleted file mode 100644 index 1444698a17..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/DockerUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -import static java.lang.String.format; - -import com.google.inject.Inject; -import com.google.inject.name.Named; -import java.io.IOException; -import java.nio.file.Path; -import javax.inject.Singleton; -import org.eclipse.che.selenium.core.utils.process.ProcessAgent; -import org.eclipse.che.selenium.core.utils.process.ProcessAgentException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This is set of methods which operate with docker containers. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class DockerUtil { - private static final Logger LOG = LoggerFactory.getLogger(DockerUtil.class); - - @Inject - @Named("che.host") - private String cheHostParameter; - - @Inject private ProcessAgent processAgent; - - /** - * Checks if IP address of host where program is running is the same as value of 'che.host' - * parameter. - * - * @return {@code true} if only program is running on the host with the same IP address as Che - */ - public boolean isCheRunLocally() { - String command = "docker run --rm --net host eclipse/che-ip:nightly"; - - try { - String cheIpAddress = processAgent.process(command); - - if (cheIpAddress != null && cheHostParameter.contains(cheIpAddress)) { - return true; - } - } catch (IOException e) { - LOG.warn("Can't check if Eclipse Che run locally.", e); - } - - return false; - } - - /** - * Copies files container to the host computer. - * - * @param containerId ID of container which we is being copped from - * @param pathInsideContainer destination of files in the container - * @param pathOnHost placement of files on the host computer - * @throws IOException - */ - public void copyFromContainer(String containerId, Path pathInsideContainer, Path pathOnHost) - throws IOException { - String copyCommand = - format("docker cp %1$s:%2$s %3$s", containerId, pathInsideContainer, pathOnHost); - - processAgent.process(copyCommand); - } - - /** - * Copies files from the the host computer to container. - * - * @param containerId ID of container which we is being copped to - * @param pathOnHost placement of files on the host computer - * @param pathInsideContainer destination of files in the container - * @throws IOException - */ - public void copyIntoContainer(String containerId, Path pathOnHost, Path pathInsideContainer) - throws IOException { - String copyCommand = - format("docker cp %1$s %2$s:%3$s", pathOnHost, containerId, pathInsideContainer); - - processAgent.process(copyCommand); - } - - /** - * Obtains ID of container kind of 'selenium_chromenode' with certain value of '{@code - * .NetworkSettings.Networks.selenium_selenium_grid_internal.IPAddress}' runtime config parameter. - * - * @param IP internal IP address of grid node - * @return ID of container - * @throws ProcessAgentException - */ - public String findGridNodeContainerByIp(String IP) throws ProcessAgentException { - String getContainerIdCommand = - format( - "docker ps -q --filter='name=selenium_chromenode*' | xargs docker inspect --format '{{ .Id }} {{ .NetworkSettings.Networks.selenium_selenium_grid_internal.IPAddress }}' | grep %s | awk 'NR>0 {print $1;}'", - IP); - - return processAgent.process(getContainerIdCommand); - } - - /** - * Delete files inside container . - * - * @param gridNodeContainerId ID of container which holds removing files - * @param pathToDelete placement of files to remove inside container - * @throws ProcessAgentException - */ - public void delete(String gridNodeContainerId, Path pathToDelete) throws ProcessAgentException { - String deleteInsideContainer = - format("docker exec -i %s sh -c 'rm -fr %s'", gridNodeContainerId, pathToDelete); - - processAgent.process(deleteInsideContainer); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/FileUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/FileUtil.java deleted file mode 100644 index a0af060913..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/FileUtil.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -import static java.util.stream.Collectors.toList; - -import com.google.common.base.Joiner; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - -/** @author Dmytro Nochevnov */ -public class FileUtil { - - /** - * Checks if directoryToRemove is empty itself and remove it if it is empty only. - * - * @param directoryToRemove directory which is verified for emptiness - * @throws IOException - */ - public static void removeDirectoryIfItIsEmpty(Path directoryToRemove) throws IOException { - if (Files.exists(directoryToRemove) - && Files.isDirectory(directoryToRemove) - && Files.list(directoryToRemove).collect(toList()).isEmpty()) { - - Files.delete(directoryToRemove); - } - } - - public static List readFile(Path pathToFile) throws IOException { - return Files.readAllLines(pathToFile, StandardCharsets.UTF_8); - } - - public static List readFile(String pathToFile) throws IOException { - Path filePath = Paths.get(URI.create(pathToFile)); - - return readFile(filePath); - } - - public static List readFile(URL pathToFile) throws IOException, URISyntaxException { - Path filePath = Paths.get(pathToFile.toURI()); - - return readFile(filePath); - } - - public static List readFile(URI pathToFile) throws IOException, URISyntaxException { - Path filePath = Paths.get(pathToFile); - - return readFile(filePath); - } - - public static String readFileToString(String pathToFile) throws IOException { - List textFromFile = readFile(pathToFile); - return Joiner.on('\n').join(textFromFile); - } - - public static String readFileToString(Path pathToFile) throws IOException { - List textFromFile = readFile(pathToFile); - return Joiner.on('\n').join(textFromFile); - } - - public static String readFileToString(URL pathToFile) throws IOException, URISyntaxException { - List textFromFile = readFile(pathToFile); - return Joiner.on('\n').join(textFromFile); - } - - public static String readFileToString(URI pathToFile) throws IOException, URISyntaxException { - List textFromFile = readFile(pathToFile); - return Joiner.on('\n').join(textFromFile); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/HttpUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/HttpUtil.java deleted file mode 100644 index 63d61496a0..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/HttpUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; - -public class HttpUtil { - - /** - * Gets the status code from URL. - * - * @param url url to check - * @return {@link HttpURLConnection#getResponseCode()} - */ - public static int getUrlResponseCode(String url) throws IOException { - URL connectionUrl = new URL(url); - HttpURLConnection connection = (HttpURLConnection) connectionUrl.openConnection(); - connection.setRequestMethod("GET"); - - return connection.getResponseCode(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/PlatformUtils.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/PlatformUtils.java deleted file mode 100644 index fc941bd7a3..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/PlatformUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -/** - * Platform utils. - * - * @author Vlad Zhukovskyi - */ -public class PlatformUtils { - - private static final String OS = System.getProperty("os.name").toLowerCase(); - private static final boolean IS_MAC = OS.startsWith("mac"); - - private PlatformUtils() {} - - /** - * Returns whether current operation system is Mac OS or not. - * - * @return {@code true} is current operation system is Mac os - */ - public static boolean isMac() { - return IS_MAC; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/UrlUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/UrlUtil.java deleted file mode 100644 index 0f3c0d6292..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/UrlUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -import java.net.MalformedURLException; -import java.net.URL; - -/** @author Alexander Garagatyi */ -public class UrlUtil { - private static final int DEFAULT_HTTP_PORT = 80; - private static final int DEFAULT_HTTPS_PORT = 443; - - /** - * Creates {@link URL} using provided parameters. - * - * @throws IllegalArgumentException in case URL creation fails because of provided parameters - */ - public static URL url(String protocol, String host, int port, String path) - throws IllegalArgumentException { - if ((DEFAULT_HTTP_PORT == port && "http".equals(protocol)) - || (DEFAULT_HTTPS_PORT == port && "https".equals(protocol))) { - // prettify URL in case of default port for the protocol - // -1 should be used in case port is equal to protocol's default one - port = -1; - } - try { - return new URL(protocol, host, port, path); - } catch (MalformedURLException e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - private UrlUtil() {} -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/WaitUtils.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/WaitUtils.java deleted file mode 100644 index 7adb0d9861..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/WaitUtils.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -import static java.lang.Thread.sleep; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.BooleanSupplier; - -/** - * @author Mykola Morhun - * @author Ihor Okhrimenko - * @author Dmytro Nochevnov - */ -public class WaitUtils { - - public static final int DEFAULT_TIMEOUT_IN_SEC = LOAD_PAGE_TIMEOUT_SEC; - public static final int DEFAULT_DELAY_BETWEEN_ATTEMPTS_IN_MILLISECONDS = 500; - - /** - * Waits given time. When thread catch interrupt signal, than it immediately ends. - * - * @param seconds time to wait in seconds - */ - public static void sleepQuietly(int seconds) { - sleepQuietly(seconds, TimeUnit.SECONDS); - } - - /** - * Waits given time. When thread catch interrupt signal, than it immediately ends. - * - * @param timeout time to wait - * @param timeUnit time unit of the timeout parameter - */ - public static void sleepQuietly(long timeout, TimeUnit timeUnit) { - long millisecondToWait = timeUnit.toMillis(timeout); - try { - sleep(millisecondToWait); - } catch (InterruptedException e) { - // Taking into account, that tests newer interrupts each other, - // we can say, that this interrupt signal is external - // and it wants to immediately stop execution of this thread. - // According to the above, method, which calls this method - // has no mechanisms for handling interrupts (so, invoke of - // interrupt() method has no effect). - // Considering the above, we must stop this thread here immediately. - throw new RuntimeException(e); - } - } - - /** - * Waits during {@code timeout} until {@code condition} has a "true" state. - * - * @param condition expression which should be performed - * @param timeout waiting time - * @param delayBetweenAttemptsInMilliseconds delay between tries of {@code condition} execution in - * milliseconds - */ - public static void waitSuccessCondition( - BooleanSupplier condition, - long timeout, - long delayBetweenAttemptsInMilliseconds, - TimeUnit timeoutTimeUnit) - throws InterruptedException, TimeoutException, ExecutionException { - ExecutorService executor = Executors.newSingleThreadExecutor(); - Future conditionVerification = - executor.submit( - (Callable) - () -> { - while (!condition.getAsBoolean()) { - sleepQuietly(delayBetweenAttemptsInMilliseconds, TimeUnit.MILLISECONDS); - } - - return null; - }); - - executor.shutdown(); - if (!executor.awaitTermination(timeout, timeoutTimeUnit)) { - throw new TimeoutException( - String.format( - "Expected condition failed: waiting for %s %s with %s MILLISECONDS interval", - timeout, timeoutTimeUnit, delayBetweenAttemptsInMilliseconds)); - } - - conditionVerification.get(); - } - - /** - * Waits during {@code timeout} until {@code condition} has a "true" state. - * - * @param condition expression which should be performed - * @param timeout waiting time - */ - public static void waitSuccessCondition( - BooleanSupplier condition, long timeout, TimeUnit timeUnit) - throws InterruptedException, TimeoutException, ExecutionException { - waitSuccessCondition( - condition, timeout, DEFAULT_DELAY_BETWEEN_ATTEMPTS_IN_MILLISECONDS, timeUnit); - } - - /** - * Waits during {@code timeoutInSec} until {@code condition} has a "true" state. - * - * @param condition expression which should be performed - * @param timeoutInSec waiting time in seconds - */ - public static void waitSuccessCondition(BooleanSupplier condition, long timeoutInSec) - throws InterruptedException, TimeoutException, ExecutionException { - waitSuccessCondition(condition, timeoutInSec, TimeUnit.SECONDS); - } - - /** - * Waits until {@code condition} has a "true" state. - * - * @param condition expression which should be performed - */ - public static void waitSuccessCondition(BooleanSupplier condition) - throws InterruptedException, TimeoutException, ExecutionException { - waitSuccessCondition(condition, DEFAULT_TIMEOUT_IN_SEC); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/WorkspaceDtoDeserializer.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/WorkspaceDtoDeserializer.java deleted file mode 100644 index c59616a0cc..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/WorkspaceDtoDeserializer.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -import static java.util.Objects.requireNonNull; - -import com.google.common.base.Charsets; -import com.google.common.io.Resources; -import com.google.gson.JsonSyntaxException; -import com.google.inject.Inject; -import java.io.IOException; -import java.net.URL; -import javax.inject.Named; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.dto.server.DtoFactory; -import org.eclipse.che.selenium.core.constant.Infrastructure; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Creates workspace config from JSON stored in resources. Takes into account current infrastructure - * implementation set by property. - * - * @author Mihail Kuznyetsov - * @author Alexander Garagatyi - */ -public class WorkspaceDtoDeserializer { - - private static final Logger LOG = LoggerFactory.getLogger(WorkspaceDtoDeserializer.class); - - @Inject - @Named("che.infrastructure") - private Infrastructure infrastructure; - - public WorkspaceConfigDto deserializeWorkspaceTemplate(String workspaceTemplateName) { - requireNonNull(workspaceTemplateName); - - try { - - URL url = - Resources.getResource( - WorkspaceDtoDeserializer.class, getTemplateDirectory(workspaceTemplateName)); - return DtoFactory.getInstance() - .createDtoFromJson(Resources.toString(url, Charsets.UTF_8), WorkspaceConfigDto.class); - } catch (IOException | IllegalArgumentException | JsonSyntaxException e) { - LOG.error( - "Fail to read workspace template {} for infrastructure {} because {} ", - workspaceTemplateName, - getTemplateDirectory(workspaceTemplateName), - e.getMessage()); - throw new RuntimeException(e.getLocalizedMessage(), e); - } - } - - private String getTemplateDirectory(String workspaceTemplateName) { - String templateDirectoryName; - switch (infrastructure) { - case OSIO: - case K8S: - templateDirectoryName = Infrastructure.OPENSHIFT.toString().toLowerCase(); - break; - - default: - templateDirectoryName = infrastructure.toString().toLowerCase(); - } - - return String.format( - "/templates/workspace/%s/%s", templateDirectoryName, workspaceTemplateName); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/executor/CommandExecutor.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/executor/CommandExecutor.java deleted file mode 100644 index 7b7fde012b..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/executor/CommandExecutor.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils.executor; - -import java.io.IOException; - -/** - * Executes commands of CLI application. - * - * @author Dmytro Nochevnov - */ -public interface CommandExecutor { - - /** - * Executes CLI application command. - * - * @param command CLI command to execute - * @return response of CLI command - * @throws IOException if there is a problem with command execution. - */ - String execute(String command) throws IOException; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/process/ProcessAgent.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/process/ProcessAgent.java deleted file mode 100644 index d726c680ac..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/process/ProcessAgent.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils.process; - -import static java.lang.String.format; - -import com.google.inject.Singleton; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** @author Dmytro Nochevnov */ -@Singleton -public class ProcessAgent { - private static final Logger LOG = LoggerFactory.getLogger(ProcessAgent.class); - - public String process(String command) throws ProcessAgentException { - try { - Process process = getProcess(command); - - int exitStatus = process.waitFor(); - InputStream in = process.getInputStream(); - InputStream err = process.getErrorStream(); - - return processOutput(exitStatus, in, err); - } catch (Exception e) { - String errMessage = format("Can't process command '%s'.", command); - throw new ProcessAgentException(errMessage, e); - } - } - - private Process getProcess(String command) throws IOException { - ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", command); - return pb.start(); - } - - private String processOutput(int exitStatus, InputStream in, InputStream error) throws Exception { - String output = readOutput(in); - String errorOutput = readOutput(error); - - if (exitStatus == 0 && errorOutput.isEmpty()) { - return output; - } - - throw new Exception(format("Output: %s; Error: %s.", output, errorOutput)); - } - - private String readOutput(InputStream in) throws IOException { - try { - String output = IOUtils.toString(in, Charset.forName("UTF-8")); - if (output.endsWith("\n")) { - output = output.substring(0, output.length() - 1); - } - return output; - } finally { - in.close(); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/process/ProcessAgentException.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/process/ProcessAgentException.java deleted file mode 100644 index c0b242e17e..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/utils/process/ProcessAgentException.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils.process; - -import java.io.IOException; - -/** @author Dmytro Nochevnov */ -public class ProcessAgentException extends IOException { - public ProcessAgentException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/AbstractUploadUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/AbstractUploadUtil.java deleted file mode 100644 index 6575c6a78f..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/AbstractUploadUtil.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import static com.google.common.io.Files.createTempDir; - -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.zip.ZipOutputStream; -import org.eclipse.che.commons.lang.ZipUtils; -import org.eclipse.che.selenium.core.SeleniumWebDriver; - -/** @author Dmytro Nochevnov */ -public abstract class AbstractUploadUtil implements UploadUtil { - private static final String ZIP_FILE_NAME = "upload.zip"; - - @Override - public final Path prepareToUpload(SeleniumWebDriver seleniumWebDriver, Path localPath) - throws IOException { - if (!localPath.toFile().isFile()) { - Path zipFile = Paths.get(createTempDir().toString()).resolve(ZIP_FILE_NAME); - - try (ZipOutputStream out = ZipUtils.stream(zipFile)) { - ZipUtils.add(out, localPath, localPath); - } - localPath = zipFile; - } - - return prepareFileToUpload(seleniumWebDriver, localPath); - } - - abstract Path prepareFileToUpload(SeleniumWebDriver seleniumWebDriver, Path localPathtoFile) - throws IOException; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedFileUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedFileUtil.java deleted file mode 100644 index e449d41b47..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedFileUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import java.io.IOException; -import java.util.List; -import org.eclipse.che.selenium.core.SeleniumWebDriver; - -/** - * This is set of methods to work with files which are downloaded by WebDriver. - * - * @author Dmytro Nochevnov - */ -public interface DownloadedFileUtil { - - /** - * Get list of files which package holds. - * - * @param seleniumWebDriver which operates with UI - * @param downloadedPackageName downloaded package to unzip - * @return list of files which package holds - */ - List getPackageFileList(SeleniumWebDriver seleniumWebDriver, String downloadedPackageName) - throws IOException; - - /** - * Obtains content of downloaded file. - * - * @param seleniumWebDriver which operates with UI - * @param downloadedFileName downloaded file name - * @return content of file - */ - String getDownloadedFileContent(SeleniumWebDriver seleniumWebDriver, String downloadedFileName) - throws IOException; - - /** - * Removes downloaded file. - * - * @param seleniumWebDriver which operates with UI - * @param filenames downloaded file name - */ - void removeDownloadedFiles(SeleniumWebDriver seleniumWebDriver, String... filenames) - throws IOException; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedIntoGridFileUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedIntoGridFileUtil.java deleted file mode 100644 index 48ed7af962..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedIntoGridFileUtil.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import static com.google.common.io.Files.createTempDir; -import static java.nio.file.Paths.get; -import static java.util.Arrays.stream; -import static org.eclipse.che.commons.lang.ZipUtils.unzip; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; -import org.apache.commons.io.FileUtils; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.utils.DockerUtil; - -/** - * This is set of methods which operate with files which are downloaded by WebDriver which is - * running inside the Docker container. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class DownloadedIntoGridFileUtil implements DownloadedFileUtil { - // default download directory in selenium chrome-node 3.10+ which doesn't depend from value of - // "download.default_directory" preference - private final String downloadDir = "/home/seluser/Downloads"; - - private final DockerUtil dockerUtil; - - @Inject - public DownloadedIntoGridFileUtil(DockerUtil dockerUtil) { - this.dockerUtil = dockerUtil; - } - - @Override - public List getPackageFileList( - SeleniumWebDriver seleniumWebDriver, String downloadedPackageName) throws IOException { - Path tempDirectory = Paths.get(createTempDir().toString()); - dockerUtil.copyFromContainer( - seleniumWebDriver.getGridNodeContainerId(), - get(downloadDir, downloadedPackageName), - tempDirectory); - - File packageFile = Paths.get(tempDirectory.toString(), downloadedPackageName).toFile(); - unzip(packageFile, tempDirectory.toFile()); - FileUtils.deleteQuietly(packageFile); - - List packageFileList = - FileUtils.listFiles(tempDirectory.toFile(), null, true) - .stream() - .map(file -> file.toString().replace(tempDirectory.toString() + File.separatorChar, "")) - .collect(Collectors.toList()); - Collections.sort(packageFileList); - - FileUtils.deleteQuietly(tempDirectory.toFile()); - - return packageFileList; - } - - @Override - public String getDownloadedFileContent( - SeleniumWebDriver seleniumWebDriver, String downloadedFileName) throws IOException { - Path tempDirectory = Paths.get(createTempDir().toString()); - - dockerUtil.copyFromContainer( - seleniumWebDriver.getGridNodeContainerId(), - get(downloadDir, downloadedFileName), - tempDirectory); - String content = FileUtils.readFileToString(tempDirectory.resolve(downloadedFileName).toFile()); - - FileUtils.deleteQuietly(tempDirectory.toFile()); - - return content; - } - - @Override - public void removeDownloadedFiles(SeleniumWebDriver seleniumWebDriver, String... filenames) - throws IOException { - String gridNodeContainerId = seleniumWebDriver.getGridNodeContainerId(); - stream(filenames) - .forEach( - filename -> { - try { - dockerUtil.delete(gridNodeContainerId, get(downloadDir, filename)); - } catch (IOException e) { - throw new RuntimeException(e); - } - }); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedLocallyFileUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedLocallyFileUtil.java deleted file mode 100644 index 8d2ba75fc8..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/DownloadedLocallyFileUtil.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import static com.google.common.io.Files.createTempDir; -import static java.nio.file.Files.deleteIfExists; -import static java.nio.file.Paths.*; -import static java.util.Arrays.stream; -import static org.eclipse.che.commons.lang.ZipUtils.unzip; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; -import org.apache.commons.io.FileUtils; -import org.eclipse.che.selenium.core.SeleniumWebDriver; - -/** - * This is set of methods which operate with files which are downloaded by WebDriver which is - * running locally. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class DownloadedLocallyFileUtil implements DownloadedFileUtil { - private final String downloadDir; - - @Inject - public DownloadedLocallyFileUtil(@Named("tests.tmp_dir") String downloadDir) { - this.downloadDir = downloadDir; - } - - @Override - public List getPackageFileList( - SeleniumWebDriver seleniumWebDriver, String downloadedPackageName) throws IOException { - Path tempDirectory = Paths.get(createTempDir().toString()); - File packageFile = Paths.get(downloadDir).resolve(downloadedPackageName).toFile(); - unzip(packageFile, tempDirectory.toFile()); - - List packageFileList = - FileUtils.listFiles(tempDirectory.toFile(), null, true) - .stream() - .map(file -> file.toString().replace(tempDirectory.toString() + File.separatorChar, "")) - .collect(Collectors.toList()); - Collections.sort(packageFileList); - - FileUtils.deleteQuietly(tempDirectory.toFile()); - - return packageFileList; - } - - @Override - public String getDownloadedFileContent( - SeleniumWebDriver seleniumWebDriver, String downloadedFileName) throws IOException { - return FileUtils.readFileToString(get(downloadDir, downloadedFileName).toFile()); - } - - @Override - public void removeDownloadedFiles(SeleniumWebDriver seleniumWebDriver, String... filenames) { - stream(filenames) - .forEach( - filename -> { - try { - deleteIfExists(get(downloadDir, filename)); - } catch (IOException e) { - throw new RuntimeException(e); - } - }); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/SeleniumWebDriverFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/SeleniumWebDriverFactory.java deleted file mode 100644 index 9c8cf6f428..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/SeleniumWebDriverFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.constant.TestBrowser; -import org.eclipse.che.selenium.core.utils.DockerUtil; - -/** @author Dmytro Nochevnov */ -@Singleton -public class SeleniumWebDriverFactory { - - @Inject - @Named("sys.browser") - TestBrowser browser; - - @Inject - @Named("sys.driver.port") - private String webDriverPort; - - @Inject - @Named("sys.grid.mode") - private boolean gridMode; - - @Inject - @Named("tests.tmp_dir") - private String downloadDir; - - @Inject private HttpJsonRequestFactory httpJsonRequestFactory; - - @Inject private DockerUtil dockerUtil; - - public SeleniumWebDriver create() { - return new SeleniumWebDriver( - browser, webDriverPort, gridMode, httpJsonRequestFactory, dockerUtil, downloadDir); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/SeleniumWebDriverHelper.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/SeleniumWebDriverHelper.java deleted file mode 100644 index a3d29219e6..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/SeleniumWebDriverHelper.java +++ /dev/null @@ -1,1612 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static java.util.stream.Collectors.toList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.APPLICATION_START_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.WIDGET_TIMEOUT_SEC; -import static org.openqa.selenium.Keys.ARROW_DOWN; -import static org.openqa.selenium.Keys.ARROW_LEFT; -import static org.openqa.selenium.Keys.ARROW_RIGHT; -import static org.openqa.selenium.Keys.ARROW_UP; -import static org.openqa.selenium.Keys.BACK_SPACE; -import static org.openqa.selenium.Keys.CONTROL; -import static org.openqa.selenium.Keys.DELETE; -import static org.openqa.selenium.Keys.ENTER; -import static org.openqa.selenium.Keys.F12; -import static org.openqa.selenium.support.ui.ExpectedConditions.elementSelectionStateToBe; -import static org.openqa.selenium.support.ui.ExpectedConditions.frameToBeAvailableAndSwitchToIt; -import static org.openqa.selenium.support.ui.ExpectedConditions.invisibilityOfAllElements; -import static org.openqa.selenium.support.ui.ExpectedConditions.invisibilityOfElementLocated; -import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfAllElementsLocatedBy; -import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfAllElements; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfAllElementsLocatedBy; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import java.nio.file.Path; -import java.util.List; -import java.util.function.UnaryOperator; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.action.ActionsFactory; -import org.eclipse.che.selenium.core.utils.WaitUtils; -import org.openqa.selenium.By; -import org.openqa.selenium.NoSuchElementException; -import org.openqa.selenium.StaleElementReferenceException; -import org.openqa.selenium.TimeoutException; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebDriverException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.interactions.Actions; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.ExpectedConditions; - -/** @author Ihor Okhrimenko */ -@Singleton -public class SeleniumWebDriverHelper { - private final int DEFAULT_TIMEOUT = LOAD_PAGE_TIMEOUT_SEC; - - private final SeleniumWebDriver seleniumWebDriver; - private final WebDriverWaitFactory webDriverWaitFactory; - private final ActionsFactory actionsFactory; - private final UploadUtil uploadUtil; - - @Inject - public SeleniumWebDriverHelper( - SeleniumWebDriver seleniumWebDriver, - WebDriverWaitFactory webDriverWaitFactory, - ActionsFactory actionsFactory, - UploadUtil uploadFileUtil) { - this.seleniumWebDriver = seleniumWebDriver; - this.webDriverWaitFactory = webDriverWaitFactory; - this.actionsFactory = actionsFactory; - this.uploadUtil = uploadFileUtil; - } - - /** - * Ensures {@code element} has got {@code value} in next steps: ensures element is visible and has - * empty value, sets {@code value} by sending corresponding keys to {@code element} and waits - * until element has got the {@code value}. Checks text by {@link WebElement#getAttribute(String)} - * - * @param elementLocator - * @param value - */ - public void setValue(By elementLocator, String value) { - waitVisibility(elementLocator).clear(); - waitValueEqualsTo(elementLocator, ""); - waitAndSendKeysTo(elementLocator, value); - waitValueEqualsTo(elementLocator, value); - } - - /** - * Ensures {@code element} has got {@code value} in next steps: ensures element is visible and has - * empty value, sets {@code value} by sending corresponding keys to {@code element} and waits - * until element has got the {@code value}. Checks text by {@link WebElement#getAttribute(String)} - * - * @param webElement - * @param value - */ - public void setValue(WebElement webElement, String value) { - waitVisibility(webElement).clear(); - waitValueEqualsTo(webElement, ""); - waitAndSendKeysTo(webElement, value); - waitValueEqualsTo(webElement, value); - } - - /** - * Ensures {@code element} has got {@code value} in next steps: ensures element is visible and has - * empty value, sets {@code value} by sending corresponding keys to {@code element} and waits - * until element has got the {@code value}. Checks text by {@link WebElement#getText()} - * - * @param elementLocator - * @param value - */ - public void setText(By elementLocator, String value) { - waitVisibility(elementLocator).clear(); - waitTextEqualsTo(elementLocator, ""); - waitAndSendKeysTo(elementLocator, value); - waitTextEqualsTo(elementLocator, value); - } - - /** - * Ensures {@code element} has got {@code value} in next steps: ensures element is visible and has - * empty value, sets {@code value} by sending corresponding keys to {@code element} and waits - * until element has got the {@code value}. Checks text by {@link WebElement#getText()} - * - * @param webElement - * @param value - */ - public void setText(WebElement webElement, String value) { - waitVisibility(webElement).clear(); - waitTextEqualsTo(webElement, "", DEFAULT_TIMEOUT); - waitAndSendKeysTo(webElement, value); - waitTextEqualsTo(webElement, value, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout}, until {@link WebElement} with provided {@code elementLocator} is - * visible - * - * @param elementLocator locator of element which should be checked - * @param timeout waiting time in seconds - * @return found element - */ - public WebElement waitVisibility(By elementLocator, int timeout) { - return webDriverWaitFactory.get(timeout).until(visibilityOfElementLocated(elementLocator)); - } - - /** - * Waits until {@link WebElement} with provided {@code elementLocator} is visible. - * - * @param elementLocator locator of element which should be checked - * @return found element - */ - public WebElement waitVisibility(By elementLocator) { - return waitVisibility(elementLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until provided {@code webElement} is visible. - * - * @param webElement element which should be checked - * @param timeout waiting time in seconds - * @return found element - */ - public WebElement waitVisibility(WebElement webElement, int timeout) { - return webDriverWaitFactory.get(timeout).until(visibilityOf(webElement)); - } - - /** - * Waits until provided {@code webElement} is visible. - * - * @param webElement element which should be checked - * @return found element - */ - public WebElement waitVisibility(WebElement webElement) { - return waitVisibility(webElement, DEFAULT_TIMEOUT); - } - - /** - * Waits until all of {@link WebElement}, which are found by {@code elementsLocator}, are visible, - * and gets them; - * - * @param elementsLocator common locator for multiple elements - * @return all elements which found by specified {@code elementLocator}, - *

    throws {@link org.openqa.selenium.TimeoutException} if at least one of the found - * elements is not visible after timeout; - */ - public List waitVisibilityOfAllElements(By elementsLocator) { - return waitVisibilityOfAllElements(elementsLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits during specified {@code timeout} until all of {@link WebElement}, which are found by - * {@code elementsLocator}, are visible and gets them. - * - * @param elementsLocator common locator for multiple elements - * @param timeout waiting time in seconds - * @return all elements which found by specified {@code elementLocator}, - *

    throws {@link org.openqa.selenium.TimeoutException} if at least one of the found - * elements is not visible after timeout; - */ - public List waitVisibilityOfAllElements(By elementsLocator, int timeout) { - return webDriverWaitFactory - .get(timeout) - .until(visibilityOfAllElementsLocatedBy(elementsLocator)); - } - - /** - * Waits until all of specified {@code elements}, are visible. - * - * @param elements web elements which should check - * @return provided {@code elements}, - *

    throws {@link org.openqa.selenium.TimeoutException} if at least one of the specified - * {@code elements} is not visible after timeout; - */ - public List waitAllVisibility(List elements) { - return waitAllVisibility(elements, DEFAULT_TIMEOUT); - } - - /** - * Waits during specified {@code timeout} until all of provided {@code elements}, are visible. - * - * @param elements web elements which should check - * @param timeout waiting time in seconds - * @return provided {@code elements}, - *

    throws {@link org.openqa.selenium.TimeoutException} if at least one of the specified - * {@code elements} is not visible after timeout; - */ - public List waitAllVisibility(List elements, int timeout) { - return webDriverWaitFactory.get(timeout).until(visibilityOfAllElements(elements)); - } - - /** - * Waits visibility and gets {@link WebElement} for all of the {@code elementsLocators} - * - * @param elementsLocators locators for all elements which should be found - * @return all found elements, - *

    throws {@link org.openqa.selenium.TimeoutException} if at least one of the specified - * {@code elements} is not visible after timeout; - */ - public List waitAllVisibilityBy(List elementsLocators) { - return waitAllVisibilityBy(elementsLocators, DEFAULT_TIMEOUT); - } - - /** - * Waits visibility during timeout and gets {@link WebElement} for all of the {@code - * elementsLocators} - * - * @param elementsLocators locators for all elements which should be found - * @param timeout waiting timeout in seconds - * @return all found elements - */ - public List waitAllVisibilityBy(List elementsLocators, int timeout) { - return elementsLocators - .stream() - .map((elementLocator -> waitVisibility(elementLocator, timeout))) - .collect(toList()); - } - - /** - * Waits during {@code timeout}, until {@link WebElement} with provided {@code elementLocator} is - * invisible. - * - * @param elementLocator locator of element which should be checked - * @param timeout waiting time in seconds - * @throw {@link org.openqa.selenium.TimeoutException} - if visible during timeout. - */ - public void waitInvisibility(By elementLocator, int timeout) { - webDriverWaitFactory.get(timeout).until(invisibilityOfElementLocated(elementLocator)); - } - - /** - * Waits until {@link WebElement} with provided {@code elementLocator} is invisible. - * - * @param elementLocator locator of element which should be checked - * @throw {@link org.openqa.selenium.TimeoutException} - if visible during timeout. - */ - public void waitInvisibility(By elementLocator) { - waitInvisibility(elementLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until provided {@code webElement} is invisible. - * - * @param webElement element which should be checked - * @param timeout waiting time in seconds - * @throw {@link org.openqa.selenium.TimeoutException} - if visible during timeout. - */ - public void waitInvisibility(WebElement webElement, int timeout) { - webDriverWaitFactory.get(timeout).until(invisibilityOfAllElements(asList(webElement))); - } - - /** - * Waits until provided {@code webElement} is invisible. - * - * @param webElement element which should be checked - * @throw {@link org.openqa.selenium.TimeoutException} - if visible during timeout. - */ - public void waitInvisibility(WebElement webElement) { - waitInvisibility(webElement, DEFAULT_TIMEOUT); - } - - /** - * Waits until each item from specified {@code elements} be invisible. - * - * @param elements web elements which should be checked - */ - public void waitAllInvisibility(List elements) { - webDriverWaitFactory - .get(DEFAULT_TIMEOUT) - .until(ExpectedConditions.invisibilityOfAllElements(elements)); - } - - /** - * Waits during {@code timeout} until each item from specified {@code elements} be invisible. - * - * @param elements web elements which should be checked - * @param timeout waiting timeout in seconds - */ - public void waitAllInvisibility(List elements, int timeout) { - webDriverWaitFactory.get(timeout).until(ExpectedConditions.invisibilityOfAllElements(elements)); - } - - /** - * Waits until each {@link WebElement}, which defined by locator from {@code elementsLocators}, be - * invisible. - * - * @param elementsLocators locators of each elements which should be checked - */ - public void waitAllInvisibilityBy(List elementsLocators) { - waitAllInvisibilityBy(elementsLocators, DEFAULT_TIMEOUT); - } - - /** - * Waits until each {@link WebElement}, which defined by locator from {@code elementsLocators}, be - * invisible. - * - * @param elementsLocators locators of each elements which should be checked - * @param timeout waiting timeout in seconds - */ - public void waitAllInvisibilityBy(List elementsLocators, int timeout) { - elementsLocators.forEach(element -> waitInvisibility(element, timeout)); - } - - /** - * Waits during {@code timeout} until {@link WebElement} with provided {@code elementLocator} is - * attached to DOM. - * - *

    Note! It does not mean that element is visible. - * - * @param elementLocator locator of element which should be checked - * @param timeout waiting time in seconds - * @return found element - */ - public WebElement waitPresence(By elementLocator, int timeout) { - return webDriverWaitFactory.get(timeout).until(presenceOfElementLocated(elementLocator)); - } - - /** - * Waits until {@link WebElement} with provided {@code elementLocator} is attached to DOM. - * - *

    Note! It does not mean that element is visible. - * - * @param elementLocator - * @return found element - */ - public WebElement waitPresence(By elementLocator) { - return waitPresence(elementLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits until all {@link WebElement} with provided {@code elementsLocator} are attached to DOM. - * - *

    Note! It does not mean that elements are visible. - * - * @param elementsLocator common locator for multiple elements - * @return all found elements - */ - public List waitPresenceOfAllElements(By elementsLocator) { - return waitPresenceOfAllElements(elementsLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until all {@link WebElement} with provided {@code elementsLocator} - * is attached to DOM. - * - *

    Note! It does not mean that elements are visible. - * - * @param elementsLocator common locator for multiple elements - * @param timeout waiting timeout in seconds - * @return all found elements - */ - public List waitPresenceOfAllElements(By elementsLocator, int timeout) { - return webDriverWaitFactory.get(timeout).until(presenceOfAllElementsLocatedBy(elementsLocator)); - } - - /** - * Waits until {@link WebElement} with specified {@code elementLocator} is visible, and types text - * in it. - * - * @param elementLocator locator of element in which {@code text} should be sent - * @param text text for sending - */ - public void waitAndSendKeysTo(By elementLocator, String text) { - waitAndSendKeysTo(elementLocator, text, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until {@link WebElement} with specified {@code elementLocator} is - * visible, and types text in it. - * - * @param elementLocator locator of element in which {@code text} should be sent - * @param text text for sending - * @param timeout waiting timeout in seconds - */ - public void waitAndSendKeysTo(By elementLocator, String text, int timeout) { - waitVisibility(elementLocator, timeout).sendKeys(text); - } - - /** - * Waits until {@code webElement} is visible, and types text in it. - * - * @param webElement element in which {@code text} should be sent - * @param text text for sending - */ - public void waitAndSendKeysTo(WebElement webElement, String text) { - waitVisibility(webElement).sendKeys(text); - } - - /** - * Types {@code text} - * - * @param text text for sending - */ - public void sendKeys(String text) { - actionsFactory.createAction(seleniumWebDriver).sendKeys(text).perform(); - } - - /** - * Waits visibility of {@link WebElement} with provided {@code elementLocator} and gets text. - * - * @param elementLocator locator of element from which text should be got - * @return text which extracted from element by {@link WebElement#getAttribute(String)} - */ - public String waitVisibilityAndGetValue(By elementLocator) { - return waitVisibilityAndGetValue(elementLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} visibility of {@link WebElement} with specified {@code - * elementLocator} and gets text. - * - * @param elementLocator locator of element from which text should be got - * @param timeout waiting time in seconds - * @return text which extracted from element by {@link WebElement#getAttribute(String)} - */ - public String waitVisibilityAndGetValue(By elementLocator, int timeout) { - return waitVisibilityAndGetAttribute(elementLocator, "value", timeout); - } - - /** - * Waits visibility of provided {@code webElement} and gets text. - * - * @param webElement element, text from which should be got - * @return text which extracted from element by {@link WebElement#getAttribute(String)} - */ - public String waitVisibilityAndGetValue(WebElement webElement) { - return waitVisibilityAndGetValue(webElement, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} visibility of provided {@code webElement} and gets text. - * - * @param webElement element, text from which should be got - * @param timeout waiting time in seconds - * @return text which extracted from element by {@link WebElement#getAttribute(String)} - */ - public String waitVisibilityAndGetValue(WebElement webElement, int timeout) { - return waitVisibilityAndGetAttribute(webElement, "value", timeout); - } - - /** - * Waits visibility of {@link WebElement} with provided {@code elementLocator} and gets text from - * its {@code attribute}. - * - * @param elementLocator locator of element from which attribute should be got - * @param attribute name of element attribute - * @return text which extracted from element by {@link WebElement#getAttribute(String)} - */ - public String waitVisibilityAndGetAttribute(By elementLocator, String attribute) { - return waitVisibilityAndGetAttribute(elementLocator, attribute, DEFAULT_TIMEOUT); - } - - /** - * Waits visibility during {@code timeout} of {@link WebElement} with provided {@code - * elementLocator} and gets text from its {@code attribute}. - * - * @param elementLocator locator of element from which attribute should be got - * @param attribute name of element attribute - * @return text which extracted from element by {@link WebElement#getAttribute(String)} - */ - public String waitVisibilityAndGetAttribute(By elementLocator, String attribute, int timeout) { - return waitVisibility(elementLocator, timeout).getAttribute(attribute); - } - - /** - * Waits visibility of specified {@code element} and gets text from its {@code attribute}. - * - * @param element element from which attribute should be got - * @param attribute name of element attribute - * @return text which extracted from element by {@link WebElement#getAttribute(String)} - */ - public String waitVisibilityAndGetAttribute(WebElement element, String attribute) { - return waitVisibilityAndGetAttribute(element, attribute, DEFAULT_TIMEOUT); - } - - /** - * Waits visibility during {@code timeout} of specified {@code element} and gets text from its - * {@code attribute}. - * - * @param element element from which attribute should be got - * @param attribute name of element attribute - * @return text which extracted from element by {@link WebElement#getAttribute(String)} - */ - public String waitVisibilityAndGetAttribute(WebElement element, String attribute, int timeout) { - return waitVisibility(element, timeout).getAttribute(attribute); - } - - /** - * Waits visibility of element which specified by {@code elementLocator} and gets provided {@code - * cssPropertyName} from it. - * - * @param elementLocator locator of the investigating element - * @param cssPropertyName name of the css properties which should be extracted - * @return value of the specified {@code cssPropertyName} - */ - public String waitAndGetCssValue(By elementLocator, String cssPropertyName) { - return waitVisibility(elementLocator).getCssValue(cssPropertyName); - } - - /** - * Waits until specified {@code cssPropertyName} in the element which defined by provided {@code - * elementLocator} is equals to {@code expectedValue}. - * - * @param elementLocator locator of the investigating element - * @param cssPropertyName name of the css properties which should be extracted - * @param expectedValue expected value of the specified {@code cssPropertyName} - */ - public void waitCssValueEqualsTo( - By elementLocator, String cssPropertyName, String expectedValue) { - waitSuccessCondition( - driver -> waitAndGetCssValue(elementLocator, cssPropertyName).equals(expectedValue)); - } - - /** - * Waits visibility of {@link WebElement} with provided {@code elementLocator} and gets text. - * - * @param elementLocator element from which text should be got - * @return element text by {@link WebElement#getText()} - */ - public String waitVisibilityAndGetText(By elementLocator) { - return waitVisibilityAndGetText(elementLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits visibility during {@code timeout} of {@link WebElement} with provided {@code - * elementLocator} and gets text. - * - * @param elementLocator element from which text should be got - * @param timeout waiting time in seconds - * @return element text by {@link WebElement#getText()} - */ - public String waitVisibilityAndGetText(By elementLocator, int timeout) { - return waitVisibility(elementLocator, timeout).getText(); - } - - /** - * Waits visibility of provided {@code webElement} and gets text. - * - * @param webElement element from which text should be got - * @return element text by {@link WebElement#getText()} - */ - public String waitVisibilityAndGetText(WebElement webElement) { - return waitVisibilityAndGetText(webElement, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} visibility of provided {@code webElement} and gets text. - * - * @param webElement element from which text should be got - * @param timeout waiting time in seconds - * @return element text by {@link WebElement#getText()} - */ - public String waitVisibilityAndGetText(WebElement webElement, int timeout) { - return waitVisibility(webElement, timeout).getText(); - } - - /** - * Waits during {@code timeout} until value extracted from {@link WebElement} with specified - * {@code locator} by {@link WebElement#getAttribute(String)} equals to provided {@code expected} - * one. - * - * @param locator locator of element in which value should be checked - * @param expected expected value which should be present in the element - * @param timeout waiting time in seconds - */ - public void waitValueEqualsTo(By locator, String expected, int timeout) { - String[] actual = new String[1]; - webDriverWaitFactory - .get(timeout, () -> format("\nexpected:\n'%s'\nbut was:\n'%s'\n", expected, actual[0])) - .until( - (ExpectedCondition) - driver -> { - actual[0] = waitVisibilityAndGetValue(locator, timeout); - return actual[0].contains(expected); - }); - } - - /** - * Waits until text extracted from {@link WebElement} with specified {@code elementLocator} by - * {@link WebElement#getAttribute(String)} equals to provided {@code expectedValue}. - * - * @param elementLocator locator of element in which text should be checked - * @param expectedValue expected text which should be present in the element - */ - public void waitValueEqualsTo(By elementLocator, String expectedValue) { - waitValueEqualsTo(elementLocator, expectedValue, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until value extracted from specified {@code element} by {@link - * WebElement#getAttribute(String)} equals to provided {@code expected} one. - * - * @param element element in which text should be checked - * @param expected expected value which should be present in the element - * @param timeout waiting time in seconds - */ - public void waitValueEqualsTo(WebElement element, String expected, int timeout) { - String[] actual = new String[1]; - webDriverWaitFactory - .get(timeout, () -> format("\nexpected:\n'%s'\nbut was:\n'%s'\n", expected, actual[0])) - .until( - (ExpectedCondition) - driver -> { - actual[0] = waitVisibilityAndGetValue(element, timeout); - return actual[0].equals(expected); - }); - } - - /** - * Waits until text extracted from specified {@code element} by {@link - * WebElement#getAttribute(String)} equals to provided {@code expectedValue}. - * - * @param element element in which text should be checked - * @param expectedValue expected text which should be present in the element - */ - public void waitValueEqualsTo(WebElement element, String expectedValue) { - waitValueEqualsTo(element, expectedValue, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until specified {@code element} contains the defined {@code - * expected} value. - * - *

    Note! The text is extracted by {@link WebElement#getAttribute(String)} method. - * - * @param element element which should be checked - * @param expected value which should be presented - * @param timeout waiting time in seconds - */ - public void waitValueContains(WebElement element, String expected, int timeout) { - String[] actual = new String[1]; - webDriverWaitFactory - .get( - timeout, - () -> format("\nactual value:\n'%s'\ndidn't contain:\n'%s'\n", actual[0], expected)) - .until( - (ExpectedCondition) - driver -> { - actual[0] = waitVisibilityAndGetValue(element, timeout); - return actual[0].contains(expected); - }); - } - - /** - * Waits until specified {@code element} contains the defined {@code expectedText}. - * - *

    Note! The text is extracted by {@link WebElement#getAttribute(String)} method. - * - * @param element element which should be checked - * @param expectedText text which should be presented - */ - public void waitValueContains(WebElement element, String expectedText) { - waitValueContains(element, expectedText, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until {@link WebElement} which defined by {@code elementLocator} - * contains the specified {@code expectedText}. - * - *

    Note! The text is extracted by {@link WebElement#getAttribute(String)} method. - * - * @param elementLocator locator of the element which should be checked - * @param expectedText text which should be present - * @param timeout waiting time in seconds - */ - public void waitValueContains(By elementLocator, String expectedText, int timeout) { - waitValueContains(waitVisibility(elementLocator, timeout), expectedText, timeout); - } - - /** - * Waits until {@link WebElement} which defined by {@code elementLocator} contains the specified - * {@code expectedText}. - * - *

    Note! The text is extracted by {@link WebElement#getAttribute(String)} method. - * - * @param elementLocator locator of the element which should be checked - * @param expectedText text which should be present - */ - public void waitValueContains(By elementLocator, String expectedText) { - waitValueContains(elementLocator, expectedText, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until text extracted from {@link WebElement} with specified {@code - * locator} by {@link WebElement#getText()} equals to provided {@code expected} one. - * - * @param locator locator of element in which text should be checked - * @param expected expected text which should be present in the element - * @param timeout waiting time in seconds - */ - public void waitTextEqualsTo(By locator, String expected, int timeout) { - String[] actual = new String[1]; - webDriverWaitFactory - .get(timeout, () -> format("\nexpected:\n'%s'\nbut was:\n'%s'\n", expected, actual[0])) - .until( - (ExpectedCondition) - driver -> { - actual[0] = waitVisibilityAndGetText(locator, timeout); - return actual[0].equals(expected); - }); - } - - /** - * Waits until text extracted from {@link WebElement} with specified {@code elementLocator} by - * {@link WebElement#getText()} equals to provided {@code expectedText}. - * - * @param elementLocator locator of element in which text should be checked - * @param expectedText expected text which should be present in the element - */ - public void waitTextEqualsTo(By elementLocator, String expectedText) { - waitTextEqualsTo(elementLocator, expectedText, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until text extracted from specified {@code element} by {@link - * WebElement#getText()} equals to provided {@code expected} one. - * - * @param element element in which text should be checked - * @param expected expected text which element text should be equal to - * @param timeout waiting time in seconds - */ - public void waitTextEqualsTo(WebElement element, String expected, int timeout) { - String[] actual = new String[1]; - webDriverWaitFactory - .get(timeout, () -> format("\nexpected:\n'%s'\nbut was:\n'%s'\n", expected, actual[0])) - .until( - (ExpectedCondition) - driver -> { - actual[0] = waitVisibilityAndGetText(element, timeout); - return actual[0].equals(expected); - }); - } - - /** - * Waits until text extracted from {@code webElement} by {@link WebElement#getText()} equals to - * provided {@code expectedText}. - * - * @param webElement element in which text should be checked - * @param expectedText expected text which element text should be equal to - */ - public void waitTextEqualsTo(WebElement webElement, String expectedText) { - waitTextEqualsTo(webElement, expectedText, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until specified {@code element} contains the specified {@code - * expected} one. - * - *

    Note! Text is extracted by {@link WebElement#getText()} method. - * - * @param element element which should be checked - * @param expected text which should be presented - * @param timeout waiting time in seconds - */ - public void waitTextContains(WebElement element, String expected, int timeout) { - String[] actual = new String[1]; - webDriverWaitFactory - .get( - timeout, - () -> format("\nactual text:\n'%s'\ndidn't contain:\n'%s'\n", actual[0], expected)) - .until( - (ExpectedCondition) - driver -> { - actual[0] = waitVisibilityAndGetText(element, timeout); - return actual[0].contains(expected); - }); - } - - /** - * Waits until specified {@code element} contains the specified {@code expectedText}. - * - *

    Note! Text is extracted by {@link WebElement#getText()} method. - * - * @param element element which should be checked - * @param expectedText text which should be presented - */ - public void waitTextContains(WebElement element, String expectedText) { - waitTextContains(element, expectedText, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until {@link WebElement} which defined by {@code elementLocator} - * contains the specified {@code expectedText}. - * - *

    Note! Text is extracted by {@link WebElement#getText()} method. - * - * @param elementLocator locator of the element which should be checked - * @param expectedText text which should be presented - * @param timeout waiting time in seconds - */ - public void waitTextContains(By elementLocator, String expectedText, int timeout) { - waitTextContains(waitVisibility(elementLocator, timeout), expectedText, timeout); - } - - /** - * Waits until {@link WebElement} which defined by {@code elementLocator} contains the specified - * {@code expectedText}. - * - *

    Note! Text is extracted by {@link WebElement#getText()} method. - * - * @param elementLocator locator of the element which should be checked - * @param expectedText text which should be presented - */ - public void waitTextContains(By elementLocator, String expectedText) { - waitTextContains(elementLocator, expectedText, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until specified {@code element} does not contain the specified - * {@code absentText}. - * - *

    Note! Text is extracted by {@link WebElement#getText()} method. - * - * @param webElement element which should be checked - * @param absentText text which should be absent - * @param timeout waiting time in seconds - */ - public void waitTextIsNotPresented(WebElement webElement, String absentText, int timeout) { - String[] actual = new String[1]; - webDriverWaitFactory - .get( - timeout, - () -> format("\nactual text:\n'%s'\ndid contain:\n'%s'\n", actual[0], absentText)) - .until( - (ExpectedCondition) - driver -> { - actual[0] = waitVisibilityAndGetText(webElement, timeout); - return !actual[0].contains(absentText); - }); - } - - /** - * Waits until {@link WebElement} which defined by {@code element} does not contain the specified - * {@code absentText}. - * - *

    Note! Text is extracted by {@link WebElement#getText()} method. - * - * @param element element which should be checked - * @param absentText text which should be absent - */ - public void waitTextIsNotPresented(WebElement element, String absentText) { - waitTextIsNotPresented(element, absentText, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} of visibility the {@link WebElement} with provided {@code - * elementLocator} and clicks once on it by {@link WebElement#click()}. - * - * @param elementLocator locator of element which should be clicked - * @param timeout waiting time in seconds - */ - public void waitAndClick(By elementLocator, int timeout) { - webDriverWaitFactory.get(timeout).until(visibilityOfElementLocated(elementLocator)).click(); - } - - /** - * Waits visibility of {@link WebElement} with provided {@code elementLocator} and clicks once on - * it by {@link WebElement#click()}. - * - * @param elementLocator locator of element which should be clicked - */ - public void waitAndClick(By elementLocator) { - waitAndClick(elementLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits visibility of provided {@code webElement} and clicks once on it by {@link - * WebElement#click()}. - * - * @param webElement element which should be clicked - * @param timeout waiting time in seconds - */ - public void waitAndClick(WebElement webElement, int timeout) { - webDriverWaitFactory.get(timeout).until(visibilityOf(webElement)).click(); - } - - /** - * Waits visibility of provided {@code webElement} and clicks once on it by {@link - * WebElement#click()}. - * - * @param webElement element which should be clicked - */ - public void waitAndClick(WebElement webElement) { - waitAndClick(webElement, DEFAULT_TIMEOUT); - } - - /** - * Moves cursor to {@link WebElement} with provided {@code elementLocator}, and clicks twice on it - * by {@link org.openqa.selenium.interactions.Action}. Gets rid of {@link - * org.openqa.selenium.StaleElementReferenceException} by using {@link Actions#doubleClick()}. - * - * @param elementLocator locator of element which should be clicked - */ - public void moveCursorToAndDoubleClick(By elementLocator) { - moveCursorTo(elementLocator); - actionsFactory.createAction(seleniumWebDriver).doubleClick().perform(); - } - - /** - * Moves cursor to provided {@code webElement}, and clicks twice on it by {@link - * org.openqa.selenium.interactions.Action}. Gets rid of {@link - * org.openqa.selenium.StaleElementReferenceException} by using {@link Actions#doubleClick()}. - * - * @param webElement element which should be clicked - */ - public void moveCursorToAndDoubleClick(WebElement webElement) { - moveCursorTo(webElement); - actionsFactory.createAction(seleniumWebDriver).doubleClick().perform(); - } - - /** Performs mouse's left button double click . */ - public void doubleClick() { - actionsFactory.createAction(seleniumWebDriver).doubleClick().perform(); - } - - /** - * Performs mouse's left button double click on element. - * - * @param elementLocator locator of element which should be double clicked - */ - public void doubleClick(By elementLocator) { - actionsFactory - .createAction(seleniumWebDriver) - .doubleClick(seleniumWebDriver.findElement(elementLocator)) - .build() - .perform(); - } - - /** - * Moves cursor to {@link WebElement} with provided {@code elementLocator} and clicks once on it - * by {@link org.openqa.selenium.interactions.Action}. - * - * @param elementLocator locator of element which should be clicked - */ - public void moveCursorToAndClick(By elementLocator) { - moveCursorTo(elementLocator); - actionsFactory.createAction(seleniumWebDriver).click().perform(); - } - - /** - * Moves cursor to provided {@code webElement}, and clicks once on it by {@link - * org.openqa.selenium.interactions.Action}. - * - * @param webElement element which should be clicked - */ - public void moveCursorToAndClick(WebElement webElement) { - moveCursorTo(webElement); - actionsFactory.createAction(seleniumWebDriver).click().perform(); - } - - /** - * Moves cursor to {@link WebElement} with provided {@code elementLocator} which attached to DOM. - * - *

    Note! It does not mean that element is visible. - * - * @param elementLocator element to which cursor should be moved - */ - public void moveCursorTo(By elementLocator) { - actionsFactory - .createAction(seleniumWebDriver) - .moveToElement(waitPresence(elementLocator)) - .perform(); - } - - /** - * Moves cursor to provided {@code webElement} which attached to DOM. - * - *

    Note! It does not mean that element is visible. - * - * @param webElement element to which cursor should be moved - */ - public void moveCursorTo(WebElement webElement) { - actionsFactory.createAction(seleniumWebDriver).moveToElement(webElement).perform(); - } - - /** - * Moves cursor to {@link WebElement} with provided {@code elementLocator} which attached to DOM - * and performs mouse's right button click. - * - *

    Note! It does not mean that element is visible. - * - * @param elementLocator locator of {@link WebElement} for which context menu will be opened. - */ - public void moveCursorToAndContextClick(By elementLocator) { - moveCursorTo(elementLocator); - actionsFactory.createAction(seleniumWebDriver).contextClick().perform(); - } - - /** - * Wait during {@code timeout} on visibility on element located at {@code elementLocator} and then - * context click on it. - * - * @param elementLocator locator of element which should be context clicked on - * @param timeout waiting time in seconds - */ - public void waitAndContextClick(By elementLocator, int timeout) { - waitVisibility(elementLocator, timeout); - - waitNoExceptions( - () -> performContextClick(elementLocator), timeout, StaleElementReferenceException.class); - } - - /** - * Waits visibility of element located at {@code elementLocator} and then context click on it. - * - * @param elementLocator locator of element which should be context clicked on - */ - public void waitAndContextClick(By elementLocator) { - waitAndContextClick(elementLocator, DEFAULT_TIMEOUT); - } - - private void performContextClick(By elementLocator) { - getAction().contextClick(seleniumWebDriver.findElement(elementLocator)).perform(); - } - - /** - * Moves cursor to specified {@code webElement} which attached to DOM and performs mouse's right - * button click. - * - *

    Note! It does not mean that element is visible. - * - * @param element {@link WebElement} for which context menu will be opened. - */ - public void moveCursorToAndContextClick(WebElement element) { - moveCursorTo(element); - actionsFactory.createAction(seleniumWebDriver).contextClick().perform(); - } - - /** - * Checks visibility state of {@link WebElement} with provided {@code elementLocator}. - * - * @param elementLocator locator of element which should be checked - * @return state of element visibility - */ - public boolean isVisible(By elementLocator) { - try { - return seleniumWebDriver.findElement(elementLocator).isDisplayed(); - } catch (NoSuchElementException | StaleElementReferenceException ex) { - return false; - } - } - - /** - * Checks visibility state of provided {@code webElement}. - * - * @param webElement element which should be checked - * @return state of element visibility - */ - public boolean isVisible(WebElement webElement) { - try { - return webElement.isDisplayed(); - } catch (NoSuchElementException | StaleElementReferenceException ex) { - return false; - } - } - - /** - * Determines whether or not this element {@code webElement} is enabled. - * - * @param webElement element which should be enabled - * @return true if given element is enabled - */ - public boolean waitVisibilityAndGetEnableState(WebElement webElement) { - return waitVisibility(webElement).isEnabled(); - } - - /** - * Waits during {@code timeout} until frame which defined by {@code frameLocator} is available and - * switches to it. - * - * @param frameLocator locator of the frame to which should be switched - * @param timeout waiting time in seconds - */ - public void waitAndSwitchToFrame(By frameLocator, int timeout) { - webDriverWaitFactory.get(timeout).until(frameToBeAvailableAndSwitchToIt(frameLocator)); - } - - /** - * Waits until frame which defined by {@code frameLocator} is available and switches to it. - * - * @param frameLocator locator of the frame to which should be switched - */ - public void waitAndSwitchToFrame(By frameLocator) { - waitAndSwitchToFrame(frameLocator, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until {@code frame} is available and switches to it. - * - * @param frame web element which defines frame - * @param timeout waiting time in seconds - */ - public void waitAndSwitchToFrame(WebElement frame, int timeout) { - webDriverWaitFactory.get(timeout).until(frameToBeAvailableAndSwitchToIt(frame)); - } - - /** - * Waits until {@code frame} is available and switches to it. - * - * @param frame web element which defines frame - */ - public void waitAndSwitchToFrame(WebElement frame) { - waitAndSwitchToFrame(frame, DEFAULT_TIMEOUT); - } - - /** - * Creates {@link Actions} by using {@link ActionsFactory}. - * - * @param seleniumWebDriver webDriver by which actions factory should be initialized - * @return created {@link Actions} - */ - public Actions getAction(SeleniumWebDriver seleniumWebDriver) { - return actionsFactory.createAction(seleniumWebDriver); - } - - /** - * Creates {@link Actions} by using {@link ActionsFactory}. - * - * @return created {@link Actions} - */ - public Actions getAction() { - return getAction(this.seleniumWebDriver); - } - - /** Switches to IDE frame and waits for Project Explorer is available. */ - public String switchToIdeFrameAndWaitAvailability() { - return switchToIdeFrameAndWaitAvailability(APPLICATION_START_TIMEOUT_SEC); - } - - /** - * Switches to IDE frame and waits during {@code timeout} for Project Explorer is available. - * - * @param timeout waiting time in seconds - */ - public String switchToIdeFrameAndWaitAvailability(int timeout) { - webDriverWaitFactory - .get(timeout) - .until( - new ExpectedCondition() { - private boolean switchedToFrame; - - @Override - public Boolean apply(WebDriver driver) { - if (!switchedToFrame) { - try { - waitAndSwitchToFrame(By.id("ide-application-iframe")); - switchedToFrame = true; - } catch (NoSuchElementException | TimeoutException e) { - driver.switchTo().parentFrame(); - return false; - } - } - - return isVisible(By.id("gwt-debug-projectTree")); - } - }); - - return seleniumWebDriver.getWindowHandle(); - } - - /** Waits while in a browser appears more than one window */ - public void waitOpenedSomeWin() { - webDriverWaitFactory - .get(WIDGET_TIMEOUT_SEC) - .until((ExpectedCondition) driver -> isTwoOrMoreWindowsOpened()); - } - - /** - * Checks appears more than one window. - * - * @return {@code true} if more than one window opened, {@code false} if one or zero window opened - */ - public boolean isTwoOrMoreWindowsOpened() { - return seleniumWebDriver.getWindowHandles().size() > 1; - } - - /** - * Waits during {@code timeout} until count of opened browser tabs are equals to {@code - * expectedCount}. - * - * @param expectedCount count of the opened browsers tabs - * @param timeout waiting time in seconds - */ - public void waitWindowsCount(int expectedCount, int timeout) { - webDriverWaitFactory - .get(timeout) - .until( - (ExpectedCondition) - driver -> seleniumWebDriver.getWindowHandles().size() == expectedCount); - } - - /** - * Waits until count of opened browser tabs are equals to {@code expectedCount}. - * - * @param expectedCount count of the opened browsers tabs - */ - public void waitWindowsCount(int expectedCount) { - waitWindowsCount(expectedCount, WIDGET_TIMEOUT_SEC); - } - - /** - * Switches to next browser window (this means that if opened 2 windows, and we are in the window - * 1, we will be switched into the window 2) - * - * @param windowHandlerToSwitchFrom - */ - public void switchToNextWindow(String windowHandlerToSwitchFrom) { - waitOpenedSomeWin(); - for (String handle : seleniumWebDriver.getWindowHandles()) { - if (!windowHandlerToSwitchFrom.equals(handle)) { - seleniumWebDriver.switchTo().window(handle); - break; - } - } - } - - /** - * Waits during {@code timeout} until attribute with specified {@code attributeName} has {@code - * expectedValue}. - * - * @param elementLocator element which contains attribute - * @param attributeName name of the attribute - * @param expectedValue expected attribute value - * @param timeout waiting time - */ - public void waitAttributeEqualsTo( - By elementLocator, String attributeName, String expectedValue, int timeout) { - webDriverWaitFactory - .get(timeout) - .until( - (ExpectedCondition) - driver -> - waitVisibilityAndGetAttribute(elementLocator, attributeName, timeout) - .equals(expectedValue)); - } - - /** - * Waits during {@code timeout} until attribute with specified {@code attributeName} has {@code - * expected} value. - * - * @param element element which contains attribute - * @param attributeName name of the attribute - * @param expectedValue expected attribute value - * @param timeout waiting time in seconds - */ - public void waitAttributeEqualsTo( - WebElement element, String attributeName, String expectedValue, int timeout) { - String[] actualValue = new String[1]; - webDriverWaitFactory - .get( - timeout, - () -> - format( - "\nexpected value of attribute '%s' was:\n'%s'\nbut actual was:\n'%s'\n", - attributeName, expectedValue, actualValue[0])) - .until( - (ExpectedCondition) - driver -> { - actualValue[0] = waitVisibilityAndGetAttribute(element, attributeName, timeout); - return actualValue[0].contains(expectedValue); - }); - } - - /** - * Waits until attribute with specified {@code attributeName} has {@code expectedValue}. - * - * @param elementLocator element which contains attribute - * @param attributeName name of the attribute - * @param expectedValue expected attribute value - */ - public void waitAttributeEqualsTo(By elementLocator, String attributeName, String expectedValue) { - waitAttributeEqualsTo(elementLocator, attributeName, expectedValue, DEFAULT_TIMEOUT); - } - - /** - * Waits until attribute with specified {@code attributeName} has {@code expectedValue}. - * - * @param element element which contains attribute - * @param attributeName name of the attribute - * @param expectedValue expected attribute value - */ - public void waitAttributeEqualsTo( - WebElement element, String attributeName, String expectedValue) { - waitAttributeEqualsTo(element, attributeName, expectedValue, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until attribute with specified {@code attributeName} contains - * {@code expectedValue}. - * - * @param locator element which contains attribute - * @param attributeName name of the attribute - * @param expectedValue expected attribute value - * @param timeout waiting time in seconds - */ - public void waitAttributeContainsValue( - By locator, String attributeName, String expectedValue, int timeout) { - String[] actualValue = new String[1]; - webDriverWaitFactory - .get( - timeout, - () -> - format( - "\nactual attribute '%s' value:\n'%s'\ndidn't contain:\n'%s'\n", - attributeName, actualValue[0], expectedValue)) - .until( - (ExpectedCondition) - driver -> { - actualValue[0] = waitVisibilityAndGetAttribute(locator, attributeName, timeout); - return actualValue[0].contains(expectedValue); - }); - } - - /** - * ~ Waits until attribute with specified {@code attributeName} contains {@code expectedValue}. - * - * @param elementLocator element which contains attribute - * @param attributeName name of the attribute - * @param expectedValue expected attribute value - */ - public void waitAttributeContainsValue( - By elementLocator, String attributeName, String expectedValue) { - waitAttributeContainsValue(elementLocator, attributeName, expectedValue, DEFAULT_TIMEOUT); - } - - /** - * Waits until given {@code webElement} is selected. - * - *

    Note! Uses only for checkboxes and radio buttons. - * - * @param webElement element which should be selected - */ - public void waitElementIsSelected(WebElement webElement) { - waitElementIsSelected(webElement, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until given {@code webElement} is selected. - * - *

    Note! Uses only for checkboxes and radio buttons. - * - * @param webElement element which should be selected - * @param timeout waiting time in seconds - */ - public void waitElementIsSelected(WebElement webElement, int timeout) { - webDriverWaitFactory.get(timeout).until(elementSelectionStateToBe(webElement, true)); - } - - /** - * Waits until given {@code webElement} is not selected. - * - *

    Note! Uses only for checkboxes and radio buttons. - * - * @param webElement element which should be not selected - */ - public void waitElementIsNotSelected(WebElement webElement) { - waitElementIsNotSelected(webElement, DEFAULT_TIMEOUT); - } - - /** - * Waits during {@code timeout} until given {@code webElement} is not selected. - * - *

    Note! Uses only for checkboxes and radio buttons. - * - * @param webElement element which should be not selected - * @param timeout waiting time in seconds - */ - public void waitElementIsNotSelected(WebElement webElement, int timeout) { - webDriverWaitFactory.get(timeout).until(elementSelectionStateToBe(webElement, false)); - } - - /** - * Sets given {@code isCheckedWebElement} to specified state and waits its state - * - *

    Note! Uses only for checkboxes and radio buttons. - * - * @param isCheckedWebElement element which should be selected - * @param setWebElement element which should be clicked to change the state - * @param state state of given element (true if the given element should be selected) - */ - public void waitAndSetCheckbox( - WebElement isCheckedWebElement, WebElement setWebElement, boolean state) { - if (state) { - if (!isCheckedWebElement.isSelected()) { - waitAndClick(setWebElement); - waitElementIsSelected(isCheckedWebElement); - } - } else { - if (isCheckedWebElement.isSelected()) { - waitAndClick(setWebElement); - waitElementIsNotSelected(isCheckedWebElement); - } - } - } - - /** - * Performs clicking and holding an {@code element} during specified {@code timeout}. - * - * @param element target element - * @param holdingTimeout time for element holding - */ - public void clickAndHoldElementDuringTimeout(By element, int holdingTimeout) { - clickAndHoldElementDuringTimeout(waitVisibility(element), holdingTimeout); - } - - /** - * Performs clicking and holding an {@code element} during specified {@code timeout}. - * - * @param element target element - * @param holdingTimeout time for element holding - */ - public void clickAndHoldElementDuringTimeout(WebElement element, int holdingTimeout) { - Actions action = getAction(); - action.clickAndHold(waitVisibility(element)).perform(); - WaitUtils.sleepQuietly(holdingTimeout); - action.release(waitVisibility(element)).perform(); - } - - /** - * @see SeleniumWebDriverHelper#selectResourceToUpload(org.openqa.selenium.WebElement, - * java.nio.file.Path) - */ - public void selectResourceToUpload(By elementLocator, Path localResource) throws IOException { - selectResourceToUpload(seleniumWebDriver.findElement(elementLocator), localResource); - } - - /** - * Links resource to upload to input element of file type. - * - * @param webElement web element which is being used to upload the file - * @param localResource path to the local file or directory - * @return name of file which is linked to upload, or the name of zip file which contains - * uploading directory - * @throws IOException if there is a problem with preparing resource to upload - */ - public String selectResourceToUpload(WebElement webElement, Path localResource) - throws IOException { - Path readyToUploadFile = uploadUtil.prepareToUpload(seleniumWebDriver, localResource); - webElement.sendKeys(readyToUploadFile.toString()); - - return readyToUploadFile.getFileName().toString(); - } - - /** - * Waits during {@code timeout} until specified {@code expression} returns "true". - * - * @param expression the condition which should be waits until it has a "true" state - * @param timeout waiting time in seconds - */ - public void waitSuccessCondition(ExpectedCondition expression, int timeout) { - webDriverWaitFactory - .get(timeout) - .until((ExpectedCondition) driver -> expression.apply(this.seleniumWebDriver)); - } - - /** - * Waits until specified {@code expression} returns "true". - * - * @param expression the condition which should be waits until it has a "true" state - */ - public void waitSuccessCondition(ExpectedCondition expression) { - waitSuccessCondition(expression, DEFAULT_TIMEOUT); - } - - /** Hides context menu. */ - public void hideContextMenu() { - actionsFactory.createAction(seleniumWebDriver).moveByOffset(-1, -1).click().perform(); - } - - public void closeCurrentWindowAndSwitchToAnother(String windowToSwitch) { - seleniumWebDriver.close(); - seleniumWebDriver.switchTo().window(windowToSwitch); - } - - public void pressArrowDown() { - getAction().sendKeys(ARROW_DOWN.toString()).perform(); - } - - public void pressArrowUp() { - getAction().sendKeys(ARROW_UP.toString()).perform(); - } - - public void pressArrowLeft() { - getAction().sendKeys(ARROW_LEFT.toString()).perform(); - } - - public void pressArrowRight() { - getAction().sendKeys(ARROW_RIGHT.toString()).perform(); - } - - public void pressEnter() { - getAction().sendKeys(ENTER.toString()).perform(); - } - - public void pressDelete() { - getAction().sendKeys(DELETE.toString()).perform(); - } - - public void pressBackspace() { - getAction().sendKeys(BACK_SPACE.toString()).perform(); - } - - public void pressCtrlF12() { - actionsFactory - .createAction(seleniumWebDriver) - .keyDown(CONTROL) - .sendKeys(F12) - .keyUp(CONTROL) - .perform(); - } - - /** - * Waits until {@code action} stop throwing exception of {@code ignoredExceptionType} and during - * {@code DEFAULT_TIMEOUT}. - * - * @param action action which should stop throwing of certain exception during timeout - * @param ignoredExceptionTypes exceptions which should be ignored when action is performed - */ - public void waitNoExceptions( - Runnable action, Class... ignoredExceptionTypes) { - waitNoExceptions(action, DEFAULT_TIMEOUT, ignoredExceptionTypes); - } - - /** - * Waits until {@code action} stop throwing exception of {@code ignoredExceptionType} during - * {@code timeoutInSec}. - * - * @param action action which should stop throwing of certain exception during timeout - * @param timeoutInSec waiting time in seconds - * @param ignoredExceptionTypes exceptions which should be ignored when action is being performed - */ - public void waitNoExceptions( - Runnable action, - int timeoutInSec, - Class... ignoredExceptionTypes) { - webDriverWaitFactory - .get(timeoutInSec, asList(ignoredExceptionTypes)) - .until( - (ExpectedCondition) - driver -> { - action.run(); - return true; - }); - } - /** - * Performs and verifies action. - * - * @param perform perform action - * @param verify verification action - * @param rollback rollback action - */ - public void performAndVerify( - UnaryOperator perform, UnaryOperator verify, UnaryOperator rollback) { - for (; ; ) { - perform.apply(null); - - try { - verify.apply(null); - break; - } catch (TimeoutException e) { - rollback.apply(null); - } - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadIntoGridUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadIntoGridUtil.java deleted file mode 100644 index 5bcea93eb2..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadIntoGridUtil.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import javax.inject.Named; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.utils.DockerUtil; - -/** - * This is set of methods to work with files which are uploaded by WebDriver inside selenium node. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class UploadIntoGridUtil extends AbstractUploadUtil { - private final Path uploadDir; - private final DockerUtil dockerUtil; - - @Inject - public UploadIntoGridUtil(@Named("tests.tmp_dir") String uploadDir, DockerUtil dockerUtil) { - this.uploadDir = Paths.get(uploadDir); - this.dockerUtil = dockerUtil; - } - - @Override - Path prepareFileToUpload(SeleniumWebDriver seleniumWebDriver, Path localPath) throws IOException { - dockerUtil.copyIntoContainer(seleniumWebDriver.getGridNodeContainerId(), localPath, uploadDir); - - return uploadDir.resolve(localPath.getFileName()); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadLocallyUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadLocallyUtil.java deleted file mode 100644 index 5b28bb4399..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadLocallyUtil.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import com.google.inject.Singleton; -import java.nio.file.Path; -import org.eclipse.che.selenium.core.SeleniumWebDriver; - -/** - * This is set of methods to work with file which is uploaded by WebDriver locally. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class UploadLocallyUtil extends AbstractUploadUtil { - - @Override - public Path prepareFileToUpload(SeleniumWebDriver seleniumWebDriver, Path localPath) { - return localPath; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadUtil.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadUtil.java deleted file mode 100644 index 2067edb389..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/UploadUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import java.io.IOException; -import java.nio.file.Path; -import org.eclipse.che.selenium.core.SeleniumWebDriver; - -/** - * This is set of methods to work with files which are uploaded by WebDriver. - * - * @author Dmytro Nochevnov - */ -public interface UploadUtil { - - /** - * Prepare local resource to be uploaded by WebDriver. If it's directory, it is zipped. - * - * @param seleniumWebDriver - * @param localPath path to local file or directory which should be uploaded by WebDriver - * @return path to file which WebDriver can upload - */ - Path prepareToUpload(SeleniumWebDriver seleniumWebDriver, Path localPath) throws IOException; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/WebDriverWaitFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/WebDriverWaitFactory.java deleted file mode 100644 index 952fad8a11..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/WebDriverWaitFactory.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver; - -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; - -import com.google.common.base.Supplier; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.Collection; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.support.ui.FluentWait; -import org.openqa.selenium.support.ui.WebDriverWait; - -@Singleton -public class WebDriverWaitFactory { - private SeleniumWebDriver seleniumWebDriver; - - @Inject - public WebDriverWaitFactory(SeleniumWebDriver seleniumWebDriver) { - this.seleniumWebDriver = seleniumWebDriver; - } - - public WebDriverWait get() { - return get(LOAD_PAGE_TIMEOUT_SEC); - } - - public WebDriverWait get(int timeoutInSec) { - return new WebDriverWait(seleniumWebDriver, timeoutInSec); - } - - /** - * Creates an instance of the {@link FluentWait} with specified {@code timeoutInSec} and error - * message supplier. - * - * @param timeoutInSec waiting time in seconds. - * @param messageSupplier error message supplier - * @return - */ - public FluentWait get(int timeoutInSec, Supplier messageSupplier) { - return new WebDriverWait(seleniumWebDriver, timeoutInSec).withMessage(messageSupplier); - } - - /** - * Creates an instance of the {@link FluentWait} with specified {@code timeoutInSec} and ignoring - * exception of {@code ignoringExceptionType}. - * - * @param timeoutInSec waiting time in seconds. - * @param ignoredExceptionTypes exceptions which are ignoring during timeout. - * @return - */ - public FluentWait get( - int timeoutInSec, Collection> ignoredExceptionTypes) { - return new WebDriverWait(seleniumWebDriver, timeoutInSec).ignoreAll(ignoredExceptionTypes); - } - - /** - * Creates an instance of the {@link WebDriverWait} with specified {@code timeoutInSec} and - * frequency of attempts. - * - * @param timeoutInSec waiting time in seconds. - * @param delayBetweenAttemptsInSec delay between attempts. - * @return instance of the {@link WebDriverWait} initialized by specified values. - */ - public WebDriverWait get(int timeoutInSec, int delayBetweenAttemptsInSec) { - long delayBetweenAttempts = SECONDS.toMillis(delayBetweenAttemptsInSec); - return new WebDriverWait(seleniumWebDriver, timeoutInSec, delayBetweenAttempts); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Log.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Log.java deleted file mode 100644 index 39807b3363..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Log.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver.log; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.webdriver.log.WebDriverLogsReader.LOG_TIME_FORMAT; - -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * This class deals with web driver log entry. - * - * @author Dmytro Nochevnov - */ -public class Log { - private Message message; - private long timestamp; - - public Message getMessage() { - return message; - } - - public void setMessage(Message message) { - this.message = message; - } - - boolean isNetworkLog() { - return isNetworkRequest() - || isNetworkResponse() - || isWebsocketCreated() - || isWebsocketRequest() - || isWebsocketResponse(); - } - - private boolean isNetworkRequest() { - return "Network.requestWillBeSent".equals(getMessage().getMethod()); - } - - private boolean isNetworkResponse() { - return "Network.responseReceived".equals(getMessage().getMethod()); - } - - private boolean isWebsocketCreated() { - return "Network.webSocketCreated".equals(getMessage().getMethod()); - } - - private boolean isWebsocketRequest() { - return "Network.webSocketFrameSent".equals(getMessage().getMethod()); - } - - private boolean isWebsocketResponse() { - return "Network.webSocketFrameReceived".equals(getMessage().getMethod()); - } - - public String getUrl() { - if (hasRequest()) { - return getMessage().getParams().getRequest().getUrl(); - - } else if (hasResponse()) { - return getMessage().getParams().getResponse().getUrl(); - - } else if (hasParams() && getMessage().getParams().getUrl() != null) { - return getMessage().getParams().getUrl(); - } - - return ""; - } - - public String getRequestId() { - if (hasParams()) { - return getMessage().getParams().getRequestId(); - } - - return ""; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - private String getRequestMethod() { - if (hasRequest()) { - return getMessage().getParams().getRequest().getMethod(); - } - - return ""; - } - - private String getResponseStatus() { - if (hasResponse()) { - return getMessage().getParams().getResponse().getStatus(); - } - - return ""; - } - - private String getPayloadData() { - if (hasResponse()) { - return getMessage().getParams().getResponse().getPayloadData(); - } - - return ""; - } - - private boolean hasRequest() { - return hasParams() && getMessage().getParams().getRequest() != null; - } - - private boolean hasResponse() { - return hasParams() && getMessage().getParams().getResponse() != null; - } - - private boolean hasParams() { - return getMessage() != null && getMessage().getParams() != null; - } - - private String formatTime(long timestamp) { - return new SimpleDateFormat(LOG_TIME_FORMAT).format(new Date(timestamp)); - } - - @Override - public String toString() { - String prefix = format("%s (id: %s)", formatTime(getTimestamp()), getRequestId()); - - if (isNetworkRequest()) { - return format("%s [REQUEST] %s %s\n", prefix, getRequestMethod(), getUrl()); - - } else if (isNetworkResponse()) { - return format("%s [RESPONSE] %s %s\n", prefix, getResponseStatus(), getUrl()); - - } else if (isWebsocketCreated()) { - return format("%s [WEBSOCKET_CREATED] %s\n", prefix, getUrl()); - - } else if (isWebsocketRequest()) { - return format("%s [WEBSOCKET_REQUEST] %s\n", prefix, getPayloadData()); - - } else if (isWebsocketResponse()) { - return format("%s [WEBSOCKET_RESPONSE] %s\n", prefix, getPayloadData()); - } - - return super.toString(); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Message.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Message.java deleted file mode 100644 index 8dbe7d2a05..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Message.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver.log; - -/** - * This is POJO to extract message from web driver network log entry - * - * @author Dmytro Nochevnov - */ -public interface Message { - String getMethod(); - - void setMethod(String method); - - Params getParams(); - - void setParams(Params params); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Params.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Params.java deleted file mode 100644 index 437082debf..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Params.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver.log; - -/** - * This is POJO to extract 'params' value from web driver network log entry - * - * @author Dmytro Nochevnov - */ -public interface Params { - String getRequestId(); - - void setRequestId(String requestId); - - String getUrl(); - - void setUrl(String url); - - Request getRequest(); - - void setRequest(Request request); - - Response getResponse(); - - void setResponse(Response request); - - String getTimestamp(); - - void setTimestamp(String timestamp); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Request.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Request.java deleted file mode 100644 index 5df5878888..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Request.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver.log; - -/** - * This is POJO to extract `request` value from web driver network log entry. - * - * @author Dmytro Nochevnov - */ -public interface Request { - String getUrl(); - - void setUrl(String url); - - String getMethod(); - - void setMethod(String method); - - String getWallTime(); - - void setWallTime(String wallTime); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Response.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Response.java deleted file mode 100644 index 2a53b53169..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/Response.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver.log; - -/** - * This is POJO to extract 'response' value from web driver network log entry. - * - * @author Dmytro Nochevnov - */ -public interface Response { - String getUrl(); - - void setUrl(String url); - - String getStatus(); - - void setStatus(String status); - - String getPayloadData(); - - void setPayloadData(String payloadData); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/WebDriverLogsReader.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/WebDriverLogsReader.java deleted file mode 100644 index 92fce9cec7..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/WebDriverLogsReader.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver.log; - -import static java.lang.String.format; -import static org.openqa.selenium.logging.LogType.BROWSER; -import static org.openqa.selenium.logging.LogType.PERFORMANCE; - -import com.google.inject.Inject; -import com.google.inject.assistedinject.Assisted; -import com.google.inject.assistedinject.AssistedInject; -import com.google.inject.name.Named; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.eclipse.che.commons.json.JsonHelper; -import org.eclipse.che.commons.json.JsonParseException; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.openqa.selenium.logging.LogEntries; -import org.openqa.selenium.logging.LogEntry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class WebDriverLogsReader { - public static final String LOG_TIME_FORMAT = "yyyy-MM-dd hh:mm:ss,SSS"; - private static final Logger LOG = LoggerFactory.getLogger(WebDriverLogsReader.class); - - private final SeleniumWebDriver seleniumWebDriver; - private final String cheHost; - - @Inject - public WebDriverLogsReader( - @Named("che.host") String cheHost, SeleniumWebDriver seleniumWebDriver) { - this.seleniumWebDriver = seleniumWebDriver; - this.cheHost = cheHost; - } - - @AssistedInject - public WebDriverLogsReader( - @Assisted SeleniumWebDriver seleniumWebDriver, @Named("che.host") String cheHost) { - this.seleniumWebDriver = seleniumWebDriver; - this.cheHost = cheHost; - } - - /** - * Reads logs of browser from web driver. - * - * @return log messages from browser console - */ - private LogEntries readBrowserLogs() { - return seleniumWebDriver.manage().logs().get(BROWSER); - } - - /** - * Reads performance logs from web driver. - * - * @return all types of performance logs - */ - private LogEntries readPerformanceLogs() { - return seleniumWebDriver.manage().logs().get(PERFORMANCE); - } - - /** - * Gets all logs of web driver. - * - * @return logs from browser console and Eclipse Che network logs - */ - public String getAllLogs() throws JsonParseException { - return prepareBrowserLogs() + "\n" + prepareCheNetworkLogs(); - } - - private String prepareBrowserLogs() { - StringBuilder browserLogsOutput = - new StringBuilder("Browser console logs:\n").append("---------------------\n"); - - readBrowserLogs() - .forEach( - logEntry -> - browserLogsOutput.append( - format( - "%s %s %s\n\n", - formatTime(logEntry.getTimestamp()), - logEntry.getLevel(), - logEntry.getMessage()))); - - return browserLogsOutput.toString(); - } - - /** filter data and get requests/responses that have been sent on CHE URL */ - private String prepareCheNetworkLogs() throws JsonParseException { - StringBuilder networkLogsOutput = - new StringBuilder("Eclipse Che network logs: \n").append("-------------------------\n"); - Map> networkLogs = new HashMap<>(); - for (LogEntry logEntry : readPerformanceLogs()) { - Log log = JsonHelper.fromJson(logEntry.getMessage(), Log.class, null); - if (log.isNetworkLog()) { - log.setTimestamp(logEntry.getTimestamp()); - if (networkLogs.containsKey(log.getRequestId())) { - networkLogs.get(log.getRequestId()).add(log); - } else { - ArrayList logs = new ArrayList<>(); - logs.add(log); - networkLogs.put(log.getRequestId(), logs); - } - - if (isLogFromCheTraffic(log.getRequestId(), networkLogs)) { - networkLogsOutput.append(log.toString()); - } else { - networkLogs.remove(log.getRequestId()); - } - } - } - - return networkLogsOutput.toString(); - } - - /** - * Go through the {@code networkLogs} related to the certain {@code requestId} and return {@code - * true} if at least one of them has url from Che traffic. - */ - private boolean isLogFromCheTraffic(String requestId, Map> networkLogs) { - return networkLogs - .get(requestId) - .stream() - .filter(log -> isUrlFromCheTraffic(log.getUrl())) - .count() - > 0; - } - - private boolean isUrlFromCheTraffic(String url) { - return url != null - && (url.matches(format("https?://%s[:\\d]*/api/.*", cheHost)) || url.matches("wss?://.*")); - } - - private String formatTime(long timestamp) { - return new SimpleDateFormat(LOG_TIME_FORMAT).format(new Date(timestamp)); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/WebDriverLogsReaderFactory.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/WebDriverLogsReaderFactory.java deleted file mode 100644 index 712502f56e..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/webdriver/log/WebDriverLogsReaderFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.webdriver.log; - -import org.eclipse.che.selenium.core.SeleniumWebDriver; - -/** @author Dmytro Nochevnov */ -public interface WebDriverLogsReaderFactory { - - WebDriverLogsReader create(SeleniumWebDriver webdriver); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/AbstractTestWorkspaceInjector.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/AbstractTestWorkspaceInjector.java deleted file mode 100644 index 7d04638b5d..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/AbstractTestWorkspaceInjector.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import static com.google.common.base.Strings.isNullOrEmpty; -import static java.lang.String.format; - -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.MembersInjector; -import com.google.inject.name.Names; -import java.lang.reflect.Field; -import org.eclipse.che.selenium.core.user.DefaultTestUser; - -/** - * Injector for custom annotation {@link InjectTestWorkspace}. - * - * @author Anatolii Bazko - */ -public abstract class AbstractTestWorkspaceInjector implements MembersInjector { - protected final Field field; - protected final InjectTestWorkspace injectTestWorkspace; - protected final Injector injector; - - public AbstractTestWorkspaceInjector( - Field field, InjectTestWorkspace injectTestWorkspace, Injector injector) { - this.field = field; - this.injectTestWorkspace = injectTestWorkspace; - this.injector = injector; - } - - @Override - public void injectMembers(T instance) throws RuntimeException { - try { - TestWorkspace testWorkspace = - getTestWorkspaceProvider() - .createWorkspace( - getUser(instance), - getMemory(), - injectTestWorkspace.template(), - injectTestWorkspace.startAfterCreation()); - testWorkspace.await(); - field.setAccessible(true); - field.set(instance, testWorkspace); - } catch (Exception e) { - throw new RuntimeException("Could not inject workspace. ", e); - } - } - - protected abstract TestWorkspaceProvider getTestWorkspaceProvider(); - - protected int getMemory() { - int workspaceDefaultMemoryGb = - injector.getInstance(Key.get(int.class, Names.named("workspace.default_memory_gb"))); - return injectTestWorkspace.memoryGb() <= 0 - ? workspaceDefaultMemoryGb - : injectTestWorkspace.memoryGb(); - } - - protected DefaultTestUser getUser(T instance) { - return isNullOrEmpty(injectTestWorkspace.user()) - ? injector.getInstance(DefaultTestUser.class) - : findInjectedUser(instance, injectTestWorkspace.user()); - } - - protected DefaultTestUser findInjectedUser(T instance, String userEmail) { - for (Field field : instance.getClass().getDeclaredFields()) { - if (field.getType() == DefaultTestUser.class) { - field.setAccessible(true); - - DefaultTestUser testUser; - try { - testUser = (DefaultTestUser) field.get(instance); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } - - if (testUser != null && testUser.getEmail().equals(userEmail)) { - return testUser; - } - } - } - - throw new IllegalArgumentException( - format( - "User %s not found or isn't instantiated in %s", - userEmail, instance.getClass().getName())); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspace.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspace.java deleted file mode 100644 index 26cf16bba1..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspace.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import static java.lang.String.format; -import static java.nio.file.Paths.get; -import static org.eclipse.che.selenium.core.workspace.MemoryMeasure.GB; - -import java.nio.file.Path; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicReference; -import javax.annotation.PreDestroy; -import org.eclipse.che.api.core.model.workspace.Workspace; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.commons.annotation.Nullable; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClient; -import org.eclipse.che.selenium.core.user.TestUser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** @author Anatolii Bazko */ -public class CheTestWorkspace implements TestWorkspace { - private static final Logger LOG = LoggerFactory.getLogger(CheTestWorkspace.class); - - private final String name; - private final TestUser owner; - private final AtomicReference id = new AtomicReference<>(); - private final TestWorkspaceServiceClient testWorkspaceServiceClient; - private CompletableFuture future; - - public CheTestWorkspace( - String name, - TestUser owner, - int memoryInGB, - boolean startAfterCreation, - WorkspaceConfigDto template, - TestWorkspaceServiceClient testWorkspaceServiceClient, - TestWorkspaceLogsReader testWorkspaceLogsReader, - String workspaceLogsDir) { - if (template == null) { - throw new IllegalStateException("Workspace template cannot be null"); - } - - this.name = name; - this.owner = owner; - this.testWorkspaceServiceClient = testWorkspaceServiceClient; - - this.future = - CompletableFuture.runAsync( - () -> { - Workspace ws; - try { - ws = testWorkspaceServiceClient.createWorkspace(name, memoryInGB, GB, template); - } catch (Exception e) { - String errorMessage = format("Workspace name='%s' creation failed.", name); - LOG.error(errorMessage, e); - - try { - testWorkspaceServiceClient.delete(name, owner.getName()); - } catch (Exception e1) { - LOG.warn("Failed to remove workspace name='{}' which creation is failed.", name); - } - - throw new IllegalStateException(errorMessage, e); - } - - long start = System.currentTimeMillis(); - String workspaceId = ws.getId(); - LOG.info( - format("Workspace with name='%s' id='%s' is starting...", name, workspaceId)); - if (startAfterCreation) { - try { - testWorkspaceServiceClient.start( - id.updateAndGet((s) -> workspaceId), name, owner); - } catch (Exception e) { - String errorMessage = - format("Workspace with name='%s' id='%s' start failed.", name, workspaceId); - LOG.error(errorMessage); - - // try to store the logs of workspace which didn't start - Path pathToWorkspaceLogs = - get(workspaceLogsDir, "injecting_workspaces_which_did_not_start"); - testWorkspaceLogsReader.store(workspaceId, pathToWorkspaceLogs, true); - - try { - testWorkspaceServiceClient.delete(name, owner.getName()); - } catch (Exception e1) { - LOG.warn( - "Failed to remove workspace with name='{}' id='{}' which start is failed.", - name, - workspaceId); - } - - throw new IllegalStateException(errorMessage, e); - } - - LOG.info( - "Workspace name='{}' id='{}' started in {} sec.", - name, - ws.getId(), - (System.currentTimeMillis() - start) / 1000); - } - }); - } - - public CheTestWorkspace( - String name, TestUser owner, TestWorkspaceServiceClient testWorkspaceServiceClient) { - this.testWorkspaceServiceClient = testWorkspaceServiceClient; - this.name = name; - this.owner = owner; - } - - @Override - public void await() throws InterruptedException, ExecutionException { - if (future == null) { - return; - } - - future.get(); - } - - @Override - public String getName() { - return name; - } - - @Override - @Nullable - public String getId() throws ExecutionException, InterruptedException { - if (future == null) { - try { - Workspace wsConfig = testWorkspaceServiceClient.getByName(name, owner.getName()); - id.set(wsConfig.getId()); - return id.get(); - } catch (Exception e) { - String errorMessage = - format("Failed to obtain id of workspace name='%s' owner='%s'", name, owner.getName()); - - LOG.warn(errorMessage, e); - - return null; - } - } - - return future.thenApply(aVoid -> id.get()).get(); - } - - @Override - public TestUser getOwner() { - return owner; - } - - @PreDestroy - @Override - @SuppressWarnings("FutureReturnValueIgnored") - public void delete() { - try { - testWorkspaceServiceClient.delete(name, owner.getName()); - } catch (Exception e) { - throw new RuntimeException(format("Failed to remove workspace '%s'", this), e); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspaceProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspaceProvider.java deleted file mode 100644 index 2d43e23fe1..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspaceProvider.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import javax.inject.Named; -import org.eclipse.che.api.core.model.workspace.WorkspaceStatus; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceConfigDto; -import org.eclipse.che.commons.lang.NameGenerator; -import org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClient; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClientFactory; -import org.eclipse.che.selenium.core.user.DefaultTestUser; -import org.eclipse.che.selenium.core.user.TestUser; -import org.eclipse.che.selenium.core.utils.WorkspaceDtoDeserializer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -public class CheTestWorkspaceProvider implements TestWorkspaceProvider { - private static final Logger LOG = LoggerFactory.getLogger(CheTestWorkspaceProvider.class); - private static final String AUTO = "auto"; - - private final DefaultTestUser defaultUser; - private final int defaultMemoryGb; - private final int poolSize; - private final TestWorkspaceServiceClient testWorkspaceServiceClient; - private final TestWorkspaceServiceClientFactory testWorkspaceServiceClientFactory; - private final TestWorkspaceLogsReader testWorkspaceLogsReader; - private final String workspaceLogsDir; - private final WorkspaceDtoDeserializer workspaceDtoDeserializer; - - private ScheduledExecutorService executor; - private ArrayBlockingQueue testWorkspaceQueue; - - @Inject - public CheTestWorkspaceProvider( - @Named("che.workspace_pool_size") String poolSize, - @Named("che.threads") int threads, - @Named("workspace.default_memory_gb") int defaultMemoryGb, - @Named("tests.workspacelogs_dir") String workspaceLogsDir, - DefaultTestUser defaultUser, - WorkspaceDtoDeserializer workspaceDtoDeserializer, - TestWorkspaceServiceClient testWorkspaceServiceClient, - TestWorkspaceServiceClientFactory testWorkspaceServiceClientFactory, - TestWorkspaceLogsReader testWorkspaceLogsReader) { - this.defaultMemoryGb = defaultMemoryGb; - this.defaultUser = defaultUser; - this.workspaceDtoDeserializer = workspaceDtoDeserializer; - this.testWorkspaceServiceClient = testWorkspaceServiceClient; - this.testWorkspaceServiceClientFactory = testWorkspaceServiceClientFactory; - this.testWorkspaceLogsReader = testWorkspaceLogsReader; - this.workspaceLogsDir = workspaceLogsDir; - - if (poolSize.equals(AUTO)) { - this.poolSize = (threads - 1) / 2 + 1; - } else { - this.poolSize = Integer.parseInt(poolSize); - } - - if (this.poolSize > 0) { - initializePool(); - } - } - - @Override - public TestWorkspace getWorkspace(String workspaceName, TestUser owner) { - return new CheTestWorkspace( - workspaceName, owner, testWorkspaceServiceClientFactory.create(owner)); - } - - @Override - public TestWorkspace createWorkspace( - TestUser owner, int memoryGB, String templateFileName, boolean startAfterCreation) - throws Exception { - if (poolSize > 0 && hasDefaultValues(owner, memoryGB, templateFileName, startAfterCreation)) { - return doGetWorkspaceFromPool(); - } - - return createWorkspace( - generateName(), - owner, - memoryGB, - startAfterCreation, - workspaceDtoDeserializer.deserializeWorkspaceTemplate(templateFileName)); - } - - public TestWorkspace createWorkspace( - String name, - TestUser owner, - int memoryGB, - boolean startAfterCreation, - WorkspaceConfigDto config) { - return new CheTestWorkspace( - name, - owner, - memoryGB, - startAfterCreation, - config, - testWorkspaceServiceClientFactory.create(owner), - testWorkspaceLogsReader, - workspaceLogsDir); - } - - @Override - public void shutdown() { - if (executor == null) { - return; - } - - boolean isInterrupted = false; - if (!executor.isShutdown()) { - executor.shutdown(); - try { - LOG.info("Shutdown workspace threads pool, wait 30s to stop normally"); - if (!executor.awaitTermination(30, TimeUnit.SECONDS)) { - executor.shutdownNow(); - LOG.info("Interrupt workspace threads pool, wait 60s to stop"); - if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { - LOG.error("Couldn't shutdown workspace threads pool"); - } - } - } catch (InterruptedException x) { - isInterrupted = true; - if (!executor.isShutdown()) { - LOG.warn("Unable to terminate executor service"); - } - } - LOG.info("Workspace threads pool is terminated"); - } - - LOG.info("Destroy remained workspaces: {}.", extractWorkspaceInfo()); - testWorkspaceQueue.parallelStream().forEach(TestWorkspace::delete); - - if (isInterrupted) { - Thread.currentThread().interrupt(); - } - } - - @SuppressWarnings("FutureReturnValueIgnored") - private void initializePool() { - LOG.info("Initialize workspace pool with {} entries.", poolSize); - testWorkspaceQueue = new ArrayBlockingQueue<>(poolSize); - executor = - Executors.newSingleThreadScheduledExecutor( - new ThreadFactoryBuilder() - .setNameFormat("WorkspaceInitializer-%d") - .setDaemon(true) - .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) - .build()); - - executor.scheduleWithFixedDelay( - () -> { - while (testWorkspaceQueue.remainingCapacity() != 0) { - String name = generateName(); - TestWorkspace testWorkspace; - try { - testWorkspace = - new CheTestWorkspace( - name, - defaultUser, - defaultMemoryGb, - true, - workspaceDtoDeserializer.deserializeWorkspaceTemplate( - WorkspaceTemplate.DEFAULT), - testWorkspaceServiceClient, - testWorkspaceLogsReader, - workspaceLogsDir); - } catch (Exception e) { - // scheduled executor service doesn't log any exceptions, so log possible exception - // here - LOG.error(e.getLocalizedMessage(), e); - throw e; - } - try { - if (!testWorkspaceQueue.offer(testWorkspace)) { - LOG.warn("Workspace {} can't be added into the pool and will be destroyed.", name); - testWorkspace.delete(); - } - } catch (Exception e) { - LOG.warn( - "Workspace {} can't be added into the pool and will be destroyed because of: {}", - name, - e.getMessage()); - testWorkspace.delete(); - } - } - }, - 0, - 100, - TimeUnit.MILLISECONDS); - } - - private boolean hasDefaultValues( - TestUser testUser, int memoryGB, String templateFileName, boolean startAfterCreation) { - return memoryGB == defaultMemoryGb - && WorkspaceTemplate.DEFAULT.equals(templateFileName) - && testUser.getEmail().equals(defaultUser.getEmail()) - && startAfterCreation; - } - - private TestWorkspace doGetWorkspaceFromPool() throws Exception { - try { - // insure workspace is running - TestWorkspace testWorkspace = testWorkspaceQueue.take(); - WorkspaceStatus testWorkspaceStatus = - testWorkspaceServiceClient.getById(testWorkspace.getId()).getStatus(); - - if (testWorkspaceStatus != WorkspaceStatus.RUNNING) { - testWorkspaceServiceClient.start( - testWorkspace.getId(), testWorkspace.getName(), testWorkspace.getOwner()); - } - - return testWorkspace; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Retrieving a new workspace has been interrupted.", e); - } - } - - private List extractWorkspaceInfo() { - return testWorkspaceQueue - .stream() - .map( - s -> { - try { - return s.getName(); - } catch (ExecutionException | InterruptedException e) { - throw new RuntimeException("Error of getting name of workspace.", e); - } - }) - .collect(Collectors.toList()); - } - - private String generateName() { - return NameGenerator.generate("workspace", 6); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/InjectTestWorkspace.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/InjectTestWorkspace.java deleted file mode 100644 index bfd1733b65..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/InjectTestWorkspace.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; -import static org.eclipse.che.selenium.core.workspace.WorkspaceTemplate.DEFAULT; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; -import org.eclipse.che.selenium.core.user.TestUser; - -/** - * To instantiate {@link TestWorkspace} in test classes with none default parameters. - * - * @see TestWorkspaceProvider#createWorkspace(TestUser, int, String, boolean) - * @author Anatolii Bazko - */ -@Target({FIELD}) -@Retention(RUNTIME) -@Documented -public @interface InjectTestWorkspace { - /** - * Workspace memory in GB. If the value is less or equal to zero then the default value will be - * used. - */ - int memoryGb() default -1; - - /** Workspace template to create workspace base upon. */ - String template() default DEFAULT; - - /** The workspace owner. If value is empty then default user will be used. */ - String user() default ""; - - /** Should we start workspace just after creation. */ - boolean startAfterCreation() default true; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/MemoryMeasure.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/MemoryMeasure.java deleted file mode 100644 index 535d0fdb00..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/MemoryMeasure.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -/** @author Anatolii Bazko */ -public enum MemoryMeasure { - MB, - GB -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspace.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspace.java deleted file mode 100644 index 803ae635c5..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspace.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import java.util.concurrent.ExecutionException; -import org.eclipse.che.selenium.core.user.TestUser; - -/** - * Represents workspace in a test environment. - * - * @author Anatolii Bazko - */ -public interface TestWorkspace { - - /** Return the name of the workspace. */ - String getName() throws ExecutionException, InterruptedException; - - /** Returns the id of the workspace. */ - String getId() throws ExecutionException, InterruptedException; - - /** Returns owner of the workspace. */ - TestUser getOwner(); - - /** Waits until workspace is started. */ - void await() throws InterruptedException, ExecutionException; - - /** Deletes workspace. */ - void delete(); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceInjector.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceInjector.java deleted file mode 100644 index 97c3806b09..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceInjector.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import com.google.inject.Injector; -import java.lang.reflect.Field; - -/** - * Injector for custom annotation {@link InjectTestWorkspace}. - * - * @author Anatolii Bazko - */ -public class TestWorkspaceInjector extends AbstractTestWorkspaceInjector { - - public TestWorkspaceInjector( - Field field, InjectTestWorkspace injectTestWorkspace, Injector injector) { - super(field, injectTestWorkspace, injector); - } - - @Override - protected TestWorkspaceProvider getTestWorkspaceProvider() { - return injector.getInstance(TestWorkspaceProvider.class); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceLogsReader.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceLogsReader.java deleted file mode 100644 index a9ec2b3b44..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceLogsReader.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import static org.eclipse.che.selenium.core.utils.FileUtil.removeDirectoryIfItIsEmpty; - -import com.google.common.annotations.VisibleForTesting; -import com.google.inject.Inject; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.concurrent.ExecutionException; -import org.eclipse.che.api.core.util.AbstractLineConsumer; -import org.eclipse.che.api.core.util.LineConsumer; -import org.eclipse.che.api.core.util.ListLineConsumer; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClient; -import org.eclipse.che.selenium.core.utils.process.ProcessAgent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Reads and stores the workspace logs by using command line operations. It ignores absent or empty - * logs directory. - * - * @author Dmytro Nochevnov - */ -public abstract class TestWorkspaceLogsReader { - - private static final String READ_LOGS_ERROR_MESSAGE_TEMPLATE = - "Can't obtain '{}' logs from workspace with id='{}' from directory '{}'."; - - @VisibleForTesting Logger log = LoggerFactory.getLogger(this.getClass()); - - @Inject @VisibleForTesting TestWorkspaceServiceClient workspaceServiceClient; - - @Inject @VisibleForTesting ProcessAgent processAgent; - - /** - * Read logs from workspace. It ignores absent or empty logs directory. - * - * @param workspace workspace which logs should be read. - * @param pathToStore location of directory where logs should be stored. - * @param suppressWarnings do not log warnings if there is a problem with getting workspace logs - */ - public void store(TestWorkspace workspace, Path pathToStore, boolean suppressWarnings) { - if (!canWorkspaceLogsBeRead()) { - return; - } - - final String workspaceId; - try { - workspaceId = workspace.getId(); - } catch (ExecutionException | InterruptedException e) { - log.warn("It's impossible to get id of test workspace.", e); - return; - } - - store(workspaceId, pathToStore, suppressWarnings); - } - - /** - * Store logs from workspace. It ignores absent or empty logs directory. - * - * @param workspaceId id of workspace which logs should be read. - * @param suppressWarnings do not log warnings if there is a problem with getting workspace logs - */ - public void store(String workspaceId, Path pathToStore, boolean suppressWarnings) { - // check if workspace exists - if (workspaceId == null) { - return; - } - - if (!canWorkspaceLogsBeRead()) { - return; - } - - getLogInfos() - .forEach( - logInfo -> - storeLog(logInfo, workspaceId, pathToStore.resolve(workspaceId), suppressWarnings)); - - try { - removeDirectoryIfItIsEmpty(pathToStore.resolve(workspaceId)); - removeDirectoryIfItIsEmpty(pathToStore); - } catch (IOException e) { - log.debug("Error of removal of empty log directory {}.", pathToStore.resolve(workspaceId), e); - } - } - - private void storeLog( - LogInfo logInfo, String workspaceId, Path pathToStore, boolean suppressWarnings) { - Path testLogsDirectory = pathToStore.resolve(logInfo.getName()); - - try { - Files.createDirectories(testLogsDirectory.getParent()); - - // process command to copy logs from workspace container to the workspaceLogsDir - processAgent.process( - getReadLogsCommand(workspaceId, testLogsDirectory, logInfo.getLocationInsideWorkspace())); - } catch (Exception e) { - if (!suppressWarnings) { - log.warn( - READ_LOGS_ERROR_MESSAGE_TEMPLATE, - logInfo.getName(), - workspaceId, - logInfo.getLocationInsideWorkspace(), - e); - } - } finally { - try { - removeDirectoryIfItIsEmpty(testLogsDirectory); - } catch (IOException e) { - log.debug("Error of removal of empty log directory {}.", testLogsDirectory, e); - } - } - } - - /** - * Returns bash command to read logs from workspace by path to them inside workspace. - * - * @param workspaceId ID of workspace - * @param testLogsDirectory location of directory to save the logs - * @param logLocationInsideWorkspace location of logs inside workspace - * @return command to read logs from workspace - */ - abstract String getReadLogsCommand( - String workspaceId, Path testLogsDirectory, Path logLocationInsideWorkspace); - - /** - * Gets list of available workspace log providers which are dedicated to read certain logs. - * - * @return list of log providers - */ - abstract List getLogInfos(); - - /** - * Checks if it is possible to read logs from workspace. - * - * @return true if it is possible to read logs from workspace, or false otherwise. - */ - abstract boolean canWorkspaceLogsBeRead(); - - @VisibleForTesting - LineConsumer getStdoutConsumer() { - return new AbstractLineConsumer() {}; - } - - @VisibleForTesting - ListLineConsumer getStderrConsumer() { - return new ListLineConsumer(); - } - - /** Holds information about log to read. */ - static class LogInfo { - private final String name; - private final Path locationInsideWorkspace; - - private LogInfo(String name, Path locationInsideWorkspace) { - this.name = name; - this.locationInsideWorkspace = locationInsideWorkspace; - } - - String getName() { - return name; - } - - Path getLocationInsideWorkspace() { - return locationInsideWorkspace; - } - - static LogInfo create(String name, Path locationInsideWorkspace) { - return new LogInfo(name, locationInsideWorkspace); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceProvider.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceProvider.java deleted file mode 100644 index e2fb7aa35c..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceProvider.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import org.eclipse.che.selenium.core.user.TestUser; - -/** - * Workspace provider. - * - * @author Anatolii Bazko - */ -public interface TestWorkspaceProvider { - - /** - * Creates a new workspace. - * - * @param owner the workspace owner - * @param memoryGB the workspace memory size in GB - * @param templateFileName the workspace template file name {@link WorkspaceTemplate} - * @param startAfterCreation start workspace just after creation, if true - */ - TestWorkspace createWorkspace( - TestUser owner, int memoryGB, String templateFileName, boolean startAfterCreation) - throws Exception; - - /** - * Get existed workspace. - * - * @param workspaceName name of workspace - * @param owner the workspace owner - */ - TestWorkspace getWorkspace(String workspaceName, TestUser owner); - - /** Release all allocated resources. */ - void shutdown(); -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceUrlResolver.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceUrlResolver.java deleted file mode 100644 index 7f85a48221..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceUrlResolver.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import java.net.MalformedURLException; -import java.net.URL; - -/** @author Anatolii Bazko */ -public interface TestWorkspaceUrlResolver { - - /** Returns URL to the workspace. */ - URL resolve(TestWorkspace testWorkspace) throws MalformedURLException; -} diff --git a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/WorkspaceTemplate.java b/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/WorkspaceTemplate.java deleted file mode 100644 index d1614e4999..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/main/java/org/eclipse/che/selenium/core/workspace/WorkspaceTemplate.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -/** - * Templates file names to create workspaces based upon. - * - * @author Dmytro Nochevnov - */ -public final class WorkspaceTemplate { - public static final String BROKEN = "broken_workspace.json"; - public static final String DEFAULT = "default.json"; - public static final String DEFAULT_WITH_GITHUB_PROJECTS = "default_with_github_projects.json"; - public static final String ECLIPSE_PHP = "eclipse_php.json"; - public static final String ECLIPSE_NODEJS = "eclipse_nodejs.json"; - public static final String ECLIPSE_CPP_GCC = "eclipse_cpp_gcc.json"; - public static final String ECLIPSE_NODEJS_YAML = "eclipse_nodejs_with_yaml_ls.json"; - public static final String PYTHON = "ubuntu_python.json"; - public static final String NODEJS_WITH_JSON_LS = "nodejs_with_json_ls.json"; - public static final String UBUNTU = "ubuntu.json"; - public static final String UBUNTU_GO = "ubuntu_go.json"; - public static final String UBUNTU_JDK8 = "ubuntu_jdk8.json"; - public static final String UBUNTU_LSP = "ubuntu_with_c_sharp_lsp.json"; - public static final String APACHE_CAMEL = "spring_boot_with_apache_camel_ls.json"; - - private WorkspaceTemplate() {} -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/action/GenericActionsTest.java b/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/action/GenericActionsTest.java deleted file mode 100644 index 3ba4ede400..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/action/GenericActionsTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.action; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -import org.mockito.Mockito; -import org.mockito.testng.MockitoTestNGListener; -import org.openqa.selenium.Keys; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.interactions.HasInputDevices; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -/** - * Unit tests for the {@link GenericActions}. - * - * @author Vlad Zhukovskyi - */ -@Listeners(value = MockitoTestNGListener.class) -public class GenericActionsTest { - - private WebDriver webDriver; - - @BeforeMethod - public void setUp() throws Exception { - webDriver = - Mockito.mock( - WebDriver.class, Mockito.withSettings().extraInterfaces(HasInputDevices.class)); - } - - @Test - public void testShouldReturnSameCharSequence() throws Exception { - GenericActions actions = new GenericActions(webDriver); - - final CharSequence[] charSequences = - actions.modifyCharSequence(Keys.END, Keys.HOME, Keys.PAGE_DOWN, Keys.PAGE_UP); - - assertNotNull(charSequences); - assertEquals(charSequences.length, 4); - - assertEquals(charSequences[0], Keys.END); - assertEquals(charSequences[1], Keys.HOME); - assertEquals(charSequences[2], Keys.PAGE_DOWN); - assertEquals(charSequences[3], Keys.PAGE_UP); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/action/MacOSActionsTest.java b/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/action/MacOSActionsTest.java deleted file mode 100644 index ee7cc42b47..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/action/MacOSActionsTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.action; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -import org.mockito.Mockito; -import org.mockito.testng.MockitoTestNGListener; -import org.openqa.selenium.Keys; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.interactions.HasInputDevices; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -/** - * Unit tests for the {@link MacOSActions}. - * - * @author Vlad Zhukovskyi - */ -@Listeners(value = MockitoTestNGListener.class) -public class MacOSActionsTest { - - private WebDriver webDriver; - - @BeforeMethod - public void setUp() throws Exception { - webDriver = - Mockito.mock( - WebDriver.class, Mockito.withSettings().extraInterfaces(HasInputDevices.class)); - } - - @Test - public void testShouldReplaceEndCharSequence() throws Exception { - MacOSActions actions = new MacOSActions(webDriver); - - final CharSequence[] charSequences = actions.modifyCharSequence(Keys.ESCAPE, Keys.END); - - assertNotNull(charSequences); - assertEquals(charSequences.length, 2); - - assertEquals(charSequences[0], Keys.ESCAPE); - assertEquals(charSequences[1], Keys.chord(Keys.COMMAND, Keys.RIGHT)); - } - - @Test - public void testShouldReplaceHomeCharSequence() throws Exception { - MacOSActions actions = new MacOSActions(webDriver); - - final CharSequence[] charSequences = actions.modifyCharSequence(Keys.ESCAPE, Keys.HOME); - - assertNotNull(charSequences); - assertEquals(charSequences.length, 2); - - assertEquals(charSequences[0], Keys.ESCAPE); - assertEquals(charSequences[1], Keys.chord(Keys.COMMAND, Keys.LEFT)); - } - - @Test - public void testShouldReplacePageDownCharSequence() throws Exception { - MacOSActions actions = new MacOSActions(webDriver); - - final CharSequence[] charSequences = actions.modifyCharSequence(Keys.ESCAPE, Keys.PAGE_DOWN); - - assertNotNull(charSequences); - assertEquals(charSequences.length, 2); - - assertEquals(charSequences[0], Keys.ESCAPE); - assertEquals(charSequences[1], Keys.chord(Keys.COMMAND, Keys.DOWN)); - } - - @Test - public void testShouldReplacePageUpCharSequence() throws Exception { - MacOSActions actions = new MacOSActions(webDriver); - - final CharSequence[] charSequences = actions.modifyCharSequence(Keys.ESCAPE, Keys.PAGE_UP); - - assertNotNull(charSequences); - assertEquals(charSequences.length, 2); - - assertEquals(charSequences[0], Keys.ESCAPE); - assertEquals(charSequences[1], Keys.chord(Keys.COMMAND, Keys.UP)); - } - - @Test - public void testShouldNotReplaceAnyCharSequence() throws Exception { - MacOSActions actions = new MacOSActions(webDriver); - - final CharSequence[] charSequences = actions.modifyCharSequence(Keys.ESCAPE, Keys.ENTER); - - assertNotNull(charSequences); - assertEquals(charSequences.length, 2); - - assertEquals(charSequences[0], Keys.ESCAPE); - assertEquals(charSequences[1], Keys.ENTER); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/inject/SeleniumTestStatisticsTest.java b/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/inject/SeleniumTestStatisticsTest.java deleted file mode 100644 index 4da454560c..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/inject/SeleniumTestStatisticsTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.inject; - -import static java.util.stream.IntStream.range; -import static org.testng.Assert.assertEquals; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -/** @author Dmytro Nochevnov */ -public class SeleniumTestStatisticsTest { - private static final Logger LOG = LoggerFactory.getLogger(SeleniumTestStatisticsTest.class); - - @Test(dataProvider = "testData") - @SuppressWarnings("FutureReturnValueIgnored") - public void testSimultaneousUsage( - int hitStart, - int hitPass, - int hitFail, - int hitSkip, - String initialToString, - String finalToString) - throws InterruptedException { - // given - SeleniumTestStatistics seleniumTestStatistics = new SeleniumTestStatistics(); - - // when - String actualString = seleniumTestStatistics.toString(); - - // then - assertEquals(actualString, initialToString); - - // when - ExecutorService executor = Executors.newFixedThreadPool(10); - - range(0, hitStart).forEach(i -> executor.submit(seleniumTestStatistics::hitStart)); - range(0, hitPass).forEach(i -> executor.submit(seleniumTestStatistics::hitPass)); - range(0, hitFail).forEach(i -> executor.submit(seleniumTestStatistics::hitFail)); - range(0, hitSkip).forEach(i -> executor.submit(seleniumTestStatistics::hitSkip)); - - executor.awaitTermination(20, TimeUnit.SECONDS); - - // then - assertEquals(seleniumTestStatistics.toString(), finalToString); - assertEquals(seleniumTestStatistics.hitStart(), hitStart + 1); - assertEquals(seleniumTestStatistics.hitPass(), hitPass + 1); - assertEquals(seleniumTestStatistics.hitFail(), hitFail + 1); - assertEquals(seleniumTestStatistics.hitSkip(), hitSkip + 1); - } - - @DataProvider - public Object[][] testData() { - return new Object[][] { - {0, 0, 0, 0, "Passed: 0, failed: 0, skipped: 0.", "Passed: 0, failed: 0, skipped: 0."}, - {31, 21, 5, 4, "Passed: 0, failed: 0, skipped: 0.", "Passed: 21, failed: 5, skipped: 4."} - }; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/inject/TestFilterTest.java b/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/inject/TestFilterTest.java deleted file mode 100644 index 04c32a40b8..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/inject/TestFilterTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.inject; - -import static org.eclipse.che.selenium.core.TestGroup.DOCKER; -import static org.eclipse.che.selenium.core.TestGroup.FLAKY; -import static org.eclipse.che.selenium.core.TestGroup.GITHUB; -import static org.eclipse.che.selenium.core.TestGroup.K8S; -import static org.eclipse.che.selenium.core.TestGroup.MULTIUSER; -import static org.eclipse.che.selenium.core.TestGroup.OPENSHIFT; -import static org.eclipse.che.selenium.core.TestGroup.OSIO; -import static org.eclipse.che.selenium.core.TestGroup.SINGLEUSER; -import static org.eclipse.che.selenium.core.TestGroup.UNDER_REPAIR; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -import org.eclipse.che.selenium.core.constant.Infrastructure; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.ITestOrConfiguration; -import org.testng.annotations.Test; - -/** @author Dmytro Nochevnov */ -public class TestFilterTest { - - public static final String SOME_GROUP = "some_group"; - public static final String[] EMPTY_TEST_GROUPS = {}; - public static final String EMPTY_EXCLUDED_GROUPS = ""; - public static final boolean CHE_SINGLEUSER = false; - public static final boolean CHE_MULTIUSER = true; - @Mock private ITestOrConfiguration mockTestAnnotation; - - @BeforeMethod - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test(dataProvider = "disableTestGroupManagementData") - public void shouldDisableTest( - String[] testGroups, - String excludedGroups, - boolean isMultiuser, - Infrastructure infrastructure) { - // given - TestFilter testFilter = new TestFilter(excludedGroups, isMultiuser, infrastructure); - doReturn(testGroups).when(mockTestAnnotation).getGroups(); - - // when - testFilter.excludeTestOfImproperGroup(mockTestAnnotation); - - // then - verify(mockTestAnnotation).setEnabled(false); - } - - @DataProvider - public Object[][] disableTestGroupManagementData() { - return new Object[][] { - {new String[] {GITHUB}, GITHUB, CHE_MULTIUSER, Infrastructure.OPENSHIFT}, - { - new String[] {UNDER_REPAIR}, - SOME_GROUP + "," + UNDER_REPAIR, - CHE_SINGLEUSER, - Infrastructure.OPENSHIFT - }, - {new String[] {OPENSHIFT, FLAKY}, GITHUB, CHE_MULTIUSER, Infrastructure.DOCKER}, - {new String[] {MULTIUSER}, SOME_GROUP, CHE_SINGLEUSER, Infrastructure.DOCKER}, - { - new String[] {OPENSHIFT, OSIO}, EMPTY_EXCLUDED_GROUPS, CHE_SINGLEUSER, Infrastructure.DOCKER - }, - { - new String[] {DOCKER, SINGLEUSER}, - EMPTY_EXCLUDED_GROUPS, - CHE_MULTIUSER, - Infrastructure.DOCKER - }, - {new String[] {OPENSHIFT}, EMPTY_EXCLUDED_GROUPS, CHE_SINGLEUSER, Infrastructure.DOCKER}, - { - new String[] {K8S, SINGLEUSER, MULTIUSER}, - EMPTY_EXCLUDED_GROUPS, - CHE_MULTIUSER, - Infrastructure.DOCKER - } - }; - } - - @Test(dataProvider = "enableTestGroupManagementData") - public void shouldEnableTest( - String[] testGroups, - String excludedGroups, - boolean isMultiuser, - Infrastructure infrastructure) { - // given - TestFilter testFilter = new TestFilter(excludedGroups, isMultiuser, infrastructure); - doReturn(testGroups).when(mockTestAnnotation).getGroups(); - - // when - testFilter.excludeTestOfImproperGroup(mockTestAnnotation); - - // then - verify(mockTestAnnotation, never()).setEnabled(false); - } - - @DataProvider - public Object[][] enableTestGroupManagementData() { - return new Object[][] { - {EMPTY_TEST_GROUPS, EMPTY_EXCLUDED_GROUPS, CHE_SINGLEUSER, Infrastructure.OPENSHIFT}, - {EMPTY_TEST_GROUPS, EMPTY_EXCLUDED_GROUPS, CHE_MULTIUSER, Infrastructure.DOCKER}, - {EMPTY_TEST_GROUPS, GITHUB, CHE_SINGLEUSER, Infrastructure.DOCKER}, - {new String[] {GITHUB}, SOME_GROUP, CHE_MULTIUSER, Infrastructure.OPENSHIFT}, - { - new String[] {GITHUB, OPENSHIFT}, - EMPTY_EXCLUDED_GROUPS, - CHE_MULTIUSER, - Infrastructure.OPENSHIFT - }, - { - new String[] {GITHUB, OPENSHIFT, DOCKER}, - EMPTY_EXCLUDED_GROUPS, - CHE_MULTIUSER, - Infrastructure.DOCKER - }, - {new String[] {MULTIUSER}, EMPTY_EXCLUDED_GROUPS, CHE_MULTIUSER, Infrastructure.OPENSHIFT}, - { - new String[] {GITHUB, SINGLEUSER, MULTIUSER}, - EMPTY_EXCLUDED_GROUPS, - CHE_SINGLEUSER, - Infrastructure.OPENSHIFT - }, - { - new String[] {SINGLEUSER, MULTIUSER, OPENSHIFT}, - EMPTY_EXCLUDED_GROUPS, - CHE_MULTIUSER, - Infrastructure.OPENSHIFT - } - }; - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/utils/WaitSuccessConditionTest.java b/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/utils/WaitSuccessConditionTest.java deleted file mode 100644 index a4d6c349ce..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/utils/WaitSuccessConditionTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -import static org.eclipse.che.selenium.core.utils.WaitUtils.DEFAULT_DELAY_BETWEEN_ATTEMPTS_IN_MILLISECONDS; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.BooleanSupplier; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -/** @author Dmytro Nochevnov */ -public class WaitSuccessConditionTest { - private static final int NUMBER_OF_SUCCESS_CONDITION_CALL = 3; - private static final long CONDITION_DELAY_MILLISECS = 300; - private int countToZeroToSuccess; - - /** - * Returns true at {@code NUMBER_OF_SUCCESS_CONDITION_CALL}. Operation lasts {@code - * CONDITION_DELAY_MILLISECS}. - */ - private BooleanSupplier testCondition = - () -> { - try { - Thread.sleep(CONDITION_DELAY_MILLISECS); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - - return --countToZeroToSuccess == 0; - }; - - @BeforeMethod - public void setupTestCondition() { - countToZeroToSuccess = NUMBER_OF_SUCCESS_CONDITION_CALL; - } - - @Test - public void shouldSuccessWithTimeoutInMillisecs() throws Exception { - WaitUtils.waitSuccessCondition( - testCondition, - NUMBER_OF_SUCCESS_CONDITION_CALL * CONDITION_DELAY_MILLISECS * 4, - CONDITION_DELAY_MILLISECS / 2, - TimeUnit.MILLISECONDS); - } - - @Test( - expectedExceptions = TimeoutException.class, - expectedExceptionsMessageRegExp = - "Expected condition failed: waiting for 600 MILLISECONDS with 150 MILLISECONDS interval") - public void shouldFailBecauseTooSmallTimeout() throws Exception { - WaitUtils.waitSuccessCondition( - testCondition, - (NUMBER_OF_SUCCESS_CONDITION_CALL - 1) * CONDITION_DELAY_MILLISECS, - CONDITION_DELAY_MILLISECS / 2, - TimeUnit.MILLISECONDS); - } - - @Test( - expectedExceptions = TimeoutException.class, - expectedExceptionsMessageRegExp = - "Expected condition failed: waiting for 1800 MILLISECONDS with 2700 MILLISECONDS interval") - public void shouldFailBecauseTooLongDelayBetweenAttempts() - throws InterruptedException, TimeoutException, ExecutionException { - WaitUtils.waitSuccessCondition( - testCondition, - NUMBER_OF_SUCCESS_CONDITION_CALL * CONDITION_DELAY_MILLISECS * 2, - NUMBER_OF_SUCCESS_CONDITION_CALL * CONDITION_DELAY_MILLISECS * 3, - TimeUnit.MILLISECONDS); - } - - @Test( - expectedExceptions = ExecutionException.class, - expectedExceptionsMessageRegExp = "java.lang.RuntimeException: test") - public void shouldFailBecauseConditionCheckException() throws Exception { - WaitUtils.waitSuccessCondition( - () -> { - throw new RuntimeException("test"); - }, - CONDITION_DELAY_MILLISECS * 2, - CONDITION_DELAY_MILLISECS, - TimeUnit.MILLISECONDS); - } - - @Test( - expectedExceptions = TimeoutException.class, - expectedExceptionsMessageRegExp = - "Expected condition failed: waiting for 150 MILLISECONDS with 30 MILLISECONDS interval") - public void shouldFailBecauseOperationTakesTooLongTime() - throws InterruptedException, TimeoutException, ExecutionException { - countToZeroToSuccess = 0; - WaitUtils.waitSuccessCondition( - testCondition, - CONDITION_DELAY_MILLISECS / 2, - CONDITION_DELAY_MILLISECS / 10, - TimeUnit.MILLISECONDS); - } - - @Test( - expectedExceptions = TimeoutException.class, - expectedExceptionsMessageRegExp = - "Expected condition failed: waiting for 1 SECONDS with 500 MILLISECONDS interval") - public void shouldFailWithDefaultDelay() throws Exception { - WaitUtils.waitSuccessCondition( - testCondition, DEFAULT_DELAY_BETWEEN_ATTEMPTS_IN_MILLISECONDS * 2 / 1000); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/utils/WorkspaceDtoDeserializerTest.java b/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/utils/WorkspaceDtoDeserializerTest.java deleted file mode 100644 index 0fbbf8c852..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/utils/WorkspaceDtoDeserializerTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.utils; - -import java.lang.reflect.Field; -import org.eclipse.che.selenium.core.constant.Infrastructure; -import org.eclipse.che.selenium.core.workspace.WorkspaceTemplate; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class WorkspaceDtoDeserializerTest { - - private WorkspaceDtoDeserializer deserializer; - - @BeforeMethod - public void setUp() throws Exception { - deserializer = new WorkspaceDtoDeserializer(); - Field f1 = WorkspaceDtoDeserializer.class.getDeclaredField("infrastructure"); - f1.setAccessible(true); - f1.set(deserializer, Infrastructure.OPENSHIFT); - } - - @Test - public void shouldBeAbleToGetWorkspaceConfigFromResource() { - - Assert.assertNotNull(deserializer.deserializeWorkspaceTemplate(WorkspaceTemplate.DEFAULT)); - } - - @Test( - expectedExceptions = RuntimeException.class, - expectedExceptionsMessageRegExp = - "com.google.gson.stream.MalformedJsonException: Expected ':' at line 3 column 8 path \\$\\.werwerw") - public void shouldFailIfNotAJson() { - deserializer.deserializeWorkspaceTemplate(WorkspaceTemplate.BROKEN); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceLogsReaderTest.java b/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceLogsReaderTest.java deleted file mode 100644 index aef1058d10..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/java/org/eclipse/che/selenium/core/workspace/TestWorkspaceLogsReaderTest.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.workspace.TestWorkspaceLogsReader.LogInfo.create; -import static org.mockito.ArgumentCaptor.forClass; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -import com.google.common.collect.ImmutableList; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.concurrent.ExecutionException; -import org.eclipse.che.api.core.model.workspace.WorkspaceStatus; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClient; -import org.eclipse.che.selenium.core.utils.process.ProcessAgent; -import org.eclipse.che.selenium.core.utils.process.ProcessAgentException; -import org.eclipse.che.selenium.core.workspace.TestWorkspaceLogsReader.LogInfo; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.mockito.testng.MockitoTestNGListener; -import org.slf4j.Logger; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -/** - * Unit tests for the {@link TestWorkspaceLogsReader} - * - * @author Dmytro Nochevnov - */ -@Listeners(value = MockitoTestNGListener.class) -public class TestWorkspaceLogsReaderTest { - - private static final LogInfo FIRST_LOG_INFO = create("log-1", Paths.get("log-1-location")); - private static final LogInfo SECOND_LOG_INFO = create("log-2", Paths.get("log-2-location")); - private static final ImmutableList TEST_LOG_INFOS = - ImmutableList.of(FIRST_LOG_INFO, SECOND_LOG_INFO); - private static final String TEST_READ_FIRST_LOG_COMMAND = "echo 'read-log-1'"; - private static final String TEST_READ_SECOND_LOG_COMMAND = "echo 'read-log-2'"; - private static final String UNKNOWN_COMMAND = "command-435f4q6we3as5va5s"; - private static final String TEST_WORKSPACE_ID = "workspace-id"; - private static final Path PATH_TO_STORE_LOGS = - Paths.get(TestWorkspaceLogsReaderTest.class.getResource("").getPath()); - private static final WorkspaceStatus WRONG_WORKSPACE_STATUS = WorkspaceStatus.STOPPED; - - @Spy private TestWorkspaceLogsReader testWorkspaceLogsReader; - - @Mock private TestWorkspace testWorkspace; - @Mock private TestWorkspaceServiceClient testWorkspaceServiceClient; - @Mock private Logger log; - - @BeforeMethod - public void setup() throws ExecutionException, InterruptedException { - MockitoAnnotations.initMocks(this); - - testWorkspaceLogsReader.workspaceServiceClient = testWorkspaceServiceClient; - testWorkspaceLogsReader.log = log; - testWorkspaceLogsReader.processAgent = new ProcessAgent(); - - lenient().doReturn(TEST_WORKSPACE_ID).when(testWorkspace).getId(); - - // init logs read commands - lenient().doReturn(TEST_LOG_INFOS).when(testWorkspaceLogsReader).getLogInfos(); - - lenient() - .doReturn(TEST_READ_FIRST_LOG_COMMAND) - .when(testWorkspaceLogsReader) - .getReadLogsCommand( - TEST_WORKSPACE_ID, - Paths.get( - format( - "%s/%s/%s", PATH_TO_STORE_LOGS, TEST_WORKSPACE_ID, FIRST_LOG_INFO.getName())), - FIRST_LOG_INFO.getLocationInsideWorkspace()); - - lenient() - .doReturn(TEST_READ_SECOND_LOG_COMMAND) - .when(testWorkspaceLogsReader) - .getReadLogsCommand( - TEST_WORKSPACE_ID, - Paths.get( - format( - "%s/%s/%s", PATH_TO_STORE_LOGS, TEST_WORKSPACE_ID, SECOND_LOG_INFO.getName())), - SECOND_LOG_INFO.getLocationInsideWorkspace()); - } - - @Test - public void shouldReadLogSuccessfully() throws Exception { - // given - doReturn(true).when(testWorkspaceLogsReader).canWorkspaceLogsBeRead(); - doReturn(WorkspaceStatus.RUNNING).when(testWorkspaceServiceClient).getStatus(TEST_WORKSPACE_ID); - - // when - testWorkspaceLogsReader.store(testWorkspace, PATH_TO_STORE_LOGS, false); - - // then - verifyZeroInteractions(log); - } - - @Test - public void shouldReadLogIfWorkspaceIsNotRunning() throws Exception { - // given - doReturn(true).when(testWorkspaceLogsReader).canWorkspaceLogsBeRead(); - doReturn(WRONG_WORKSPACE_STATUS).when(testWorkspaceServiceClient).getStatus(TEST_WORKSPACE_ID); - - // when - testWorkspaceLogsReader.store(testWorkspace, PATH_TO_STORE_LOGS, false); - - // then - verifyZeroInteractions(log); - } - - @Test - public void shouldAbortExecutionIfWorkspaceCannotBeRead() throws Exception { - // given - doReturn(false).when(testWorkspaceLogsReader).canWorkspaceLogsBeRead(); - - // when - testWorkspaceLogsReader.store(testWorkspace, PATH_TO_STORE_LOGS, false); - - // then - verify(testWorkspaceLogsReader, never()).getLogInfos(); - verifyZeroInteractions(log); - } - - @Test - public void shouldHandleCommandError() throws Exception { - // given - doReturn(UNKNOWN_COMMAND) - .when(testWorkspaceLogsReader) - .getReadLogsCommand( - TEST_WORKSPACE_ID, - Paths.get( - format( - "%s/%s/%s", PATH_TO_STORE_LOGS, TEST_WORKSPACE_ID, FIRST_LOG_INFO.getName())), - FIRST_LOG_INFO.getLocationInsideWorkspace()); - - doReturn(true).when(testWorkspaceLogsReader).canWorkspaceLogsBeRead(); - doReturn(WorkspaceStatus.RUNNING).when(testWorkspaceServiceClient).getStatus(TEST_WORKSPACE_ID); - - // when - testWorkspaceLogsReader.store(testWorkspace, PATH_TO_STORE_LOGS, false); - - // then - ArgumentCaptor logArgumentCaptor1 = forClass(String.class); - ArgumentCaptor logArgumentCaptor2 = forClass(String.class); - ArgumentCaptor logArgumentCaptor3 = forClass(String.class); - ArgumentCaptor logArgumentCaptor4 = forClass(Path.class); - ArgumentCaptor logArgumentCaptor5 = - forClass(ProcessAgentException.class); - - verify(log) - .warn( - logArgumentCaptor1.capture(), - logArgumentCaptor2.capture(), - logArgumentCaptor3.capture(), - logArgumentCaptor4.capture(), - logArgumentCaptor5.capture()); - - assertEquals( - logArgumentCaptor1.getValue(), - "Can't obtain '{}' logs from workspace with id='{}' from directory '{}'."); - assertEquals(logArgumentCaptor2.getValue(), FIRST_LOG_INFO.getName()); - assertEquals(logArgumentCaptor3.getValue(), TEST_WORKSPACE_ID); - assertEquals(logArgumentCaptor4.getValue(), FIRST_LOG_INFO.getLocationInsideWorkspace()); - - assertNotNull(logArgumentCaptor5.getValue()); - String errorMessage = logArgumentCaptor5.getValue().getMessage(); - assertTrue( - errorMessage.contains(UNKNOWN_COMMAND), "Actual errorMessage content: " + errorMessage); - } - - @Test - public void shouldSuppressCommandErrorWarnings() throws Exception { - // given - doReturn(UNKNOWN_COMMAND) - .when(testWorkspaceLogsReader) - .getReadLogsCommand( - TEST_WORKSPACE_ID, - Paths.get( - format( - "%s/%s/%s", PATH_TO_STORE_LOGS, TEST_WORKSPACE_ID, FIRST_LOG_INFO.getName())), - FIRST_LOG_INFO.getLocationInsideWorkspace()); - - doReturn(true).when(testWorkspaceLogsReader).canWorkspaceLogsBeRead(); - doReturn(WorkspaceStatus.RUNNING).when(testWorkspaceServiceClient).getStatus(TEST_WORKSPACE_ID); - - // when - testWorkspaceLogsReader.store(testWorkspace, PATH_TO_STORE_LOGS, true); - - // then - verifyZeroInteractions(log); - } -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/resources/logback-test.xml b/tests/legacy-e2e/che-selenium-core/src/test/resources/logback-test.xml deleted file mode 100644 index 55b2bc661a..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/resources/logback-test.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - %-41(%date[%.15thread]) %-45([%-5level] [%.30logger{30} %L]) - %msg%n - - - - - - - diff --git a/tests/legacy-e2e/che-selenium-core/src/test/resources/templates/workspace/openshift/broken_workspace.json b/tests/legacy-e2e/che-selenium-core/src/test/resources/templates/workspace/openshift/broken_workspace.json deleted file mode 100644 index 8062b15336..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/resources/templates/workspace/openshift/broken_workspace.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - werwerw - awerw -} diff --git a/tests/legacy-e2e/che-selenium-core/src/test/resources/templates/workspace/openshift/default.json b/tests/legacy-e2e/che-selenium-core/src/test/resources/templates/workspace/openshift/default.json deleted file mode 100644 index d248565362..0000000000 --- a/tests/legacy-e2e/che-selenium-core/src/test/resources/templates/workspace/openshift/default.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "environments": { - "replaced_name": { - "machines": { - "app/main": { - "installers": [ - "org.eclipse.che.terminal", - "org.eclipse.che.ws-agent" - ], - "attributes": { - "memoryLimitBytes": "desired_memory_value" - } - } - }, - "recipe": { - "content": "kind: List\nitems:\n-\n apiVersion: v1\n kind: Pod\n metadata:\n name: app\n spec:\n containers:\n -\n image: rhche/centos_jdk8:latest\n name: main\n ports:\n -\n containerPort: 8080\n protocol: TCP", - "contentType": "application/x-yaml", - "type": "openshift" - } - } - }, - "defaultEnv": "replaced_name", - "projects": [], - "name": "replaced_name", - "attributes": {}, - "temporary": false -} diff --git a/tests/legacy-e2e/che-selenium-test/README.md b/tests/legacy-e2e/che-selenium-test/README.md deleted file mode 100644 index 009fe1c5f2..0000000000 --- a/tests/legacy-e2e/che-selenium-test/README.md +++ /dev/null @@ -1,165 +0,0 @@ -How to run Selenium tests ------------------- - -#### 1. Register OAuth application - -Go to [OAuth application page](https://github.com/settings/applications/new) and register a new application: -* `Application name` : `Che` -* `Homepage URL` : `http://<:YOUR_CHE_PORT>` -* `Application description` : `Che` -* `Authorization callback URL` : `http://<:YOUR_CHE_PORT>/api/oauth/callback` - -Substitute `CHE_OAUTH_GITHUB_CLIENTID` and `CHE_OAUTH_GITHUB_CLIENTSECRET` properties in `che.env` with `Client ID` and `Client Secret` taken from -newly created [OAuth application](https://github.com/settings/developers). - -#### 2. Configure selenium tests -In case of running GitHub-related tests (which are run by default) you need to define GitHub test users credentials. Set `CHE_LOCAL_CONF_DIR` environment variable -and point to the folder where selenium tests configuration will be stored. Then create file with `.properties` extension in that folder -with the following content: -``` -# GitHub account credentials -github.username= -github.password= -github.auxiliary.username= -github.auxiliary.password= -``` - -In case of running the tests for Eclipse Che in Multi User mode you can set your own credentials of test user or admin instead of default ones -``` -export CHE_ADMIN_NAME= -export CHE_ADMIN_EMAIL= -export CHE_ADMIN_PASSWORD= - -export CHE_TESTUSER_NAME= -export CHE_TESTUSER_EMAIL= -export CHE_TESTUSER_PASSWORD= -``` - -Default values: -- CHE_ADMIN_NAME: "admin" -- CHE_ADMIN_EMAIL: "admin@admin.com" -- CHE_ADMIN_PASSWORD: "admin" - -#### 3. Start Eclipse Che - -Follow the guide: [https://github.com/eclipse/che](https://github.com/eclipse/che) - -#### 4. Run tests - -Simply launch `./selenium-tests.sh` - -### How to run tests on OpenShift -#### 1. Set workspace runtime infrastructure implementation -export CHE_INFRASTRUCTURE=openshift -#### 2. Run tests and specify host and port of Che deployed to OpenShift -Launch `./selenium-tests.sh --host= --port=80` - -Example: `./selenium-tests.sh --host=che-spi.192.168.99.100.nip.io --port=80` - -In case of running the tests for Eclipse Che on OCP, which is run remotely with default Eclipse Che admin and test user credentials: -``` -export OPENSHIFT_USERNAME= -export OPENSHIFT_PASSWORD= -export OPENSHIFT_TOKEN= -export OPENSHIFT_CHE_NAMESPACE= -export OPENSHIFT_URL= -``` -where `OPENSHIFT_TOKEN` is optional and is aimed to replace username/password when OpenShift is configured with OAuth. - - -Default values: -- OPENSHIFT_USERNAME: "developer" -- OPENSHIFT_PASSWORD: "any" -- OPENSHIFT_CHE_NAMESPACE: "che" -- OPENSHIFT_URL: https://:8443 - - -Run tests configuration properties --------------------------------------- -``` -Usage: ./selenium-tests.sh [-Mmode] [options] [tests scope] - -Options: - --http Use 'http' protocol to connect to product - --https Use 'https' protocol to connect to product - --host= Set host where product is deployed - --port= Set port of the product, default is 8080 - --multiuser Run tests of Multi User Che - -Modes (defines environment to run tests): - -Mlocal All tests will be run in a Web browser on the developer machine. - Recommended if test visualization is needed and for debugging purpose. - - Options that go with 'local' mode: - --web-driver-version= To use the specific version of the WebDriver, be default the latest will be used: 2.30 - --web-driver-port= To run WebDriver on the specific port, by default: 9515 - --threads= Number of tests that will be run simultaneously. It also means the very same number of - Web browsers will be opened on the developer machine. - Default value is in range [2,5] and depends on available RAM. - - -Mgrid (default) All tests will be run in parallel among several docker containers. - One container per thread. Recommended to run test suite. - - Options that go with 'grid' mode: - --threads= Number of tests that will be run simultaneously. - Default value is in range [2,5] and depends on available RAM. - -Define tests scope: - --test= Single test/package to run. - For example: '--test=DialogAboutTest', '--test=org.eclipse.che.selenium.git.**'. - --suite= Test suite to run. Default suite is CheSuite.xml. - --exclude= Comma-separated list of test groups to exclude from execution. - For example, use '--exclude=github' to exclude GitHub-related tests. - -Handle failing tests: - --failed-tests Rerun failed tests that left after the previous try - --regression-tests Rerun regression tests that left after the previous try - --rerun [ATTEMPTS] Automatically rerun failing tests. - Default attempts number is 1. - --compare-with-ci [BUILD NUMBER] Compare failed tests with results on CI server. - Default build is the latest. - --fail-script-on-failed-tests Fail webdriver.sh if tests failed. - -Other options: - --debug Run tests in debug mode - --skip-sources-validation Fast build. Skips source validation and enforce plugins - --workspace-pool-size=[|auto] Size of test workspace pool. - Default value is 0, that means that test workspaces are created on demand. - --include-tests-under-repair Include tests which permanently fail and so belong to group 'UNDER REPAIR' - --include-flaky-tests Include tests which randomly fail and so belong to group 'FLAKY' - -HOW TO of usage: - Test Eclipse Che single user assembly: - ./selenium-tests.sh - - Test Eclipse Che multi user assembly: - ./selenium-tests.sh --multiuser - - Test Eclipse Che assembly and automatically rerun failing tests: - ./selenium-tests.sh --rerun [ATTEMPTS] - - Run single test or package of tests: - ./selenium-tests.sh <...> --test= - - Run suite: - ./selenium-tests.sh <...> --suite= - - Include tests which belong to groups 'UNDER REPAIR' and 'FLAKY' - ./selenium-tests.sh --include-tests-under-repair --include-flaky-tests - - Rerun failed tests: - ./selenium-tests.sh <...> --failed-tests - ./selenium-tests.sh <...> --failed-tests --rerun [ATTEMPTS] - - Debug selenium test: - ./selenium-tests.sh -Mlocal --test= --debug - - Analyse tests results: - ./selenium-tests.sh --compare-with-ci [BUILD NUMBER] -``` - -Test development tips --------------------------------------- -It's impossible to use `@Test(dependsOnMethods)` to express dependency between the tests because it breaks parallel execution of test classes (an issue https://github.com/cbeust/testng/issues/1773). - -`@Test(priority)` can be used instead, and dependent test will be skipped if preceding test with higher priority from the same test class has failed. diff --git a/tests/legacy-e2e/che-selenium-test/docker-compose.yml b/tests/legacy-e2e/che-selenium-test/docker-compose.yml deleted file mode 100644 index 49a2b93e22..0000000000 --- a/tests/legacy-e2e/che-selenium-test/docker-compose.yml +++ /dev/null @@ -1,49 +0,0 @@ -version: '2' -services: - selenium_hub: - image: selenium/hub:3.141.59-dubnium - container_name: selenium_hub - ports: - - 4444:4444 - environment: - - GRID_TIMEOUT=900 - - GRID_BROWSER_TIMEOUT=900 - - JAVA_OPTS=-Xms512m -Xmx1024m -Djava.security.egd=file:/dev/./urandom - - GRID_CLEAN_UP_CYCLE=5000 - ulimits: - nproc: 163840 - nofile: - soft: 163840 - hard: 163840 - restart: always - networks: - - selenium_grid_internal - - chromenode: - image: selenium/node-chrome${NODE_CHROME_DEBUG_SUFFIX}:3.141.59-dubnium - depends_on: - - selenium_hub - environment: - - HUB_PORT_4444_TCP_ADDR=selenium_hub - - HUB_PORT_4444_TCP_PORT=4444 - - DBUS_SESSION_BUS_ADDRESS=/dev/null - - NODE_MAX_INSTANCES=5 - - NODE_MAX_SESSION=5 - - SCREEN_HEIGHT=1080 - - SCREEN_WIDTH=1920 - - SCREEN_DEPTH=24 - ports: - - 5900 - - 5555 - networks: - - selenium_grid_internal - ulimits: - nproc: 163840 - nofile: - soft: 163840 - hard: 163840 - restart: always - shm_size: 1g - -networks: - selenium_grid_internal: diff --git a/tests/legacy-e2e/che-selenium-test/pom.xml b/tests/legacy-e2e/che-selenium-test/pom.xml deleted file mode 100644 index f2be4dc196..0000000000 --- a/tests/legacy-e2e/che-selenium-test/pom.xml +++ /dev/null @@ -1,389 +0,0 @@ - - - - 4.0.0 - - che-selenium-parent - org.eclipse.che.selenium - 7.29.0-SNAPSHOT - - che-selenium-test - jar - Che Legacy E2E :: Test - - true - ${project.build.testOutputDirectory}/suites/CheSuite.xml - - - - com.google.code.gson - gson - - - com.google.guava - guava - - - com.google.inject - guice - - - com.google.inject.extensions - guice-assistedinject - - - commons-io - commons-io - - - commons-lang - commons-lang - - - javax.annotation - javax.annotation-api - - - javax.inject - javax.inject - - - javax.ws.rs - javax.ws.rs-api - - - org.eclipse.che.core - che-core-api-core - - - org.eclipse.che.core - che-core-api-dto - - - org.eclipse.che.core - che-core-api-model - - - org.eclipse.che.core - che-core-api-system-shared - - - org.eclipse.che.core - che-core-api-workspace-shared - - - org.eclipse.che.core - che-core-commons-annotations - - - org.eclipse.che.core - che-core-commons-json - - - org.eclipse.che.core - che-core-commons-lang - - - org.eclipse.che.selenium - che-selenium-core - - - org.everrest - everrest-core - - - org.seleniumhq.selenium - selenium-api - - - org.seleniumhq.selenium - selenium-remote-driver - - - commons-logging - commons-logging - - - - - org.seleniumhq.selenium - selenium-support - - - org.slf4j - slf4j-api - - - org.testng - testng - - - org.eclipse.che.multiuser - che-multiuser-api-organization - runtime - - - org.eclipse.che.multiuser - che-multiuser-api-permission - runtime - - - ch.qos.logback - logback-classic - test - - - org.eclipse.che.core - che-core-api-factory-shared - test - - - org.slf4j - jcl-over-slf4j - test - - - org.slf4j - jul-to-slf4j - test - - - org.slf4j - log4j-over-slf4j - test - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - - - - org.apache.maven.plugins - maven-site-plugin - - false - - - - com.mycila - license-maven-plugin - - - **/*.md - **/*.json - **/.gitkeep - **/.gitignore - **/*.cc - **/*.less - **/.keep - **/*.txt - **/*.zip - **/resources/**/another - **/resources/**/classpath - **/resources/**/editor - **/resources/**/errors-warnings - **/resources/**/expected-test-after-download-sources - **/resources/**/expected-test-before-download-sources - **/resources/**/file.less - **/resources/**/file - **/resources/**/hello.cc - **/resources/**/jar-module - **/resources/**/LessFile.less - **/resources/**/main - **/resources/**/Makefile - **/resources/**/new_file - **/resources/**/pom-quick-start-archetype-context - **/resources/**/README.md - **/resources/**/readme-txt - **/resources/**/replace-all - **/resources/**/replace - **/resources/**/some - **/resources/**/SomeLess.less - **/resources/**/tEst - **/resources/**/TeST - **/resources/**/TEST - **/resources/**/tesT - **/resources/**/TEst - **/resources/**/tESt - **/resources/**/Test - **/resources/**/test - **/resources/**/teSt - **/resources/**/TeSt - **/resources/**/text - **/resources/**/war-module - **/resources/**/README - **/resources/**/embed-code - - - - - - org.apache.maven.plugins - maven-resources-plugin - 3.0.2 - - false - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - integration-test - - - false - - classes - - - configfailurepolicy - continue - - - listener - org.eclipse.che.selenium.core.CheSeleniumTestHandler - - - - - java.util.logging.config.file - ${project.build.testOutputDirectory}/logging.properties - - - - ${excludedGroups} - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - generate-sources - - copy - - - ${project.build.testOutputDirectory}/projects/lib - - - log4j - log4j - ${log4j.version} - jar - - - org.mockito - mockito-core - ${org.mockito.version} - jar - - - - - - unpack-dependency - process-test-resources - - unpack-dependencies - - - org.eclipse.che.selenium - che-selenium-core - ${project.build.directory}/bin - webdriver.sh - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - add permissions - process-test-resources - - run - - - - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - **/logback-test.xml - - - - - - - - - - selenium-test - - false - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - integration-test - verify - - - - - - ${runSuite} - - - - - - - - diff --git a/tests/legacy-e2e/che-selenium-test/selenium-tests.sh b/tests/legacy-e2e/che-selenium-test/selenium-tests.sh deleted file mode 100755 index 114c7b91bd..0000000000 --- a/tests/legacy-e2e/che-selenium-test/selenium-tests.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/bash -# -# Copyright (c) 2012-2018 Red Hat, Inc. -# This program and the accompanying materials are made -# available under the terms of the Eclipse Public License 2.0 -# which is available at https://www.eclipse.org/legal/epl-2.0/ -# -# SPDX-License-Identifier: EPL-2.0 -# -# Contributors: -# Red Hat, Inc. - initial API and implementation -# -export CUR_DIR=$(cd "$(dirname "$0")"; pwd) -export CALLER=$(basename $0) - -cd $CUR_DIR - -TESTS_SCOPE="--suite=CheSuite.xml" -CLEAN_GOAL="clean" -for var in "$@"; do - if [[ "$var" =~ --test=.* ]] || [[ "$var" =~ --suite=.* ]]; then - TESTS_SCOPE= - break - fi - - if [[ "$var" == "--compare-with-ci" ]] \ - || [[ "$var" == "--failed-tests" ]] \ - || [[ "$var" == "--regression-tests" ]]; then - TESTS_SCOPE= - CLEAN_GOAL= - break - fi -done - -mvn $CLEAN_GOAL dependency:unpack-dependencies \ - -DincludeArtifactIds=che-selenium-core \ - -DincludeGroupIds=org.eclipse.che.selenium \ - -Dmdep.unpack.includes=webdriver.sh \ - -DoutputDirectory=${CUR_DIR}/target/bin -chmod +x target/bin/webdriver.sh - -(target/bin/webdriver.sh "$TESTS_SCOPE" $@) diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumDockerModule.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumDockerModule.java deleted file mode 100644 index 472e16be7f..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumDockerModule.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import com.google.inject.AbstractModule; -import org.eclipse.che.selenium.core.client.keycloak.cli.DockerKeycloakCliCommandExecutor; -import org.eclipse.che.selenium.core.client.keycloak.cli.KeycloakCliCommandExecutor; -import org.eclipse.che.selenium.core.workspace.CheTestDockerWorkspaceLogsReader; -import org.eclipse.che.selenium.core.workspace.TestWorkspaceLogsReader; - -/** @author Dmytro Nochevnov */ -public class CheSeleniumDockerModule extends AbstractModule { - - @Override - protected void configure() { - bind(TestWorkspaceLogsReader.class).to(CheTestDockerWorkspaceLogsReader.class); - bind(KeycloakCliCommandExecutor.class).to(DockerKeycloakCliCommandExecutor.class); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumMultiUserModule.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumMultiUserModule.java deleted file mode 100644 index 11c3ffcf04..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumMultiUserModule.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import com.google.inject.AbstractModule; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; -import com.google.inject.assistedinject.FactoryModuleBuilder; -import org.eclipse.che.selenium.core.client.CheTestDefaultOrganizationServiceClient; -import org.eclipse.che.selenium.core.client.CheTestMachineServiceClient; -import org.eclipse.che.selenium.core.client.TestMachineServiceClient; -import org.eclipse.che.selenium.core.client.TestOrganizationServiceClient; -import org.eclipse.che.selenium.core.client.TestOrganizationServiceClientFactory; -import org.eclipse.che.selenium.core.provider.AdminTestUserProvider; -import org.eclipse.che.selenium.core.provider.DefaultTestUserProvider; -import org.eclipse.che.selenium.core.provider.TestUserProvider; -import org.eclipse.che.selenium.core.user.AdminTestUser; -import org.eclipse.che.selenium.core.user.MultiUserCheAdminTestUserProvider; -import org.eclipse.che.selenium.core.user.MultiUserCheDefaultTestUserProvider; -import org.eclipse.che.selenium.core.user.MultiUserCheTestUserProvider; -import org.eclipse.che.selenium.core.user.TestUser; -import org.eclipse.che.selenium.core.user.TestUserFactory; -import org.eclipse.che.selenium.core.user.TestUserImpl; - -/** @author Anton Korneta */ -public class CheSeleniumMultiUserModule extends AbstractModule { - - @Override - protected void configure() { - bind(TestMachineServiceClient.class).to(CheTestMachineServiceClient.class); - - bind(DefaultTestUserProvider.class).to(MultiUserCheDefaultTestUserProvider.class); - - bind(TestUser.class).toProvider(TestUserProvider.class); - bind(TestUserProvider.class).to(MultiUserCheTestUserProvider.class); - - bind(AdminTestUser.class).toProvider(AdminTestUserProvider.class); - bind(AdminTestUserProvider.class).to(MultiUserCheAdminTestUserProvider.class); - - bind(TestOrganizationServiceClient.class).to(CheTestDefaultOrganizationServiceClient.class); - - install( - new FactoryModuleBuilder() - .build(Key.get(new TypeLiteral>() {}.getType()))); - - install( - new FactoryModuleBuilder() - .build(Key.get(new TypeLiteral>() {}.getType()))); - - install(new FactoryModuleBuilder().build(TestOrganizationServiceClientFactory.class)); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumOpenShiftModule.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumOpenShiftModule.java deleted file mode 100644 index 3dff159094..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumOpenShiftModule.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import com.google.inject.AbstractModule; -import org.eclipse.che.selenium.core.client.keycloak.cli.KeycloakCliCommandExecutor; -import org.eclipse.che.selenium.core.client.keycloak.cli.OpenShiftKeycloakCliCommandExecutor; -import org.eclipse.che.selenium.core.workspace.CheTestOpenshiftWorkspaceLogsReader; -import org.eclipse.che.selenium.core.workspace.TestWorkspaceLogsReader; - -public class CheSeleniumOpenShiftModule extends AbstractModule { - - @Override - protected void configure() { - bind(TestWorkspaceLogsReader.class).to(CheTestOpenshiftWorkspaceLogsReader.class); - bind(KeycloakCliCommandExecutor.class).to(OpenShiftKeycloakCliCommandExecutor.class); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumSingleUserModule.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumSingleUserModule.java deleted file mode 100644 index 25187d5e08..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumSingleUserModule.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import com.google.inject.AbstractModule; -import org.eclipse.che.selenium.core.client.CheTestAuthServiceClient; -import org.eclipse.che.selenium.core.client.DummyCheTestMachineServiceClient; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.client.TestMachineServiceClient; -import org.eclipse.che.selenium.core.provider.DefaultTestUserProvider; -import org.eclipse.che.selenium.core.user.SingleUserCheDefaultTestUserProvider; - -/** @author Anton Korneta */ -public class CheSeleniumSingleUserModule extends AbstractModule { - - @Override - protected void configure() { - bind(TestAuthServiceClient.class).to(CheTestAuthServiceClient.class); - bind(TestMachineServiceClient.class).to(DummyCheTestMachineServiceClient.class); - bind(DefaultTestUserProvider.class).to(SingleUserCheDefaultTestUserProvider.class); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumSuiteModule.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumSuiteModule.java deleted file mode 100644 index 4f406a0b57..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumSuiteModule.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import static com.google.inject.name.Names.named; -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.utils.PlatformUtils.isMac; -import static org.eclipse.che.selenium.core.workspace.WorkspaceTemplate.DEFAULT; - -import com.google.inject.AbstractModule; -import com.google.inject.Key; -import com.google.inject.Provides; -import com.google.inject.TypeLiteral; -import com.google.inject.assistedinject.FactoryModuleBuilder; -import com.google.inject.name.Named; -import java.io.IOException; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.selenium.core.action.ActionsFactory; -import org.eclipse.che.selenium.core.action.GenericActionsFactory; -import org.eclipse.che.selenium.core.action.MacOSActionsFactory; -import org.eclipse.che.selenium.core.client.CheTestUserServiceClient; -import org.eclipse.che.selenium.core.client.CheTestWorkspaceServiceClient; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.client.TestGitHubRepository; -import org.eclipse.che.selenium.core.client.TestUserServiceClient; -import org.eclipse.che.selenium.core.client.TestUserServiceClientFactory; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClient; -import org.eclipse.che.selenium.core.client.TestWorkspaceServiceClientFactory; -import org.eclipse.che.selenium.core.client.keycloak.KeycloakTestAuthServiceClient; -import org.eclipse.che.selenium.core.client.keycloak.OsioKeycloakTestAuthServiceClient; -import org.eclipse.che.selenium.core.configuration.SeleniumTestConfiguration; -import org.eclipse.che.selenium.core.configuration.TestConfiguration; -import org.eclipse.che.selenium.core.constant.Infrastructure; -import org.eclipse.che.selenium.core.pageobject.PageObjectsInjector; -import org.eclipse.che.selenium.core.provider.CheTestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.provider.CheTestDashboardUrlProvider; -import org.eclipse.che.selenium.core.provider.CheTestIdeUrlProvider; -import org.eclipse.che.selenium.core.provider.CheTestWorkspaceAgentApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.provider.DefaultTestUserProvider; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.provider.TestDashboardUrlProvider; -import org.eclipse.che.selenium.core.provider.TestIdeUrlProvider; -import org.eclipse.che.selenium.core.provider.TestWorkspaceAgentApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.CheTestDefaultHttpJsonRequestFactory; -import org.eclipse.che.selenium.core.requestfactory.TestUserHttpJsonRequestFactory; -import org.eclipse.che.selenium.core.requestfactory.TestUserHttpJsonRequestFactoryCreator; -import org.eclipse.che.selenium.core.user.DefaultTestUser; -import org.eclipse.che.selenium.core.user.TestUserFactory; -import org.eclipse.che.selenium.core.webdriver.log.WebDriverLogsReaderFactory; -import org.eclipse.che.selenium.core.workspace.CheTestWorkspaceProvider; -import org.eclipse.che.selenium.core.workspace.CheTestWorkspaceUrlResolver; -import org.eclipse.che.selenium.core.workspace.TestWorkspace; -import org.eclipse.che.selenium.core.workspace.TestWorkspaceProvider; -import org.eclipse.che.selenium.core.workspace.TestWorkspaceUrlResolver; -import org.eclipse.che.selenium.pageobject.PageObjectsInjectorImpl; - -/** - * Guice module per suite. - * - * @author Anatolii Bazko - * @author Dmytro Nochevnov - */ -public class CheSeleniumSuiteModule extends AbstractModule { - - public static final String AUXILIARY = "auxiliary"; - - private static final String CHE_MULTIUSER_VARIABLE = "che.multiuser"; - private static final String CHE_INFRASTRUCTURE_VARIABLE = "che.infrastructure"; - - @Override - public void configure() { - TestConfiguration config = new SeleniumTestConfiguration(); - config.getMap().forEach((key, value) -> bindConstant().annotatedWith(named(key)).to(value)); - - bind(DefaultTestUser.class).toProvider(DefaultTestUserProvider.class); - install( - new FactoryModuleBuilder() - .build(Key.get(new TypeLiteral>() {}.getType()))); - - bind(TestUserServiceClient.class).to(CheTestUserServiceClient.class); - - bind(HttpJsonRequestFactory.class).to(TestUserHttpJsonRequestFactory.class); - bind(TestUserHttpJsonRequestFactory.class).to(CheTestDefaultHttpJsonRequestFactory.class); - - bind(TestApiEndpointUrlProvider.class).to(CheTestApiEndpointUrlProvider.class); - bind(TestIdeUrlProvider.class).to(CheTestIdeUrlProvider.class); - bind(TestDashboardUrlProvider.class).to(CheTestDashboardUrlProvider.class); - bind(TestWorkspaceAgentApiEndpointUrlProvider.class) - .to(CheTestWorkspaceAgentApiEndpointUrlProvider.class); - - bind(TestWorkspaceUrlResolver.class).to(CheTestWorkspaceUrlResolver.class); - - install( - new FactoryModuleBuilder() - .implement(TestWorkspaceServiceClient.class, CheTestWorkspaceServiceClient.class) - .build(TestWorkspaceServiceClientFactory.class)); - - bind(TestWorkspaceServiceClient.class).to(CheTestWorkspaceServiceClient.class); - bind(TestWorkspaceProvider.class).to(CheTestWorkspaceProvider.class).asEagerSingleton(); - - install(new FactoryModuleBuilder().build(TestUserHttpJsonRequestFactoryCreator.class)); - install(new FactoryModuleBuilder().build(TestUserServiceClientFactory.class)); - install(new FactoryModuleBuilder().build(WebDriverLogsReaderFactory.class)); - - bind(PageObjectsInjector.class).to(PageObjectsInjectorImpl.class); - - configureInfrastructureRelatedDependencies(config); - - if (config.getBoolean(CHE_MULTIUSER_VARIABLE)) { - install(new CheSeleniumMultiUserModule()); - } else { - install(new CheSeleniumSingleUserModule()); - } - - install(new TestExecutionModule()); - } - - private void configureInfrastructureRelatedDependencies(TestConfiguration config) { - final Infrastructure cheInfrastructure = - Infrastructure.valueOf(config.getString(CHE_INFRASTRUCTURE_VARIABLE).toUpperCase()); - switch (cheInfrastructure) { - case OPENSHIFT: - case K8S: - if (config.getBoolean(CHE_MULTIUSER_VARIABLE)) { - bind(TestAuthServiceClient.class).to(KeycloakTestAuthServiceClient.class); - } - - install(new CheSeleniumOpenShiftModule()); - break; - - case OSIO: - if (config.getBoolean(CHE_MULTIUSER_VARIABLE)) { - bind(TestAuthServiceClient.class).to(OsioKeycloakTestAuthServiceClient.class); - } - - install(new CheSeleniumOpenShiftModule()); - break; - - case DOCKER: - if (config.getBoolean(CHE_MULTIUSER_VARIABLE)) { - bind(TestAuthServiceClient.class).to(KeycloakTestAuthServiceClient.class); - } - - install(new CheSeleniumDockerModule()); - break; - - default: - throw new RuntimeException( - format("Infrastructure '%s' hasn't been supported by tests.", cheInfrastructure)); - } - } - - @Provides - public TestWorkspace getWorkspace( - TestWorkspaceProvider workspaceProvider, - DefaultTestUser testUser, - @Named("workspace.default_memory_gb") int defaultMemoryGb) - throws Exception { - TestWorkspace ws = workspaceProvider.createWorkspace(testUser, defaultMemoryGb, DEFAULT, true); - ws.await(); - return ws; - } - - @Provides - public ActionsFactory getActionFactory() { - return isMac() ? new MacOSActionsFactory() : new GenericActionsFactory(); - } - - @Provides - @Named(AUXILIARY) - public TestGitHubRepository getTestGitHubRepository( - @Named("github.auxiliary.username") String gitHubAuxiliaryUsername, - @Named("github.auxiliary.password") String gitHubAuxiliaryPassword) - throws IOException, InterruptedException { - return new TestGitHubRepository(gitHubAuxiliaryUsername, gitHubAuxiliaryPassword); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumTestHandler.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumTestHandler.java deleted file mode 100644 index d9f3179cab..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumTestHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import com.google.inject.Module; -import java.util.ArrayList; -import java.util.List; -import org.eclipse.che.selenium.core.inject.SeleniumTestHandler; - -/** @author Anatolii Bazko */ -public class CheSeleniumTestHandler extends SeleniumTestHandler { - @Override - public List getParentModules() { - List modules = new ArrayList<>(); - modules.add(new CheSeleniumSuiteModule()); - return modules; - } - - @Override - public List getChildModules() { - List modules = new ArrayList<>(); - modules.add(new CheSeleniumWebDriverRelatedModule()); - return modules; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumWebDriverRelatedModule.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumWebDriverRelatedModule.java deleted file mode 100644 index 72ea311f9d..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/CheSeleniumWebDriverRelatedModule.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import com.google.inject.AbstractModule; -import com.google.inject.Provides; -import com.google.inject.name.Named; -import org.eclipse.che.selenium.core.entrance.CookieEntrance; -import org.eclipse.che.selenium.core.entrance.Entrance; -import org.eclipse.che.selenium.core.entrance.LoginPageEntrance; -import org.eclipse.che.selenium.pageobject.site.CheLoginPage; -import org.eclipse.che.selenium.pageobject.site.LoginPage; - -/** - * Module which is dedicated to deal with dependencies which are injecting SeleniumWebDriver.class - * itself. - * - * @author Dmytro Nochevnov - */ -public class CheSeleniumWebDriverRelatedModule extends AbstractModule { - - @Override - protected void configure() { - bind(LoginPage.class).to(CheLoginPage.class); - } - - @Provides - public Entrance getEntrance( - @Named("che.multiuser") boolean isMultiuser, - LoginPage loginPage, - SeleniumWebDriver seleniumWebDriver) { - if (isMultiuser) { - return new LoginPageEntrance(loginPage); - } else { - return new CookieEntrance(seleniumWebDriver); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/TestExecutionModule.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/TestExecutionModule.java deleted file mode 100644 index f351ca3de2..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/TestExecutionModule.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core; - -import com.google.inject.AbstractModule; -import org.eclipse.che.selenium.core.webdriver.DownloadedFileUtil; -import org.eclipse.che.selenium.core.webdriver.DownloadedIntoGridFileUtil; -import org.eclipse.che.selenium.core.webdriver.DownloadedLocallyFileUtil; -import org.eclipse.che.selenium.core.webdriver.UploadIntoGridUtil; -import org.eclipse.che.selenium.core.webdriver.UploadLocallyUtil; -import org.eclipse.che.selenium.core.webdriver.UploadUtil; - -public class TestExecutionModule extends AbstractModule { - - @Override - protected void configure() { - boolean gridMode = Boolean.valueOf(System.getProperty("grid.mode")); - if (gridMode) { - bind(DownloadedFileUtil.class).to(DownloadedIntoGridFileUtil.class); - bind(UploadUtil.class).to(UploadIntoGridUtil.class); - } else { - bind(DownloadedFileUtil.class).to(DownloadedLocallyFileUtil.class); - bind(UploadUtil.class).to(UploadLocallyUtil.class); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestAdminOrganizationServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestAdminOrganizationServiceClient.java deleted file mode 100644 index 341696343d..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestAdminOrganizationServiceClient.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.CheTestAdminHttpJsonRequestFactory; - -/** This util is handling the requests to Organization API as admin. */ -@Singleton -public class CheTestAdminOrganizationServiceClient extends TestOrganizationServiceClient { - - @Inject - public CheTestAdminOrganizationServiceClient( - TestApiEndpointUrlProvider apiEndpointUrlProvider, - CheTestAdminHttpJsonRequestFactory adminRequestFactory) { - super(apiEndpointUrlProvider, adminRequestFactory); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestAuthServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestAuthServiceClient.java deleted file mode 100644 index 7a313f78c6..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestAuthServiceClient.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.api.core.rest.DefaultHttpJsonRequestFactory; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** @author Anatolii Bazko */ -@Singleton -public class CheTestAuthServiceClient implements TestAuthServiceClient { - - private static final Logger LOG = LoggerFactory.getLogger(CheTestAuthServiceClient.class); - - private final String apiEndpoint; - private final HttpJsonRequestFactory requestFactory; - - @Inject - public CheTestAuthServiceClient( - String apiEndpoint, DefaultHttpJsonRequestFactory requestFactory) { - this.apiEndpoint = apiEndpoint; - this.requestFactory = requestFactory; - } - - @Override - public String login(String username, String password) throws Exception { - return username; - } - - @Override - public void logout(String authToken) { - try { - String apiUrl = apiEndpoint + "auth/logout?token=" + authToken; - requestFactory.fromUrl(apiUrl).usePostMethod().request(); - } catch (Exception e) { - LOG.error(e.getLocalizedMessage(), e); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestDefaultOrganizationServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestDefaultOrganizationServiceClient.java deleted file mode 100644 index 897776e2be..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestDefaultOrganizationServiceClient.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.CheTestDefaultHttpJsonRequestFactory; - -/** This util is handling the requests to Organization API as default user. */ -@Singleton -public class CheTestDefaultOrganizationServiceClient extends TestOrganizationServiceClient { - - @Inject - public CheTestDefaultOrganizationServiceClient( - TestApiEndpointUrlProvider apiEndpointUrlProvider, - CheTestDefaultHttpJsonRequestFactory defaultRequestFactory) { - super(apiEndpointUrlProvider, defaultRequestFactory); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestMachineServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestMachineServiceClient.java deleted file mode 100644 index 11a7562c96..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestMachineServiceClient.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.Inject; -import com.google.inject.Singleton; - -/** - * @author Musienko Maxim - * @author Dmytro Nochevnov - */ -@Singleton -public class CheTestMachineServiceClient implements TestMachineServiceClient { - - private final TestWorkspaceServiceClient testWorkspaceServiceClient; - - @Inject - public CheTestMachineServiceClient(TestWorkspaceServiceClient testWorkspaceServiceClient) { - this.testWorkspaceServiceClient = testWorkspaceServiceClient; - } - - /** - * Returns machine token for current workspace - * - * @param workspaceId the workspace id - * @return the machine token for current workspace - */ - @Override - public String getMachineApiToken(String workspaceId) throws Exception { - return testWorkspaceServiceClient.getById(workspaceId).getRuntime().getMachineToken(); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestSystemClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestSystemClient.java deleted file mode 100644 index 809210ce94..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/CheTestSystemClient.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import org.eclipse.che.api.system.shared.SystemStatus; -import org.eclipse.che.api.system.shared.dto.SystemStateDto; -import org.eclipse.che.commons.annotation.Nullable; -import org.eclipse.che.selenium.core.provider.CheTestApiEndpointUrlProvider; -import org.eclipse.che.selenium.core.requestfactory.CheTestAdminHttpJsonRequestFactory; -import org.eclipse.che.selenium.core.utils.WaitUtils; - -/** - * Client of workspace master system service. - * - * @author Musienko Maxim - * @author Nochevnov Dmytro - */ -@Singleton -public class CheTestSystemClient { - - @Inject CheTestApiEndpointUrlProvider cheTestApiEndpointUrlProvider; - - @Inject CheTestAdminHttpJsonRequestFactory testUserHttpJsonRequestFactory; - - /** - * Stops workspace master. Checks on next statuses flow: PREPARING_TO_SHUTDOWN, READY_TO_SHUTDOWN. - * - * @throws Exception - */ - public void stop() throws Exception { - int maxRequestAttempts = 30; - int requestTimeoutInSec = 1; - - String restUrlForSuspendingWorkspaces = - cheTestApiEndpointUrlProvider.get().toString() + "system/stop"; - - testUserHttpJsonRequestFactory - .fromUrl(restUrlForSuspendingWorkspaces) - .usePostMethod() - .request(); - - waitWorkspaceMasterStatus( - maxRequestAttempts, requestTimeoutInSec, SystemStatus.PREPARING_TO_SHUTDOWN); - - waitWorkspaceMasterStatus( - maxRequestAttempts, requestTimeoutInSec, SystemStatus.READY_TO_SHUTDOWN); - } - - /** - * Returns workspace master system state, or null if system is inaccessible (suspended). - */ - @Nullable - public SystemStatus getStatus() throws Exception { - String restUrlForGettingSuspendingStatus = - cheTestApiEndpointUrlProvider.get().toString() + "system/state"; - - try { - return testUserHttpJsonRequestFactory - .fromUrl(restUrlForGettingSuspendingStatus) - .useGetMethod() - .request() - .asDto(SystemStateDto.class) - .getStatus(); - } catch (IOException ex) { - return null; - } - } - - public void waitWorkspaceMasterStatus( - int readStatusAttempts, int readStatusTimeoutInSec, SystemStatus expectedStatus) - throws Exception { - int timeToReadStatus = readStatusAttempts * readStatusTimeoutInSec; - while (readStatusAttempts-- > 0) { - if (expectedStatus.equals(getStatus())) { - return; - } - - WaitUtils.sleepQuietly(readStatusTimeoutInSec); - } - - throw new IOException( - String.format( - "Workspace Master hasn't achieved status '%s' in '%s' seconds.", - expectedStatus, timeToReadStatus)); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/DummyCheTestMachineServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/DummyCheTestMachineServiceClient.java deleted file mode 100644 index 779e9af12f..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/DummyCheTestMachineServiceClient.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client; - -/** @author Anton Korneta */ -public class DummyCheTestMachineServiceClient implements TestMachineServiceClient { - - @Override - public String getMachineApiToken(String workspaceId) throws Exception { - return workspaceId; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/AbstractKeycloakTestAuthServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/AbstractKeycloakTestAuthServiceClient.java deleted file mode 100644 index e1b61192e7..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/AbstractKeycloakTestAuthServiceClient.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak; - -import static com.google.common.io.BaseEncoding.base64; -import static java.nio.charset.StandardCharsets.UTF_8; -import static java.time.LocalDateTime.now; -import static java.time.ZoneId.systemDefault; - -import com.google.gson.Gson; -import java.io.Reader; -import java.util.concurrent.ConcurrentHashMap; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.client.keycloak.KeycloakToken.TokenDetails; - -public abstract class AbstractKeycloakTestAuthServiceClient implements TestAuthServiceClient { - - private static final long MIN_TOKEN_LIFETIME_SEC = 30; - - private final Gson gson; - - protected final ConcurrentHashMap tokens; - - public AbstractKeycloakTestAuthServiceClient() { - this.tokens = new ConcurrentHashMap<>(); - this.gson = new Gson(); - } - - @Override - public String login(String username, String password) throws Exception { - final KeycloakToken token = tokens.get(username); - if (token != null) { - final long now = now().atZone(systemDefault()).toEpochSecond(); - if (token.getAccessDetails().getExpiresAt() - now < MIN_TOKEN_LIFETIME_SEC) { - if (!(token.getRefreshDetails().getExpiresAt() - now < MIN_TOKEN_LIFETIME_SEC)) { - final KeycloakToken refreshed = refreshRequest(token); - tokens.replace(username, refreshed); - return refreshed.getAccessToken(); - } - } else { - return token.getAccessToken(); - } - } - - KeycloakToken newToken = loginRequest(username, password); - - tokens.put(username, newToken); - return newToken.getAccessToken(); - } - - protected KeycloakToken readerToKeycloakToken(final Reader response) { - KeycloakToken token; - token = gson.fromJson(response, KeycloakToken.class); - token.setAccessDetails( - gson.fromJson( - new String(base64().decode(token.getAccessToken().split("\\.")[1]), UTF_8), - TokenDetails.class)); - token.setRefreshDetails( - gson.fromJson( - new String(base64().decode(token.getRefreshToken().split("\\.")[1]), UTF_8), - TokenDetails.class)); - return token; - } - - @Override - public abstract void logout(String token) throws Exception; - - protected abstract KeycloakToken loginRequest(String username, String password); - - protected abstract KeycloakToken refreshRequest(KeycloakToken token); -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakSettings.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakSettings.java deleted file mode 100644 index 49fb2a76f1..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakSettings.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak; - -import com.google.gson.annotations.SerializedName; - -/** @author Anton Korneta */ -public class KeycloakSettings { - @SerializedName("che.keycloak.token.endpoint") - private String keycloakTokenEndpoint; - - @SerializedName("che.keycloak.profile.endpoint") - private String keycloakProfileEndpoint; - - @SerializedName("che.keycloak.auth_server_url") - private String keycloakAuthServerUrl; - - @SerializedName("che.keycloak.password.endpoint") - private String keycloakPasswordEndpoint; - - @SerializedName("che.keycloak.logout.endpoint") - private String keycloakLogoutEndpoint; - - @SerializedName("che.keycloak.realm") - private String keycloakRealm; - - @SerializedName("che.keycloak.client_id") - private String keycloakClientId; - - public String getKeycloakTokenEndpoint() { - return keycloakTokenEndpoint; - } - - public String getKeycloakProfileEndpoint() { - return keycloakProfileEndpoint; - } - - public String getKeycloakAuthServerUrl() { - return keycloakAuthServerUrl; - } - - public String getKeycloakPasswordEndpoint() { - return keycloakPasswordEndpoint; - } - - public String getKeycloakLogoutEndpoint() { - return keycloakLogoutEndpoint; - } - - public String getKeycloakRealm() { - return keycloakRealm; - } - - public String getKeycloakClientId() { - return keycloakClientId; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakTestAuthServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakTestAuthServiceClient.java deleted file mode 100644 index 6f65465c4d..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakTestAuthServiceClient.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static javax.ws.rs.HttpMethod.POST; - -import com.google.common.collect.ImmutableList; -import com.google.gson.JsonSyntaxException; -import com.google.inject.Inject; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.List; -import javax.inject.Singleton; -import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.rest.DefaultHttpJsonRequestFactory; -import org.eclipse.che.commons.lang.IoUtil; -import org.eclipse.che.commons.lang.Pair; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Mykhailo Kuznietsov - * @author Anton Korneta - */ -@Singleton -public class KeycloakTestAuthServiceClient extends AbstractKeycloakTestAuthServiceClient { - - private static final Logger LOG = LoggerFactory.getLogger(KeycloakTestAuthServiceClient.class); - - private static final String CONTENT_TYPE = "Content-Type"; - private static final String FORM_MIME_TYPE = "application/x-www-form-urlencoded"; - private static final String GRANT_TYPE = "grant_type"; - private static final String CLIENT_ID_PARAM = "client_id"; - private static final String PASSWORD = "password"; - private static final String REFRESH_TOKEN = "refresh_token"; - - private final DefaultHttpJsonRequestFactory requestFactory; - - private final KeycloakSettings keycloakSettings; - - @Inject - public KeycloakTestAuthServiceClient( - DefaultHttpJsonRequestFactory requestFactory, - TestKeycloakSettingsServiceClient testKeycloakSettingsServiceClient) { - super(); - this.requestFactory = requestFactory; - this.keycloakSettings = testKeycloakSettingsServiceClient.read(); - } - - @Override - public void logout(String authToken) { - try { - requestFactory.fromUrl(keycloakSettings.getKeycloakLogoutEndpoint()).request(); - } catch (ApiException | IOException ex) { - LOG.error(ex.getLocalizedMessage(), ex); - } - } - - @Override - protected KeycloakToken loginRequest(String username, String password) { - return requestToken( - PASSWORD, ImmutableList.of(Pair.of("username", username), Pair.of("password", password))); - } - - @Override - protected KeycloakToken refreshRequest(KeycloakToken prevToken) { - return requestToken( - REFRESH_TOKEN, ImmutableList.of(Pair.of("refresh_token", prevToken.getRefreshToken()))); - } - - private KeycloakToken requestToken(String grandType, List> params) { - KeycloakToken token = null; - HttpURLConnection http = null; - final String keycloakTokenEndpoint = keycloakSettings.getKeycloakTokenEndpoint(); - if (keycloakTokenEndpoint == null) { - throw new RuntimeException("Keycloak token endpoint is not configured"); - } - try { - - http = (HttpURLConnection) new URL(keycloakTokenEndpoint).openConnection(); - http.setRequestMethod(POST); - http.setAllowUserInteraction(false); - http.setRequestProperty(CONTENT_TYPE, FORM_MIME_TYPE); - http.setInstanceFollowRedirects(true); - http.setDoOutput(true); - OutputStream output = http.getOutputStream(); - StringBuilder sb = new StringBuilder(); - sb.append(GRANT_TYPE) - .append('=') - .append(grandType) - .append('&') - .append(CLIENT_ID_PARAM) - .append('=') - .append(keycloakSettings.getKeycloakClientId()); - for (Pair param : params) { - sb.append('&').append(param.first).append('=').append(param.second); - } - output.write(sb.toString().getBytes(UTF_8)); - if (http.getResponseCode() != 200) { - throw new RuntimeException( - "Cannot get access token using the KeyCloak REST API. Server response code: " - + keycloakTokenEndpoint - + " " - + http.getResponseCode() - + IoUtil.readStream(http.getErrorStream())); - } - output.close(); - - final BufferedReader response = - new BufferedReader(new InputStreamReader(http.getInputStream(), UTF_8)); - - token = readerToKeycloakToken(response); - - } catch (IOException | JsonSyntaxException ex) { - LOG.error(ex.getMessage(), ex); - } finally { - if (http != null) { - http.disconnect(); - } - } - return token; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakToken.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakToken.java deleted file mode 100644 index a5ed364996..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakToken.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak; - -import com.google.gson.annotations.SerializedName; - -/** @author Mihail Kuznyetsov */ -public class KeycloakToken { - @SerializedName("access_token") - private String accessToken; - - @SerializedName("expires_in") - private long expiresIn; - - @SerializedName("refresh_token") - private String refreshToken; - - private TokenDetails accessDetails; - private TokenDetails refreshDetails; - - public KeycloakToken() {} - - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public long getExpiresIn() { - return expiresIn; - } - - public void setExpiresIn(long expiresIn) { - this.expiresIn = expiresIn; - } - - public String getRefreshToken() { - return refreshToken; - } - - public void setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - } - - public TokenDetails getAccessDetails() { - return accessDetails; - } - - public void setAccessDetails(TokenDetails accessDetails) { - this.accessDetails = accessDetails; - } - - public TokenDetails getRefreshDetails() { - return refreshDetails; - } - - public void setRefreshDetails(TokenDetails refreshDetails) { - this.refreshDetails = refreshDetails; - } - - static class TokenDetails { - @SerializedName("exp") - private long expiresAt; - - @SerializedName("iat") - private long initialized; - - public long getExpiresAt() { - return expiresAt; - } - - public void setExpiresAt(long expiresAt) { - this.expiresAt = expiresAt; - } - - public long getInitialized() { - return initialized; - } - - public void setInitialized(long initialized) { - this.initialized = initialized; - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakTokenContainer.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakTokenContainer.java deleted file mode 100644 index c908c8b2d7..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/KeycloakTokenContainer.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak; - -import com.google.gson.annotations.SerializedName; - -/** @author Dmytro Nochevnov */ -public class KeycloakTokenContainer { - @SerializedName("token") - private KeycloakToken token; - - public KeycloakTokenContainer() {} - - public KeycloakToken getToken() { - return token; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/OsioKeycloakTestAuthServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/OsioKeycloakTestAuthServiceClient.java deleted file mode 100644 index 723b309cae..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/OsioKeycloakTestAuthServiceClient.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.net.CookieHandler; -import java.net.CookieManager; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; -import java.util.StringJoiner; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.ws.rs.HttpMethod; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.eclipse.che.commons.lang.IoUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class for obtaining active token from OSIO using login/pass credentials. As fabric8-auth service - * does not have REST endpoint for login, the logic for obtaining active token is not so simple: - * - *

    1) Access /api/login?redirect=che.openshift.io (the redirect URL doesn't - * matter). This redirects us to redhat developer portal login page. 2) Parse that page - obtain - * `action` attribute of the login form 3) Send login request to URL obtained in step 2) and follow - * redirects until `token_json` appears in redirect URL. - * - * @author rhopp - */ -@Singleton -public class OsioKeycloakTestAuthServiceClient extends AbstractKeycloakTestAuthServiceClient { - - private static final Logger LOG = - LoggerFactory.getLogger(OsioKeycloakTestAuthServiceClient.class); - private static final String REFRESH_TOKEN_TEMPLATE = "{\"refresh_token\":\"%s\"}"; - - private final String osioAuthEndpoint; - - @Inject - public OsioKeycloakTestAuthServiceClient(@Named("che.osio.auth.endpoint") String authEndpoint) { - super(); - this.osioAuthEndpoint = authEndpoint; - } - - private KeycloakToken obtainActiveToken(String username, String password) - throws IOException, MalformedURLException, ProtocolException, UnsupportedEncodingException { - HttpURLConnection.setFollowRedirects(true); - HttpURLConnection conn; - String formPostURL = loginAndGetFormPostURL(); - - HttpURLConnection.setFollowRedirects(false); - - conn = fillFormAndCreateConnection(formPostURL, username, password); - - String tokenJsonString = followRedirects(conn); - - // "token_json={}" - String tokenJson = - URLDecoder.decode(new URL(tokenJsonString).getQuery(), "UTF-8").substring(11); - KeycloakToken readerToKeycloakToken = readerToKeycloakToken(new StringReader(tokenJson)); - return readerToKeycloakToken; - } - - @Override - public void logout(String token) throws Exception { - // NOT SUPPORTED ON OSIO - } - - @Override - protected KeycloakToken loginRequest(String username, String password) { - try { - return obtainActiveToken(username, password); - } catch (IOException e) { - throw new RuntimeException("Unable to obtain active token", e); - } - } - - @Override - protected KeycloakToken refreshRequest(KeycloakToken token) { - KeycloakToken newToken = null; - HttpURLConnection http = null; - try { - http = (HttpURLConnection) new URL(osioAuthEndpoint + "/api/token/refresh").openConnection(); - http.setRequestMethod(HttpMethod.POST); - http.setAllowUserInteraction(false); - http.setInstanceFollowRedirects(true); - http.setRequestProperty("Content-Type", "application/json"); - http.setDoOutput(true); - OutputStream output = http.getOutputStream(); - output.write(String.format(REFRESH_TOKEN_TEMPLATE, token.getRefreshToken()).getBytes(UTF_8)); - output.close(); - if (http.getResponseCode() != 200) { - throw new RuntimeException( - "Cannot get access token using the KeyCloak REST API. Server response code: " - + osioAuthEndpoint - + " " - + http.getResponseCode() - + IoUtil.readStream(http.getErrorStream())); - } - - // request was ok. Obtain token from inputStream. Response is in format - // {"token":{"active_token":"", ...}} Need to get rid of the root "token" element. - - final BufferedReader response = - new BufferedReader(new InputStreamReader(http.getInputStream(), UTF_8)); - String responseString = IOUtils.toString(response); - JsonParser parser = new JsonParser(); - JsonObject parse = parser.parse(responseString).getAsJsonObject(); - JsonElement jsonElement = parse.get("token"); - - newToken = readerToKeycloakToken(new StringReader(jsonElement.toString())); - - } catch (IOException e) { - LOG.error(e.getMessage(), e); - } finally { - if (http != null) { - http.disconnect(); - } - } - - return newToken; - } - - private HttpURLConnection fillFormAndCreateConnection( - String formPostURL, String username, String password) - throws IOException, MalformedURLException, ProtocolException, UnsupportedEncodingException { - HttpURLConnection conn; - conn = (HttpURLConnection) new URL(formPostURL).openConnection(); - conn.setRequestMethod("POST"); - conn.setDoOutput(true); - - Map arguments = new HashMap<>(); - arguments.put("username", username); - arguments.put("password", password); - arguments.put("login", "Log+In"); - StringJoiner sj = new StringJoiner("&"); - for (Map.Entry entry : arguments.entrySet()) - sj.add( - URLEncoder.encode(entry.getKey(), "UTF-8") - + "=" - + URLEncoder.encode(entry.getValue(), "UTF-8")); - byte[] out = sj.toString().getBytes(UTF_8); - try (OutputStream os = conn.getOutputStream()) { - os.write(out); - } - return conn; - } - - private String followRedirects(URLConnection conn) throws IOException { - int responseCode = ((HttpURLConnection) conn).getResponseCode(); - if (responseCode > 300 && responseCode < 309) { - String location = conn.getHeaderField("Location"); - if (location.contains("token_json")) { - return location; - } else { - return followRedirects(new URL(location).openConnection()); - } - } else { - throw new RuntimeException("Unable to obtain active token."); - } - } - - private String loginAndGetFormPostURL() - throws IOException, MalformedURLException, ProtocolException { - CookieManager cookieManager = new CookieManager(); - CookieHandler.setDefault(cookieManager); - HttpURLConnection conn = - (HttpURLConnection) - new URL(osioAuthEndpoint + "/api/login?redirect=https://che.openshift.io") - .openConnection(); - conn.setRequestMethod("GET"); - - String htmlOutput = IOUtils.toString(conn.getInputStream()); - Pattern p = Pattern.compile("action=\"(.*?)\""); - Matcher m = p.matcher(htmlOutput); - if (m.find()) { - String formPostURL = StringEscapeUtils.unescapeHtml(m.group(1)); - return formPostURL; - } else { - LOG.error("Unable to login - didn't find URL to send login form to."); - throw new RuntimeException("Unable to login - didn't find URL to send login form to."); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/TestKeycloakSettingsServiceClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/TestKeycloakSettingsServiceClient.java deleted file mode 100644 index 07104524af..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/TestKeycloakSettingsServiceClient.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak; - -import static java.lang.String.format; - -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; -import com.google.inject.Inject; -import java.io.IOException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import org.eclipse.che.api.core.ApiException; -import org.eclipse.che.api.core.rest.DefaultHttpJsonRequestFactory; -import org.eclipse.che.selenium.core.provider.TestApiEndpointUrlProvider; - -/** @author Dmytro Nochevnov */ -public class TestKeycloakSettingsServiceClient { - - private final String keycloakSettingsServiceUrl; - private final DefaultHttpJsonRequestFactory requestFactory; - private final Gson gson; - - @Inject - public TestKeycloakSettingsServiceClient( - TestApiEndpointUrlProvider cheApiEndpointProvider, - DefaultHttpJsonRequestFactory requestFactory, - Gson gson) { - this.keycloakSettingsServiceUrl = format("%skeycloak/settings/", cheApiEndpointProvider.get()); - this.requestFactory = requestFactory; - this.gson = gson; - } - - public KeycloakSettings read() { - try { - trustAllTlsCertificates(); - - return gson.fromJson( - requestFactory.fromUrl(keycloakSettingsServiceUrl).useGetMethod().request().asString(), - KeycloakSettings.class); - } catch (ApiException - | IOException - | JsonSyntaxException - | NoSuchAlgorithmException - | KeyManagementException ex) { - throw new RuntimeException("Error during retrieving Che Keycloak configuration: ", ex); - } - } - - /** - * Trust all TLS certificates to be able to test Eclipse Che with self-signed TLS certificate - * support - * - * @throws NoSuchAlgorithmException - * @throws KeyManagementException - */ - private void trustAllTlsCertificates() throws NoSuchAlgorithmException, KeyManagementException { - TrustManager[] trustAllCerts = - new TrustManager[] { - new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return null; - } - - public void checkClientTrusted(X509Certificate[] certs, String authType) {} - - public void checkServerTrusted(X509Certificate[] certs, String authType) {} - } - }; - - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); - HostnameVerifier allHostsVerifier = (arg0, arg1) -> true; - HttpsURLConnection.setDefaultHostnameVerifier(allHostsVerifier); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/DockerKeycloakCliCommandExecutor.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/DockerKeycloakCliCommandExecutor.java deleted file mode 100644 index 09e481e788..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/DockerKeycloakCliCommandExecutor.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak.cli; - -import static java.lang.String.format; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import org.eclipse.che.selenium.core.executor.DockerCliCommandExecutor; -import org.eclipse.che.selenium.core.utils.process.ProcessAgent; -import org.eclipse.che.selenium.core.utils.process.ProcessAgentException; - -/** - * This class is aimed to call Keycloak CLI commands inside Docker container. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class DockerKeycloakCliCommandExecutor implements KeycloakCliCommandExecutor { - @Inject private DockerCliCommandExecutor dockerCliCommandExecutor; - - @Inject private ProcessAgent processAgent; - - private String keycloakContainerId; - - @Override - public String execute(String command) throws IOException { - if (keycloakContainerId == null || keycloakContainerId.trim().isEmpty()) { - obtainKeycloakContainerId(); - } - - String dockerKeycloakCliCommand = - format("exec -i %s sh -c 'keycloak/bin/kcadm.sh %s'", keycloakContainerId, command); - return dockerCliCommandExecutor.execute(dockerKeycloakCliCommand); - } - - private void obtainKeycloakContainerId() throws ProcessAgentException { - // obtain id of keycloak docker container - keycloakContainerId = - processAgent.process("echo $(docker ps | grep che_keycloak | cut -d ' ' -f1)"); - - if (keycloakContainerId.trim().isEmpty()) { - throw new RuntimeException( - "Keycloak container is not found. Make sure that correct value is set for `CHE_INFRASTRUCTURE`, and product to test is run locally"); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/KeycloakCliClient.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/KeycloakCliClient.java deleted file mode 100644 index 1e97ccec26..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/KeycloakCliClient.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak.cli; - -import static java.lang.String.format; - -import com.google.inject.Inject; -import java.io.IOException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.inject.Singleton; -import org.eclipse.che.selenium.core.client.keycloak.KeycloakSettings; -import org.eclipse.che.selenium.core.client.keycloak.TestKeycloakSettingsServiceClient; -import org.eclipse.che.selenium.core.provider.AdminTestUserProvider; -import org.eclipse.che.selenium.core.provider.RemovableUserProvider; -import org.eclipse.che.selenium.core.user.AdminTestUser; -import org.eclipse.che.selenium.core.user.DefaultTestUser; -import org.eclipse.che.selenium.core.user.TestUser; -import org.eclipse.che.selenium.core.user.TestUserFactory; -import org.eclipse.che.selenium.core.user.TestUserImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This is java-client of 'keycloak/bin/kcadm.sh' command line application - * - * @author Dmytro Nochevnov - */ -@Singleton -public class KeycloakCliClient { - private static final Logger LOG = LoggerFactory.getLogger(KeycloakCliClient.class); - private static final Pattern EXTRACT_USER_ID_PATTERN = - Pattern.compile("^.*Created new user with id '(.*)'.*$", Pattern.DOTALL); - - // we need to inject AdminTestUser separately to avoid circular dependency error - @Inject private AdminTestUserProvider adminTestUserProvider; - - private final TestUserFactory defaultTestUserFactory; - private final TestUserFactory testUserFactory; - private final KeycloakSettings keycloakSettings; - - @Inject private KeycloakCliCommandExecutor executor; - - @Inject - public KeycloakCliClient( - TestUserFactory testUserFactory, - TestUserFactory defaultTestUserFactory, - TestKeycloakSettingsServiceClient testKeycloakSettingsServiceClient) { - this.testUserFactory = testUserFactory; - this.defaultTestUserFactory = defaultTestUserFactory; - this.keycloakSettings = testKeycloakSettingsServiceClient.read(); - } - - public TestUserImpl createUser(RemovableUserProvider testUserProvider) throws IOException { - long currentTimeInMillisec = System.currentTimeMillis(); - String username = "user" + currentTimeInMillisec; - String email = username + "@1.com"; - String password = String.valueOf(currentTimeInMillisec); - - String userId = doCreateUser(username, email, password); - - LOG.info("Test user with name='{}' and id='{}' has been created.", username, userId); - - return testUserFactory.create(username, email, password, testUserProvider); - } - - public DefaultTestUser createDefaultUser(RemovableUserProvider testUserProvider) - throws IOException { - long currentTimeInMillisec = System.currentTimeMillis(); - String username = "user" + currentTimeInMillisec; - String email = username + "@1.com"; - String password = String.valueOf(currentTimeInMillisec); - - String userId = doCreateUser(username, email, password); - - LOG.info("Default test user with name='{}' and id='{}' has been created.", username, userId); - - return defaultTestUserFactory.create(username, email, password, testUserProvider); - } - - private String doCreateUser(String username, String email, String password) throws IOException { - String authPartOfCommand = - format( - "--no-config --server http://0.0.0.0:8080/auth --user %s --password %s --realm master", - adminTestUserProvider.get().getName(), adminTestUserProvider.get().getPassword()); - - String createUserCommand = - format( - "create users -r %s -s username=%s -s enabled=true %s 2>&1", - getCheKeycloakRealm(), username, authPartOfCommand); - String response = executor.execute(createUserCommand); - if (!response.contains("Created new user with id ")) { - throw new IOException("Test user creation error: " + response); - } - - String userId = extractUserId(response); - - String setTestUsersPermanentPasswordCommand = - format( - "set-password -r %s --username %s --new-password %s %s 2>&1", - getCheKeycloakRealm(), username, password, authPartOfCommand); - executor.execute(setTestUsersPermanentPasswordCommand); - - String setEmailCommand = - format( - "update users/%s -r %s --set email=%s %s 2>&1", - userId, getCheKeycloakRealm(), email, authPartOfCommand); - executor.execute(setEmailCommand); - - String addReadTokenRoleToUserCommand = - format( - "add-roles -r %s --uusername %s --cclientid broker --rolename read-token %s 2>&1", - getCheKeycloakRealm(), username, authPartOfCommand); - executor.execute(addReadTokenRoleToUserCommand); - - return userId; - } - - /** Adds role "read-token" of client "broker" to admin user */ - public void setupAdmin(AdminTestUser adminTestUser) { - String authPartOfCommand = - format( - "--no-config --server http://0.0.0.0:8080/auth --user %s --password %s --realm master", - adminTestUser.getName(), adminTestUser.getPassword()); - - String addReadTokenRoleToUserCommand = - format( - "add-roles -r %s --uusername %s --cclientid broker --rolename read-token %s 2>&1", - getCheKeycloakRealm(), adminTestUser.getName(), authPartOfCommand); - - try { - executor.execute(addReadTokenRoleToUserCommand); - } catch (IOException e) { - // ignore error of adding role to admin because of it can be added before - } - } - - public void delete(TestUser testUser) throws IOException { - delete(testUser.getId(), testUser.getName()); - } - - private String extractUserId(String response) { - Matcher matcher = EXTRACT_USER_ID_PATTERN.matcher(response); - - if (matcher.find()) { - return matcher.group(1); - } - - throw new RuntimeException( - String.format("User id wasn't found in create user response '%s'.", response)); - } - - private void delete(String userId, String username) throws IOException { - String commandToDeleteUser = - format( - "delete users/%s -r %s -s username=%s --no-config --server http://0.0.0.0:8080/auth --user %s --password %s --realm master 2>&1", - userId, - getCheKeycloakRealm(), - username, - adminTestUserProvider.get().getName(), - adminTestUserProvider.get().getPassword()); - - executor.execute(commandToDeleteUser); - - LOG.info("Test user with name='{}' has been removed.", username); - } - - private String getCheKeycloakRealm() { - return keycloakSettings.getKeycloakRealm(); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/KeycloakCliCommandExecutor.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/KeycloakCliCommandExecutor.java deleted file mode 100644 index 2a81d38a91..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/KeycloakCliCommandExecutor.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak.cli; - -import org.eclipse.che.selenium.core.utils.executor.CommandExecutor; - -/** - * Execute commands of Keycloak CLI application. - * - * @author Dmytro Nochevnov - */ -public interface KeycloakCliCommandExecutor extends CommandExecutor {} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/OpenShiftKeycloakCliCommandExecutor.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/OpenShiftKeycloakCliCommandExecutor.java deleted file mode 100644 index 151e205e83..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/client/keycloak/cli/OpenShiftKeycloakCliCommandExecutor.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.client.keycloak.cli; - -import static java.lang.String.format; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.io.IOException; -import org.eclipse.che.selenium.core.executor.OpenShiftCliCommandExecutor; - -/** - * This class is aimed to call Keycloak CLI commands inside OpenShift pod. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class OpenShiftKeycloakCliCommandExecutor implements KeycloakCliCommandExecutor { - private static final String DEFAULT_CHE_OPENSHIFT_PROJECT = "che"; - private static final String DEFAULT_KEYCLOAK_APP = "keycloak"; - private static final String DEFAULT_INTERNAL_PATH_TO_KEYCLOAK_CLI = - "/opt/jboss/keycloak/bin/kcadm.sh"; - - private String keycloakPodName; - - @Inject private OpenShiftCliCommandExecutor openShiftCliCommandExecutor; - - @Inject(optional = true) - @Named("che.openshift.project") - private String cheOpenshiftProject; - - @Inject(optional = true) - @Named("env.keycloak.openshift.app") - private String keycloakApp; - - @Inject(optional = true) - @Named("env.keycloak.cli.internal.path") - private String internalPathToKeycloakCli; - - @Override - public String execute(String command) throws IOException { - if (keycloakPodName == null || keycloakPodName.trim().isEmpty()) { - obtainKeycloakPodName(); - } - - String openShiftKeycloakCliCommand = - format( - "exec %s -- %s %s", - keycloakPodName, - internalPathToKeycloakCli != null - ? internalPathToKeycloakCli - : DEFAULT_INTERNAL_PATH_TO_KEYCLOAK_CLI, - command); - - return openShiftCliCommandExecutor.execute(openShiftKeycloakCliCommand); - } - - private void obtainKeycloakPodName() throws IOException { - // obtain name of keycloak pod - String getKeycloakPodNameCommand = - format( - "get pods --namespace=%s | grep keycloak | awk '{print $1}'", - cheOpenshiftProject != null ? cheOpenshiftProject : DEFAULT_CHE_OPENSHIFT_PROJECT); - - keycloakPodName = openShiftCliCommandExecutor.execute(getKeycloakPodNameCommand); - - if (keycloakPodName.trim().isEmpty()) { - String errorMessage = - format( - "Keycloak pod is not found at project %s at OpenShift instance.", - cheOpenshiftProject != null ? cheOpenshiftProject : DEFAULT_CHE_OPENSHIFT_PROJECT); - - throw new RuntimeException(errorMessage); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestBuildConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestBuildConstants.java deleted file mode 100644 index 3803d3345d..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestBuildConstants.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** Introduce text constants related to build project process */ -public class TestBuildConstants { - public static final String BUILD_SUCCESS = "BUILD SUCCESS"; - public static final String BUILD_FAILED = "[INFO] BUILD FAILURE"; - public static final String SERVER_STARTUP_IN = "Server startup in"; - public static final String LISTENING_AT_ADDRESS = "Listening for transport dt_socket at address"; - public static final String LISTENING_AT_ADDRESS_8000 = LISTENING_AT_ADDRESS + ": 8000"; -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestCommandsConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestCommandsConstants.java deleted file mode 100644 index b7ced3cf27..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestCommandsConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** @author Anatolii Bazko */ -public interface TestCommandsConstants { - String CUSTOM = "custom"; - String MAVEN = "mvn"; - String GWT = "gwt"; - String RUN_COMMAND = "run"; - String BUILD_COMMAND = "build"; - String CLEAN_BUILD_COMMAND = "clean build"; - String DEBUG_COMMAND = "debug"; - String BUILD_AND_RUN_COMMAND = "build and run"; - String STOP_TOMCAT_COMMAND = "stop tomcat"; - String RUN_TOMCAT_COMMAND = "run tomcat"; - String INSTALL_DEPENDENCIES_COMMAND = "install dependencies"; - String UPDATE_DEPENDENCIES_COMMAND = "update dependencies"; - String START_APACHE_COMMAND = "start apache"; - String STOP_APACHE_COMMAND = "stop apache"; - String RESTART_APACHE_COMMAND = "restart apache"; -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestGitConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestGitConstants.java deleted file mode 100644 index 7053a40838..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestGitConstants.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** @author Anatolii Bazko */ -public final class TestGitConstants { - public static final String GIT_ADD_TO_INDEX_SUCCESS = "Git index updated"; - public static final String GIT_NOTHING_TO_ADD = - "Selected item does not have any unstaged changes"; - public static final String GIT_REMOVE_FROM_INDEX_SUCCESS = "Files removed from index"; - public static final String GIT_INITIALIZED_SUCCESS = "Repository initialized"; - public static final String GIT_REPO_DELETE = "Git repository deleted"; - public static final String COMMIT_MESSAGE_SUCCESS = "Committed with revision"; - public static final String CONFIGURING_PROJECT_AND_CLONING_SOURCE_CODE = - "Configuring project and cloning source code."; -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestGoalsConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestGoalsConstants.java deleted file mode 100644 index 1004338566..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestGoalsConstants.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** @author Anatolii Bazko */ -public interface TestGoalsConstants { - String RUN = "Run"; - String BUILD = "Build"; - String DEBUG = "Debug"; - String TEST = "Test"; - String COMMON = "Common"; -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestIntelligentCommandsConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestIntelligentCommandsConstants.java deleted file mode 100644 index 0c073dc416..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestIntelligentCommandsConstants.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -import static java.lang.String.format; - -/** */ -public final class TestIntelligentCommandsConstants { - - private TestIntelligentCommandsConstants() { - // this prevents class instance creation - throw new AssertionError(); - } - - public enum CommandItem { - RUN_COMMAND_ITEM("%s:run"), - GRADLE_RUN_COMMAND_ITEM("%s:gradle run"), - BUILD_COMMAND_ITEM("%s:build"), - MAVEN_BUILD_COMMAND_ITEM("%s:maven build"), - BUILD_AND_RUN_COMMAND_ITEM("%s:build and run"), - MAVEN_BUILD_AND_RUN_COMMAND_ITEM("%s:maven build and run"), - BUILD_AND_DEPLOY_COMMAND_ITEM("%s:build and deploy"), - STOP_TOMCAT_COMMAND_ITEM("%s:stop tomcat"), - RUN_TOMCAT_COMMAND_ITEM("%s:run tomcat"), - DEBUG_COMMAND_ITEM("%s:debug"), - INSTALL_DEPENDENCIES_COMMAND_ITEM("%s:install dependencies"), - UPDATE_DEPENDENCIES_COMMAND_ITEM("%s:update dependencies"); - - private final String itemTemplate; - - CommandItem(String itemTemplate) { - this.itemTemplate = itemTemplate; - } - - public String getItem(String projectName) { - return format(itemTemplate, projectName); - } - } - - public static class CommandsGoals { - - private CommandsGoals() {} - - public static final String COMMON_GOAL = "Common"; - public static final String DEPLOY_GOAL = "Deploy"; - public static final String DEBUG_GOAL = "Debug"; - public static final String RUN_GOAL = "Run"; - public static final String TEST_GOAL = "Test"; - public static final String BUILD_GOAL = "Build"; - public static final String NEW_COMMAND_GOAL = "New Command Goal..."; - } - - public static class CommandsTypes { - - private CommandsTypes() {} - - public static final String GWT_TYPE = "GWT"; - public static final String GWT_SDM_FOR_CHE_TYPE = "GWT SDM for Che"; - public static final String CUSTOM_TYPE = "Custom"; - public static final String JAVA_TYPE = "Java"; - public static final String MAVEN_TYPE = "Maven"; - } - - public static class CommandsDefaultNames { - - private CommandsDefaultNames() {} - - public static final String GWT_NAME = "newGWT"; - public static final String JAVA_NAME = "newJava"; - public static final String MAVEN_NAME = "newMaven"; - public static final String CUSTOM_NAME = "newCustom"; - public static final String GWT_SDM_FOR_CHE = "newGWT SDM for Che"; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestMenuCommandsConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestMenuCommandsConstants.java deleted file mode 100644 index 67fb63395b..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestMenuCommandsConstants.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** @author Musienko Maxim */ -public interface TestMenuCommandsConstants { - - interface Workspace { - String WORKSPACE_MENU_PREFIX = "gwt-debug-topmenu/Workspace/"; - String WORKSPACE = "gwt-debug-MenuItem/workspaceGroup-true"; - String IMPORT_PROJECT = WORKSPACE_MENU_PREFIX + "importProject"; - String CREATE_PROJECT = WORKSPACE_MENU_PREFIX + "createProject"; - String STOP_WORKSPACE = WORKSPACE_MENU_PREFIX + "stopWorkspace"; - String CREATE_FACTORY = WORKSPACE_MENU_PREFIX + "configureFactoryAction"; - String STOP = WORKSPACE_MENU_PREFIX + "stopWorkspace"; - String DOWNLOAD_AS_ZIP = WORKSPACE_MENU_PREFIX + "downloadWsAsZipAction"; - } - - interface Project { - String PROJECT = "gwt-debug-MenuItem/projectGroup-true"; - String PROJECT_MENU_PREFIX = "gwt-debug-topmenu/Project/"; - String UPLOAD_FILE = PROJECT_MENU_PREFIX + "uploadFile"; - String UPLOAD_FOLDER = PROJECT_MENU_PREFIX + "uploadFolder"; - String CONVERT_TO_PROJECT = PROJECT_MENU_PREFIX + "convertFolderToProject"; - String CONFIGURATION = PROJECT_MENU_PREFIX + "projectConfiguration"; - String CONFIGURE_CLASSPATH = PROJECT_MENU_PREFIX + "projectProperties"; - String SHOW_HIDE_HIDDEN_FILES = PROJECT_MENU_PREFIX + "showHideHiddenFiles"; - String UPDATE_PROJECT_CONFIGURATION = PROJECT_MENU_PREFIX + "projectConfiguration"; - String DOWNLOAD_AS_ZIP = PROJECT_MENU_PREFIX + "downloadAsZipAction"; - - interface New { - String NEW = PROJECT_MENU_PREFIX + "newGroup"; - String JAVA_CLASS = PROJECT_MENU_PREFIX + "New/newJavaClass"; - String PACKAGE = PROJECT_MENU_PREFIX + "New/newJavaPackage"; - String MAVEN_MODULE = PROJECT_MENU_PREFIX + "New/createMavenModule"; - String FILE = PROJECT_MENU_PREFIX + "New/newFile"; - String FOLDER = PROJECT_MENU_PREFIX + "New/newFolder"; - String HTML_FILE = PROJECT_MENU_PREFIX + "New/newHtmlFile"; - String CSS_FILE = PROJECT_MENU_PREFIX + "New/newCssFile"; - String XML_FILE = PROJECT_MENU_PREFIX + "New/newXmlFile"; - String LESS_FILE = PROJECT_MENU_PREFIX + "New/newLessFile"; - String JAVASCRIPT_FILE = PROJECT_MENU_PREFIX + "New/newJavaScriptFile"; - } - } - - interface Edit { - String EDIT_MENU_PREFIX = "gwt-debug-topmenu/Edit/"; - String EDIT = "gwt-debug-MenuItem/editGroup-true"; - String RECENT = EDIT_MENU_PREFIX + "recentFiles"; - String FORMAT = EDIT_MENU_PREFIX + "format"; - String UNDO = EDIT_MENU_PREFIX + "undo"; - String REDO = EDIT_MENU_PREFIX + "redo"; - String CUT = EDIT_MENU_PREFIX + "cut"; - String COPY = EDIT_MENU_PREFIX + "copy"; - String PASTE = EDIT_MENU_PREFIX + "paste"; - String RENAME = EDIT_MENU_PREFIX + "renameResource"; - String DELETE = EDIT_MENU_PREFIX + "deleteItem"; - String FIND = EDIT_MENU_PREFIX + "fullTextSearch"; - String OPEN_RECENT_FILE = EDIT_MENU_PREFIX + "openRecentFiles"; - - interface Recent { - String CLEAR_LIST = EDIT_MENU_PREFIX + "Recent/clearRecentList"; - } - } - - interface Assistant { - String ASSISTANT_MENU_PREFIX = "gwt-debug-topmenu/Assistant/"; - String ASSISTANT = "gwt-debug-MenuItem/assistantGroup-true"; - String FIND_ACTION = ASSISTANT_MENU_PREFIX + "findAction"; - String KEY_BINDINGS = ASSISTANT_MENU_PREFIX + "hotKeysList"; - String NAVIGATE_TO_FILE = ASSISTANT_MENU_PREFIX + "navigateToFile"; - String QUICK_DOCUMENTATION = ASSISTANT_MENU_PREFIX + "showQuickDoc"; - String OPEN_DECLARATION = ASSISTANT_MENU_PREFIX + "openJavaDeclaration"; - String IMPLEMENTATION_S = ASSISTANT_MENU_PREFIX + "openImplementation"; - String FILE_STRUCTURE = ASSISTANT_MENU_PREFIX + "javaClassStructure"; - String FIND_USAGES = ASSISTANT_MENU_PREFIX + "javaFindUsages"; - String UPDATE_DEPENDENCIES = ASSISTANT_MENU_PREFIX + "updateDependency"; - String ORGANIZE_IMPORTS = ASSISTANT_MENU_PREFIX + "organizeImports"; - String GENERATE_EFFECTIVE_POM = ASSISTANT_MENU_PREFIX + "getEffectivePom"; - String QUICK_FIX = ASSISTANT_MENU_PREFIX + "quickFix"; - String FIND_DEFINITION = ASSISTANT_MENU_PREFIX + "LSFindDefinitionAction"; - String FIND_REFERENCES = ASSISTANT_MENU_PREFIX + "LSFindReferencesAction"; - String GO_TO_SYMBOL = ASSISTANT_MENU_PREFIX + "LSGoToSymbolAction"; - String FIND_PROJECT_SYMBOL = ASSISTANT_MENU_PREFIX + "LSFindSymbolAction"; - - interface ToolWindows { - String TOOL_WINDOWS = ASSISTANT_MENU_PREFIX + "toolWindows"; - String CONTRIBUTE_TOOL_WIDOWS = - ASSISTANT_MENU_PREFIX + "Tool Windows/contributePartDisplayingMode"; - } - - interface Refactoring { - String REFACTORING = ASSISTANT_MENU_PREFIX + "assistantRefactoringGroup"; - String MOVE = ASSISTANT_MENU_PREFIX + "Refactoring/javaMoveRefactoring"; - String RENAME = ASSISTANT_MENU_PREFIX + "Refactoring/javaRenameRefactoring"; - String LS_RENAME = ASSISTANT_MENU_PREFIX + "Refactoring/LS.rename"; - } - } - - interface Run { - String TERMINAL = "gwt-debug-topmenu/Run/newTerminal"; - String EDIT_COMMANDS = "gwt-debug-topmenu/Run/editCommands"; - String RUN_MENU = "gwt-debug-MenuItem/runGroup-true"; - String EDIT_DEBUG_CONFIGURATION = "gwt-debug-topmenu/Run/editDebugConfigurations"; - String DEBUG = "gwt-debug-topmenu/Run/Debug"; - String DEBUG_CONFIGURATION = "gwt-debug-topmenu/Run/Debug Configurations"; - String END_DEBUG_SESSION = "gwt-debug-topmenu/Run/disconnectDebug"; - String TEST = "gwt-debug-topmenu/Run/TestingMainGroup"; - } - - interface Profile { - String PROFILE_PREFIX = "gwt-debug-topmenu/Profile/"; - String PROFILE_MENU = "gwt-debug-MenuItem/profileGroup-true"; - String ACCOUNT = PROFILE_PREFIX + "redirectToDashboardAccount"; - String PROJECTS = PROFILE_PREFIX + "redirectToDashboardProjectsAction"; - String WORKSPACES = PROFILE_PREFIX + "redirectToDashboardWorkspacesAction"; - String PREFERENCES = PROFILE_PREFIX + "showPreferences"; - } - - interface Git { - - String GIT_MENU_PREFFIX = "gwt-debug-topmenu/Git/"; - String GIT = "gwt-debug-MenuItem/git-true"; - String ADD_TO_INDEX = GIT_MENU_PREFFIX + "gitAddToIndex"; - String RESET = GIT_MENU_PREFFIX + "gitResetToCommit"; - String REMOVE_FROM_INDEX = GIT_MENU_PREFFIX + "gitRemoveFromIndexCommit"; - String COMMIT = GIT_MENU_PREFFIX + "gitCommit"; - String BRANCHES = GIT_MENU_PREFFIX + "gitBranches"; - String CHECKOUT_REFERENCE = GIT_MENU_PREFFIX + "gitCheckoutReference"; - String MERGE = GIT_MENU_PREFFIX + "gitMerge"; - String RESET_INDEX = GIT_MENU_PREFFIX + "gitResetFiles"; - String SHOW_HISTORY = GIT_MENU_PREFFIX + "gitHistory"; - String STATUS = GIT_MENU_PREFFIX + "gitStatus"; - String PROJECT_GIT_URL = GIT_MENU_PREFFIX + "gitUrl"; - String INITIALIZE_REPOSITORY = GIT_MENU_PREFFIX + "gitInitRepository"; - String DELETE_REPOSITORY = GIT_MENU_PREFFIX + "gitDeleteRepository"; - String REVERT_COMMIT = GIT_MENU_PREFFIX + "gitRevertCommit"; - - interface Remotes { - String REMOTES_TOP = "gwt-debug-topmenu/Git/gitRemoteGroup"; - String FETCH = "gwt-debug-topmenu/Git/Remotes.../gitFetch"; - String PULL = "gwt-debug-topmenu/Git/Remotes.../gitPull"; - String PUSH = "gwt-debug-topmenu/Git/Remotes.../gitPush"; - String REMOTES = "gwt-debug-topmenu/Git/Remotes.../gitRemote"; - } - - interface Compare { - String COMPARE_TOP = "gwt-debug-topmenu/Git/gitCompareGroup"; - String COMPARE_LATEST_VER = "gwt-debug-topmenu/Git/Compare/gitCompareWithLatest"; - String COMPARE_WITH_BRANCH = "gwt-debug-topmenu/Git/Compare/gitCompareWithBranch"; - String COMPARE_WITH_REVISION = "gwt-debug-topmenu/Git/Compare/gitCompareWithRevision"; - } - } - - interface Help { - String HELP = "gwt-debug-MenuItem/helpGroup-true"; - String SETTINGS = "gwt-debug-topmenu/Help/setupProjectAction"; - String SUPPORT = "gwt-debug-topmenu/Help/redirectToSupport"; - String ABOUT = "gwt-debug-topmenu/Help/showAbout"; - } - - interface Machine { - String MACHINE = "gwt-debug-MenuItem/machine-true"; - String CREATE = "topmenu/Machine/Create..."; - String RESTART = "gwt-debug-topmenu/Machine/restartMachine"; - String DESTROY = "gwt-debug-topmenu/Machine/destroyMachine"; - String CREATE_SNAPSHOT = "gwt-debug-topmenu/Machine/createSnapshot"; - } - - interface CommandList { - String WS_MACHINE_LIST = "gwt-debug-dropDownHeader"; - String ITEM_PREFFIX_ID = "gwt-debug-CommandsGroup/"; - String COMMAND_LIST_XPATH = "//div[@id='gwt-debug-dropDownHeader'][2]"; - } - - String TEST_NG_TEST_DROP_DAWN_ITEM = "topmenu/Run/Test/Run Test"; - String JUNIT_TEST_DROP_DAWN_ITEM = "gwt-debug-topmenu/Run/Test/TestJUnitActionRun"; - - String TEST_DROP_DAWN_ITEM = "gwt-debug-topmenu/Run/Test/RunTest"; -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestProjectExplorerContextMenuConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestProjectExplorerContextMenuConstants.java deleted file mode 100644 index b757fb379a..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestProjectExplorerContextMenuConstants.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** */ -public final class TestProjectExplorerContextMenuConstants { - - public interface ContextMenuItems { - String get(); - } - - /** First level of project explorer's context menu items */ - public enum ContextMenuFirstLevelItems implements ContextMenuItems { - NEW("gwt-debug-contextMenu/newGroup"), - COMMANDS("gwt-debug-contextMenu/commandsActionGroup"), - PREVIEW("gwt-debug-contextMenu/previewHTML"), - SHOW_REFERENCES("gwt-debug-contextMenu/showReference"), - GO_INTO("gwt-debug-contextMenu/goInto"), - GO_BACK("gwt-debug-contextMenu/goInto"), - OPEN_IN_TERMINAL("gwt-debug-contextMenu/openInTerminal"), - OPEN_ON_GITHUB("gwt-debug-contextMenu/openOnGitHub"), - CUT("gwt-debug-contextMenu/cut"), - COPY("gwt-debug-contextMenu/copy"), - PASTE("gwt-debug-contextMenu/paste"), - RENAME("gwt-debug-contextMenu/renameResource"), - DELETE("gwt-debug-contextMenu/deleteItem"), - DOWNLOAD("gwt-debug-contextMenu/downloadItemAction"), - CONVERT_TO_PROJECT("gwt-debug-contextMenu/convertFolderToProject"), - BUILD_PATH("gwt-debug-contextMenu/markDirectoryAsSourceGroup"), - EDIT("gwt-debug-contextMenu/editFile"), - MAVEN("gwt-debug-contextMenu/mavenGroupContextMenu"), - REFRESH("gwt-debug-contextMenu/refreshPathAction"), - REIMPORT("gwt-debug-contextMenu/Maven/reimportMavenDependenciesAction"), - TEST("gwt-debug-contextMenu/TestingContextGroup"), - ADD_TO_FILE_WATCHER_EXCLUDES("gwt-debug-contextMenu/Add to File Watcher exclusion list"), - REMOVE_FROM_FILE_WATCHER_EXCLUDES( - "gwt-debug-contextMenu/Remove from File Watcher exclusion list"); - - private final String itemId; - - ContextMenuFirstLevelItems(String itemId) { - this.itemId = itemId; - } - - @Override - public String get() { - return this.itemId; - } - } - - /** Submenu for "new" project explorer context menu items */ - public enum SubMenuNew implements ContextMenuItems { - JAVA_CLASS("gwt-debug-contextMenu/New/newJavaClass"), - JAVA_PACKAGE("gwt-debug-contextMenu/New/newJavaPackage"), - FILE("gwt-debug-contextMenu/New/newFile"), - FOLDER("gwt-debug-contextMenu/New/newFolder"), - XML_FILE("gwt-debug-contextMenu/New/newXmlFile"), - CSS_FILE("gwt-debug-contextMenu/New/newCssFile"), - LESS_FILE("gwt-debug-contextMenu/New/newLessFile"), - HTML_FILE("gwt-debug-contextMenu/New/newHtmlFile"), - JAVASCRIPT_FILE("gwt-debug-contextMenu/New/newJavaScriptFile"), - PYTHON_FILE("gwt-debug-contextMenu/New/pythonFile"), - C_FILE("gwt-debug-contextMenu/New/newCFile"), - C_PLUS_PLUS_FILE("gwt-debug-contextMenu/New/newCppFile"), - H_FILE("gwt-debug-contextMenu/New/newHFile"); - - private final String itemId; - - SubMenuNew(String itemId) { - this.itemId = itemId; - } - - @Override - public String get() { - return this.itemId; - } - } - - /** Submenu for (uses for Java project only) */ - public enum SubMenuBuildPath implements ContextMenuItems { - USE_AS_SOURCE_FOLDER("gwt-debug-contextMenu/Build Path/markDirectoryAsSource"), - UNMARK_AS_SOURCE_FOLDER("gwt-debug-contextMenu/Build Path/unmarkDirectoryAsSource"), - CONFIGURE_CLASSPATH("gwt-debug-contextMenu/Build Path/projectProperties"); - - private final String itemId; - - SubMenuBuildPath(String itemId) { - this.itemId = itemId; - } - - @Override - public String get() { - return this.itemId; - } - } - - /** Submenu for {@link ContextMenuFirstLevelItems#TEST} */ - public enum SubMenuTest implements ContextMenuItems { - TEST_NG_CLASS("contextMenu/Run Test/TestNG Class"), - TEST_NG_PROJECT("topmenu/Run/Test/TestNG Project"), - TEST_NG_XML_SUITE("topmenu/Run/Test/TestNG XML Suite"), - JUNIT_CLASS("contextMenu/Run Test/JUnit Class"), - JUNIT_PROJECT("topmenu/Run/Test/JUnit Project"); - - private final String itemId; - - SubMenuTest(String itemId) { - this.itemId = itemId; - } - - @Override - public String get() { - return this.itemId; - } - } - - /** Submenu for {@link ContextMenuFirstLevelItems#COMMANDS} */ - public enum ContextMenuCommandGoals implements ContextMenuItems { - COMMON_GOAL("gwt-debug-contextMenu/Commands/goal_Common"), - BUILD_GOAL("gwt-debug-contextMenu/Commands/goal_Build"), - RUN_GOAL("gwt-debug-contextMenu/Commands/goal_Run"), - DEBUG_GOAL("gwt-debug-contextMenu/Commands/goal_Debug"); - - private final String itemId; - - ContextMenuCommandGoals(String itemId) { - this.itemId = itemId; - } - - @Override - public String get() { - return itemId; - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestToolbarPanelConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestToolbarPanelConstants.java deleted file mode 100644 index ba70c1a35d..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestToolbarPanelConstants.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** @author Musienko Maxim */ -public interface TestToolbarPanelConstants { - interface Actions { - String DELETE = "gwt-debug-ActionButton/deleteItem-true"; - } - - interface MachineDropDown { - String COMMAND_DROPDAWN_XPATH = "//div[@id='gwt-debug-dropDownHeader'][position()='1']"; - String DEV_MACHINE = "gwt-debug-MachinesGroup/dev-machine"; - String DB_MACHINE = "gwt-debug-MachinesGroup/db"; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestWorkspaceConstants.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestWorkspaceConstants.java deleted file mode 100644 index 6e674f28bd..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/constant/TestWorkspaceConstants.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.constant; - -/** Constants related to workspace lifecycle */ -public final class TestWorkspaceConstants { - public static final String RUNNING_WORKSPACE_MESS = "Workspace is running"; -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/entrance/CookieEntrance.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/entrance/CookieEntrance.java deleted file mode 100644 index 1f2c63f970..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/entrance/CookieEntrance.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.entrance; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.user.TestUser; -import org.openqa.selenium.Cookie; - -/** - * Enter the product by adding "session-access-key=[auth_token]" to the cookie of web driver. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class CookieEntrance implements Entrance { - - private final SeleniumWebDriver seleniumWebDriver; - - @Inject - public CookieEntrance(SeleniumWebDriver seleniumWebDriver) { - this.seleniumWebDriver = seleniumWebDriver; - } - - /** - * Login to product by using cookies. - * - * @param user - */ - @Override - public void login(TestUser user) { - Cookie accessKey = new Cookie("session-access-key", user.obtainAuthToken()); - seleniumWebDriver.manage().addCookie(accessKey); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/entrance/LoginPageEntrance.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/entrance/LoginPageEntrance.java deleted file mode 100644 index 6f19a27596..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/entrance/LoginPageEntrance.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.entrance; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.user.TestUser; -import org.eclipse.che.selenium.pageobject.site.LoginPage; - -/** - * Enter the product through the Login Page. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class LoginPageEntrance implements Entrance { - - private final LoginPage loginPage; - - @Inject - public LoginPageEntrance(LoginPage loginPage) { - this.loginPage = loginPage; - } - - /** - * Login to product. - * - * @param user - */ - @Override - public void login(TestUser user) { - if (loginPage.isOpened()) { - loginPage.login(user.getName(), user.getPassword()); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/DockerCliCommandExecutor.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/DockerCliCommandExecutor.java deleted file mode 100644 index d9454e1057..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/DockerCliCommandExecutor.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.executor; - -import static java.lang.String.format; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import org.eclipse.che.selenium.core.utils.executor.CommandExecutor; -import org.eclipse.che.selenium.core.utils.process.ProcessAgent; - -/** - * This class is aimed to call Docker CLI command. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class DockerCliCommandExecutor implements CommandExecutor { - - private final ProcessAgent processAgent; - - @Inject - public DockerCliCommandExecutor(ProcessAgent processAgent) { - this.processAgent = processAgent; - } - - @Override - public String execute(String command) throws IOException { - String dockerCommand = format("docker %s", command); - return processAgent.process(dockerCommand); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/OpenShiftCliCommandExecutor.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/OpenShiftCliCommandExecutor.java deleted file mode 100644 index 68a486684d..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/OpenShiftCliCommandExecutor.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.executor; - -import static java.lang.String.format; -import static java.lang.System.getProperty; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.concurrent.locks.ReentrantLock; -import org.apache.commons.io.FileUtils; -import org.eclipse.che.selenium.core.provider.OpenShiftWebConsoleUrlProvider; -import org.eclipse.che.selenium.core.utils.executor.CommandExecutor; -import org.eclipse.che.selenium.core.utils.process.ProcessAgent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is aimed to call OpenShift CLI command. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class OpenShiftCliCommandExecutor implements CommandExecutor { - private static final Logger LOG = LoggerFactory.getLogger(OpenShiftCliCommandExecutor.class); - - private static final boolean IS_MAC_OS = getProperty("os.name").toLowerCase().startsWith("mac"); - private static final String DEFAULT_OPENSHIFT_USERNAME = "developer"; - private static final String DEFAULT_OPENSHIFT_PASSWORD = "any"; - private boolean isLoggedIn; - private ReentrantLock loginLock = new ReentrantLock(); - - private static final Path PATH_TO_OPENSHIFT_CLI_DIRECTORY = - Paths.get(getProperty("java.io.tmpdir")); - - private static final Path PATH_TO_OPENSHIFT_CLI = PATH_TO_OPENSHIFT_CLI_DIRECTORY.resolve("oc"); - - @Inject private ProcessAgent processAgent; - - @Inject(optional = true) - @Named("env.openshift.username") - private String openShiftUsername; - - @Inject(optional = true) - @Named("env.openshift.password") - private String openShiftPassword; - - @Inject(optional = true) - @Named("env.openshift.token") - private String openShiftToken; - - @Inject(optional = true) - @Named("che.openshift.project") - private String cheProjectName; - - @Inject private OpenShiftWebConsoleUrlProvider openShiftWebConsoleUrlProvider; - - @Override - public String execute(String command) throws IOException { - return execute(command, true); - } - - private String execute(String command, boolean needToLogin) throws IOException { - if (!PATH_TO_OPENSHIFT_CLI.toFile().exists()) { - downloadOpenShiftCli(); - } - - if (needToLogin && !isLoggedIn) { - loginLock.lock(); - try { - login(); - isLoggedIn = true; - } catch (IOException e) { - isLoggedIn = false; - throw e; - } finally { - loginLock.unlock(); - } - } - - String projectArgument = cheProjectName != null ? "-n " + cheProjectName : ""; - String openShiftCliCommand = - format("%s %s %s", PATH_TO_OPENSHIFT_CLI, projectArgument, command); - - return processAgent.process(openShiftCliCommand); - } - - /** Logs into OpensShift as a regular user */ - private void login() throws IOException { - String loginToOpenShiftCliCommand; - if (openShiftToken != null) { - loginToOpenShiftCliCommand = - format( - "login --server=%s --token=%s --insecure-skip-tls-verify", - openShiftWebConsoleUrlProvider.get(), openShiftToken); - } else { - loginToOpenShiftCliCommand = - format( - "login --server=%s -u=%s -p=%s --insecure-skip-tls-verify", - openShiftWebConsoleUrlProvider.get(), - openShiftUsername != null ? openShiftUsername : DEFAULT_OPENSHIFT_USERNAME, - openShiftPassword != null ? openShiftPassword : DEFAULT_OPENSHIFT_PASSWORD); - } - - execute(loginToOpenShiftCliCommand, false); - } - - private void downloadOpenShiftCli() throws IOException { - if (Files.notExists(PATH_TO_OPENSHIFT_CLI_DIRECTORY)) { - Files.createDirectory(PATH_TO_OPENSHIFT_CLI_DIRECTORY); - } - - URL url; - File packagePath; - String commandToUnpackOpenShiftCli; - if (IS_MAC_OS) { - url = - new URL( - "https://github.com/openshift/origin/releases/download/v3.9.0/openshift-origin-client-tools-v3.9.0-191fece-mac.zip"); - packagePath = - PATH_TO_OPENSHIFT_CLI_DIRECTORY.resolve("openshift-origin-client-tools.zip").toFile(); - commandToUnpackOpenShiftCli = - format("unzip -d %s %s", PATH_TO_OPENSHIFT_CLI_DIRECTORY, packagePath); - } else { - url = - new URL( - "https://github.com/openshift/origin/releases/download/v3.9.0/openshift-origin-client-tools-v3.9.0-191fece-linux-64bit.tar.gz"); - packagePath = - PATH_TO_OPENSHIFT_CLI_DIRECTORY.resolve("openshift-origin-client-tools.tar.gz").toFile(); - commandToUnpackOpenShiftCli = - format("tar --strip 1 -xzf %s -C %s", packagePath, PATH_TO_OPENSHIFT_CLI_DIRECTORY); - } - - LOG.info("Downloading OpenShift CLI from {} ...", url); - FileUtils.copyURLToFile(url, packagePath); - LOG.info("OpenShift CLI has been downloaded."); - - processAgent.process(commandToUnpackOpenShiftCli); - - FileUtils.deleteQuietly(packagePath); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/hotupdate/HotUpdateUtil.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/hotupdate/HotUpdateUtil.java deleted file mode 100644 index 2d487028d4..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/executor/hotupdate/HotUpdateUtil.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.executor.hotupdate; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.stream.Collectors; -import org.eclipse.che.selenium.core.client.TestUserPreferencesServiceClient; -import org.eclipse.che.selenium.core.executor.OpenShiftCliCommandExecutor; -import org.eclipse.che.selenium.core.utils.WaitUtils; - -/** - * This is a set of methods which make easier to do updating of the che pod and wait of the updating - * results. - * - * @author Ihor Okhrimenko - */ -@Singleton -public class HotUpdateUtil { - private static final int TIMEOUT_FOR_FINISH_UPDATE_IN_SECONDS = 600; - private static final int DELAY_BETWEEN_ATTEMPTS_IN_MILLISECS = 5000; - private static final String PODS_LIST_COMMAND = "get pods | awk 'NR > 1 {print $1}'"; - private static final String COMMAND_TO_GET_REVISION_OF_CHE_DEPLOYMENT = - "get dc che | awk 'NR==2{print $2}'"; - private static final String COMMAND_TO_GET_NAME_OF_CHE_DEPLOYMENT = - "get dc che | awk 'NR==2{print $1}'"; - private static final String UPDATE_COMMAND_TEMPLATE = - "patch deployment che -p \"{\\\"spec\\\": {\\\"template\\\": {\\\"spec\\\":{\\\"terminationGracePeriodSeconds\\\":%s}}}}\""; - private static final String COMMAND_TO_GET_CURRENT_TERMINATION_GRACE_PERIOD = - "get deployments/che -o jsonpath={..terminationGracePeriodSeconds}"; - private static final String COMMAND_TO_GET_ROLLOUT_STATUS = "rollout status deployment/che"; - protected final OpenShiftCliCommandExecutor openShiftCliCommandExecutor; - protected final TestUserPreferencesServiceClient testUserPreferencesServiceClient; - - @Inject - public HotUpdateUtil( - OpenShiftCliCommandExecutor openShiftCliCommandExecutor, - TestUserPreferencesServiceClient testUserPreferencesServiceClient) { - - this.openShiftCliCommandExecutor = openShiftCliCommandExecutor; - this.testUserPreferencesServiceClient = testUserPreferencesServiceClient; - } - - /** - * Waits during {@code timeoutInSec} until update is finished by checking that only single master - * pod is present and it has incremented {@code masterVersionBeforeUpdate} number in name. - * - * @param masterRevisionBeforeUpdate - revision of the master pod before updating. - * @param timeoutInSec - waiting time in seconds. - */ - public void waitFullMasterPodUpdate(int masterRevisionBeforeUpdate, int timeoutInSec) - throws TimeoutException, InterruptedException, ExecutionException { - final int numberOfUpdatedVersion = masterRevisionBeforeUpdate + 1; - final String beforeUpdatePodNamePattern = "che-" + masterRevisionBeforeUpdate; - final String updatedPodNamePattern = "che-" + numberOfUpdatedVersion; - - waitPodNameDisappearance(beforeUpdatePodNamePattern, timeoutInSec); - - waitPodNamePatternHasSingleOccurrence(updatedPodNamePattern, timeoutInSec); - } - - /** - * Waits until update is finished by checking that only single master pod is present and it has - * incremented {@code masterVersionBeforeUpdate} number in name. - * - * @param masterRevisionBeforeUpdate - revision of the master pod before updating. - * @throws Exception - */ - public void waitFullMasterPodUpdate(int masterRevisionBeforeUpdate) throws Exception { - waitFullMasterPodUpdate(masterRevisionBeforeUpdate, TIMEOUT_FOR_FINISH_UPDATE_IN_SECONDS); - } - - /** - * Performs CLI request to the master pod for current Rollout status - * - * @return rollout status of CHE - */ - public String getRolloutStatus() { - try { - return openShiftCliCommandExecutor.execute(COMMAND_TO_GET_ROLLOUT_STATUS); - } catch (IOException ex) { - throw new RuntimeException(ex.getLocalizedMessage(), ex); - } - } - - /** - * Waits during {@code timeoutInSec} until master pod has a specified {@code expectedRevision}. - * - * @param expectedRevision revision of the master pod. - * @param timeoutInSec - waiting time in seconds. - */ - public void waitMasterPodRevision(int expectedRevision, int timeoutInSec) - throws TimeoutException, InterruptedException, ExecutionException { - WaitUtils.waitSuccessCondition(() -> expectedRevision == getMasterPodRevision(), timeoutInSec); - } - - /** - * Waits until master pod has a specified {@code expectedRevision}. - * - * @param expectedRevision master pod revision. - */ - public void waitMasterPodRevision(int expectedRevision) - throws TimeoutException, InterruptedException, ExecutionException { - waitMasterPodRevision(expectedRevision, TIMEOUT_FOR_FINISH_UPDATE_IN_SECONDS); - } - - /** - * Performs CLI command for master pod updating. - * - * @throws Exception - */ - public void executeMasterPodUpdateCommand() throws Exception { - int currentTerminationGracePeriod = getCurrentTerminationGracePeriod() + 1; - String updateCommand = String.format(UPDATE_COMMAND_TEMPLATE, currentTerminationGracePeriod); - openShiftCliCommandExecutor.execute(updateCommand); - } - - /** Performs GET request to master pod API for checking its availability. */ - public void checkMasterPodAvailabilityByPreferencesRequest() { - try { - testUserPreferencesServiceClient.getPreferences(); - } catch (Exception ex) { - throw new RuntimeException("Master POD is not available", ex); - } - } - - /** - * Performs CLI request to the master pod for getting its revision. - * - * @return revision of the master pod. - */ - public int getMasterPodRevision() { - try { - return Integer.parseInt( - openShiftCliCommandExecutor.execute(COMMAND_TO_GET_REVISION_OF_CHE_DEPLOYMENT)); - } catch (IOException ex) { - throw new RuntimeException(ex.getLocalizedMessage(), ex); - } - } - - /** - * Performs CLI request to the master pod for getting its termination grace period. - * - * @return current termination grace period - */ - public int getCurrentTerminationGracePeriod() { - try { - return Integer.parseInt( - openShiftCliCommandExecutor.execute(COMMAND_TO_GET_CURRENT_TERMINATION_GRACE_PERIOD)); - } catch (IOException ex) { - throw new RuntimeException(ex.getLocalizedMessage(), ex); - } - } - - /** - * Performs CLI request to the master pod to get its name. - * - * @return name of Che master pod. - */ - public String getMasterPodName() { - try { - return openShiftCliCommandExecutor.execute(COMMAND_TO_GET_NAME_OF_CHE_DEPLOYMENT); - } catch (IOException ex) { - throw new RuntimeException(ex.getLocalizedMessage(), ex); - } - } - - private List getPods() throws Exception { - return Arrays.asList(openShiftCliCommandExecutor.execute(PODS_LIST_COMMAND).split("\n")); - } - - private boolean isAnyPodNameHasPatternOccurrence(String pattern) throws Exception { - return !getPodsNamesWithPatternOccurrence(pattern).isEmpty(); - } - - private List getPodsNamesWithPatternOccurrence(String pattern) throws Exception { - return getPods() - .stream() - .filter(podName -> podName.contains(pattern)) - .collect(Collectors.toList()); - } - - private void waitPodNameDisappearance(String podName, int timeout) - throws TimeoutException, InterruptedException, ExecutionException { - WaitUtils.waitSuccessCondition( - () -> { - try { - return !isAnyPodNameHasPatternOccurrence(podName); - } catch (Exception ex) { - throw new RuntimeException(ex.getLocalizedMessage(), ex); - } - }, - timeout, - DELAY_BETWEEN_ATTEMPTS_IN_MILLISECS, - TimeUnit.SECONDS); - } - - private boolean isPodNamePatternHasSingleOccurrence(String podNamePattern) throws Exception { - return 1 == getPodsNamesWithPatternOccurrence(podNamePattern).size(); - } - - private void waitPodNamePatternHasSingleOccurrence(String podName, int timeout) - throws TimeoutException, InterruptedException, ExecutionException { - WaitUtils.waitSuccessCondition( - () -> { - try { - return isPodNamePatternHasSingleOccurrence(podName); - } catch (Exception ex) { - throw new RuntimeException(ex); - } - }, - timeout, - DELAY_BETWEEN_ATTEMPTS_IN_MILLISECS, - TimeUnit.SECONDS); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestApiEndpointUrlProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestApiEndpointUrlProvider.java deleted file mode 100644 index a103ef9923..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestApiEndpointUrlProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.net.URL; -import org.eclipse.che.selenium.core.utils.UrlUtil; - -/** @author Anatolii Bazko */ -@Singleton -public class CheTestApiEndpointUrlProvider implements TestApiEndpointUrlProvider { - @Inject - @Named("che.protocol") - private String protocol; - - @Inject - @Named("che.host") - private String host; - - @Inject - @Named("che.port") - private int port; - - @Override - public URL get() { - return UrlUtil.url(protocol, host, port, "/api/"); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestDashboardUrlProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestDashboardUrlProvider.java deleted file mode 100644 index 054dadd23b..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestDashboardUrlProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.net.URL; -import javax.inject.Named; -import org.eclipse.che.selenium.core.utils.UrlUtil; - -/** @author Anatolii Bazko */ -@Singleton -public class CheTestDashboardUrlProvider implements TestDashboardUrlProvider { - @Inject - @Named("che.protocol") - private String protocol; - - @Inject - @Named("che.host") - private String host; - - @Inject - @Named("che.port") - private int port; - - @Override - public URL get() { - return UrlUtil.url(protocol, host, port, "/dashboard/"); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestIdeUrlProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestIdeUrlProvider.java deleted file mode 100644 index db6266bf3f..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestIdeUrlProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.net.URL; -import javax.inject.Named; -import org.eclipse.che.selenium.core.utils.UrlUtil; - -/** @author Anatolii Bazko */ -@Singleton -public class CheTestIdeUrlProvider implements TestIdeUrlProvider { - @Inject - @Named("che.protocol") - private String protocol; - - @Inject - @Named("che.host") - private String host; - - @Inject - @Named("che.port") - private int port; - - @Override - public URL get() { - return UrlUtil.url(protocol, host, port, "/"); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestWorkspaceAgentApiEndpointUrlProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestWorkspaceAgentApiEndpointUrlProvider.java deleted file mode 100644 index bfe1b63067..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/CheTestWorkspaceAgentApiEndpointUrlProvider.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import static org.eclipse.che.api.workspace.shared.Constants.SERVER_WS_AGENT_HTTP_REFERENCE; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.net.URL; -import java.util.Map; -import org.eclipse.che.api.core.model.workspace.runtime.Machine; -import org.eclipse.che.api.core.model.workspace.runtime.Server; -import org.eclipse.che.api.core.rest.HttpJsonRequestFactory; -import org.eclipse.che.api.workspace.shared.Constants; -import org.eclipse.che.selenium.core.client.CheTestWorkspaceServiceClient; - -@Singleton -public class CheTestWorkspaceAgentApiEndpointUrlProvider - implements TestWorkspaceAgentApiEndpointUrlProvider { - - @Inject private HttpJsonRequestFactory httpJsonRequestFactory; - @Inject private CheTestWorkspaceServiceClient workspaceServiceClient; - - @Override - public URL get(String workspaceId) throws Exception { - workspaceServiceClient.ensureRunningStatus(workspaceServiceClient.getById(workspaceId)); - - Map machines = - workspaceServiceClient.getById(workspaceId).getRuntime().getMachines(); - for (Machine machine : machines.values()) { - if (containsWsAgentServer(machine)) { - Server wsAgentServer = machine.getServers().get(SERVER_WS_AGENT_HTTP_REFERENCE); - if (wsAgentServer != null) { - return new URL(wsAgentServer.getUrl() + "/"); - } else { - throw new RuntimeException("Workspace agent server is null"); - } - } - } - throw new RuntimeException("Cannot find dev machine on workspace with id " + workspaceId); - } - - /** - * Checks whether provided {@link Machine} contains wsagent server. - * - * @param machine machine to check - * @return true when wsagent server is found in provided machine, false otherwise - */ - public static boolean containsWsAgentServer(Machine machine) { - return machine.getServers().keySet().contains(Constants.SERVER_WS_AGENT_HTTP_REFERENCE); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/OpenShiftWebConsoleUrlProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/OpenShiftWebConsoleUrlProvider.java deleted file mode 100644 index 92f889f44f..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/provider/OpenShiftWebConsoleUrlProvider.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.provider; - -import static java.lang.String.format; - -import com.google.inject.Inject; -import com.google.inject.Provider; -import com.google.inject.Singleton; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.inject.Named; -import org.eclipse.che.selenium.core.utils.UrlUtil; - -/** @author Dmytro Nochevnov */ -@Singleton -public class OpenShiftWebConsoleUrlProvider implements Provider { - - private static final int PORT = 8443; - private static final String PROTOCOL = "https"; - - // extract openshift host from the url like 'che-che.172.19.20.137.nip.io' - private static final Pattern OPENSHIFT_HOST_REGEXP = - Pattern.compile(".*[\\.]([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})[.].*"); - - @Inject - @Named("che.host") - private String cheHost; - - @Inject(optional = true) - @Named("env.openshift.url") - private String openShiftUrl; - - @Override - public URL get() { - if (openShiftUrl != null) { - try { - return new URL(openShiftUrl); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } - - String openShiftHost = obtainOpenShiftHost(); - return UrlUtil.url(PROTOCOL, openShiftHost, PORT, "/"); - } - - private String obtainOpenShiftHost() { - if (openShiftUrl != null) { - return openShiftUrl; - } - - Matcher matcher = OPENSHIFT_HOST_REGEXP.matcher(cheHost); - if (!matcher.matches()) { - throw new RuntimeException( - format( - "It's impossible to extract OpenShift host from Eclipse Che host '%s'. Make sure that correct value is set for `CHE_INFRASTRUCTURE`.", - cheHost)); - } - - return matcher.group(1); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/requestfactory/CheTestAdminHttpJsonRequestFactory.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/requestfactory/CheTestAdminHttpJsonRequestFactory.java deleted file mode 100644 index b43b77a935..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/requestfactory/CheTestAdminHttpJsonRequestFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.requestfactory; - -import javax.inject.Inject; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.user.AdminTestUser; - -/** @author Dmytro Nochevnov */ -public class CheTestAdminHttpJsonRequestFactory extends TestUserHttpJsonRequestFactory { - - @Inject - public CheTestAdminHttpJsonRequestFactory( - TestAuthServiceClient authServiceClient, AdminTestUser adminTestUser) { - super(authServiceClient, adminTestUser); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/requestfactory/CheTestDefaultHttpJsonRequestFactory.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/requestfactory/CheTestDefaultHttpJsonRequestFactory.java deleted file mode 100644 index ae9e354c1a..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/requestfactory/CheTestDefaultHttpJsonRequestFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.requestfactory; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.client.TestAuthServiceClient; -import org.eclipse.che.selenium.core.user.DefaultTestUser; - -/** @author Anton Korneta */ -@Singleton -public class CheTestDefaultHttpJsonRequestFactory extends TestUserHttpJsonRequestFactory { - - @Inject - public CheTestDefaultHttpJsonRequestFactory( - TestAuthServiceClient authServiceClient, DefaultTestUser defaultTestUser) { - super(authServiceClient, defaultTestUser); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheAdminTestUserProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheAdminTestUserProvider.java deleted file mode 100644 index 1751bcbed5..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheAdminTestUserProvider.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import com.google.inject.Inject; -import com.google.inject.name.Named; -import java.io.IOException; -import javax.inject.Singleton; -import org.eclipse.che.selenium.core.client.keycloak.cli.KeycloakCliClient; -import org.eclipse.che.selenium.core.provider.AdminTestUserProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Provides {@link AdminTestUser} that ought to be existed at the start of test execution. All tests - * share the same admin user. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class MultiUserCheAdminTestUserProvider implements AdminTestUserProvider { - - private static final Logger LOG = - LoggerFactory.getLogger(MultiUserCheDefaultTestUserProvider.class); - - private AdminTestUser adminTestUser; - - @Inject private TestUserFactory adminTestUserFactory; - @Inject private KeycloakCliClient keycloakCliClient; - - @Inject - @Named("che.admin.name") - private String name; - - @Inject - @Named("che.admin.email") - private String email; - - @Inject - @Named("che.admin.password") - private String password; - - @Override - public AdminTestUser get() { - if (adminTestUser == null) { - if (email == null - || email.trim().isEmpty() - || password == null - || password.trim().isEmpty()) { - throw new IllegalStateException("Admin test user credentials are unknown"); - } - - adminTestUser = adminTestUserFactory.create(name, email, password, this); - keycloakCliClient.setupAdmin(adminTestUser); - - LOG.info("User name='{}', id='{}' is being used as admin", name, adminTestUser.getId()); - } - - return adminTestUser; - } - - @Override - public void delete() throws IOException { - // do nothing because we don't remove admin user - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheDefaultTestUserProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheDefaultTestUserProvider.java deleted file mode 100644 index 20b2fe3bf6..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheDefaultTestUserProvider.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import com.google.inject.Inject; -import com.google.inject.name.Named; -import java.io.IOException; -import javax.inject.Singleton; -import org.eclipse.che.selenium.core.client.keycloak.cli.KeycloakCliClient; -import org.eclipse.che.selenium.core.provider.DefaultTestUserProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Provides {@link DefaultTestUser} for the Multi User Eclipse Che which ought to be existed at the - * start of test execution. All tests share the same default user. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class MultiUserCheDefaultTestUserProvider implements DefaultTestUserProvider { - - private static final Logger LOG = - LoggerFactory.getLogger(MultiUserCheDefaultTestUserProvider.class); - - private final DefaultTestUser defaultTestUser; - private final boolean isNewUser; - private final KeycloakCliClient keycloakCliClient; - - @Inject - public MultiUserCheDefaultTestUserProvider( - TestUserFactory defaultTestUserFactory, - KeycloakCliClient keycloakCliClient, - MultiUserCheAdminTestUserProvider adminTestUserProvider, - @Named("che.testuser.name") String name, - @Named("che.testuser.email") String email, - @Named("che.testuser.password") String password) { - this.keycloakCliClient = keycloakCliClient; - if (email == null || email.trim().isEmpty() || password == null || password.trim().isEmpty()) { - DefaultTestUser testUser; - Boolean isNewUser; - try { - testUser = keycloakCliClient.createDefaultUser(this); - isNewUser = true; - } catch (IOException e) { - LOG.warn( - "Default test user credentials isn't set and it's impossible to create it from tests because of error. " - + "Is going to use admin test user as a default test user.", - e); - - isNewUser = false; - - AdminTestUser adminTestUser = adminTestUserProvider.get(); - testUser = - defaultTestUserFactory.create( - adminTestUser.getName(), - adminTestUser.getEmail(), - adminTestUser.getPassword(), - adminTestUserProvider); - } - - this.defaultTestUser = testUser; - this.isNewUser = isNewUser; - } else { - this.defaultTestUser = defaultTestUserFactory.create(name, email, password, this); - this.isNewUser = false; - - LOG.info( - "User name='{}', id='{}' is being used as default user", - defaultTestUser.getName(), - defaultTestUser.getId()); - } - } - - @Override - public DefaultTestUser get() { - return defaultTestUser; - } - - @Override - public void delete() throws IOException { - if (isNewUser) { - keycloakCliClient.delete(defaultTestUser); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheTestUserProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheTestUserProvider.java deleted file mode 100644 index 5b546de94f..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/MultiUserCheTestUserProvider.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import com.google.inject.Inject; -import java.io.IOException; -import javax.annotation.PreDestroy; -import org.eclipse.che.selenium.core.client.keycloak.cli.KeycloakCliClient; -import org.eclipse.che.selenium.core.provider.AdminTestUserProvider; -import org.eclipse.che.selenium.core.provider.TestUserProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Provides new {@link TestUser} for the Multi User Eclipse Che. - * - * @author Dmytro Nochevnov - */ -public class MultiUserCheTestUserProvider implements TestUserProvider { - - private static final Logger LOG = LoggerFactory.getLogger(MultiUserCheTestUserProvider.class); - - private final TestUser testUser; - private final boolean isNewUser; - private final KeycloakCliClient keycloakCliClient; - - @Inject - public MultiUserCheTestUserProvider( - TestUserFactory testUserFactory, - KeycloakCliClient keycloakCliClient, - AdminTestUserProvider adminTestUserProvider) { - this.keycloakCliClient = keycloakCliClient; - TestUserImpl testUser; - Boolean isNewUser; - try { - testUser = keycloakCliClient.createUser(this); - isNewUser = true; - } catch (IOException e) { - LOG.warn( - "It's impossible to create test user from tests because of error. " - + "Is going to use admin test user as test user.", - e); - - isNewUser = false; - - AdminTestUser adminTestUser = adminTestUserProvider.get(); - testUser = - testUserFactory.create( - adminTestUser.getName(), - adminTestUser.getEmail(), - adminTestUser.getPassword(), - adminTestUserProvider); - - LOG.info( - "User name='{}', id='{}' is being used for testing", - testUser.getName(), - testUser.getId()); - } - - this.testUser = testUser; - this.isNewUser = isNewUser; - } - - @Override - public TestUser get() { - return testUser; - } - - @Override - @PreDestroy - public void delete() throws IOException { - if (isNewUser) { - keycloakCliClient.delete(testUser); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/SingleUserCheDefaultTestUserProvider.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/SingleUserCheDefaultTestUserProvider.java deleted file mode 100644 index 901fddf3a7..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/user/SingleUserCheDefaultTestUserProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.user; - -import com.google.inject.Inject; -import java.io.IOException; -import javax.inject.Singleton; -import org.eclipse.che.selenium.core.provider.DefaultTestUserProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Provides {@link DefaultTestUser} for the Single User Eclipse Che which ought to be existed at the - * start of test execution. All tests share the same default user. - * - * @author Dmytro Nochevnov - */ -@Singleton -public class SingleUserCheDefaultTestUserProvider implements DefaultTestUserProvider { - private static final Logger LOG = - LoggerFactory.getLogger(SingleUserCheDefaultTestUserProvider.class); - private final DefaultTestUser defaultTestUser; - - @Inject - public SingleUserCheDefaultTestUserProvider( - TestUserFactory defaultTestUserFactory) { - String name = "che"; - String email = "che@eclipse.org"; - String password = "secret"; - this.defaultTestUser = defaultTestUserFactory.create(name, email, password, this); - - LOG.info("User name='{}', id='{}' is being used by default", name, defaultTestUser.getId()); - } - - @Override - public DefaultTestUser get() { - return defaultTestUser; - } - - @Override - public void delete() throws IOException { - // we don't need to remove test user of Single User Eclipse Che - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestDockerWorkspaceLogsReader.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestDockerWorkspaceLogsReader.java deleted file mode 100644 index 5f3f5bc144..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestDockerWorkspaceLogsReader.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.workspace.TestWorkspaceLogsReader.LogInfo.create; - -import com.google.common.collect.ImmutableList; -import com.google.inject.Inject; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import javax.inject.Singleton; -import org.eclipse.che.selenium.core.utils.DockerUtil; - -/** @author Dmytro Nochevnov */ -@Singleton -public class CheTestDockerWorkspaceLogsReader extends TestWorkspaceLogsReader { - - @Inject private DockerUtil dockerUtil; - - private final List logInfos = - ImmutableList.of( - create("ws-agent", Paths.get("/home/user/che/ws-agent/logs")), - create("exec-agent", Paths.get("/home/user/che/exec-agent/logs")), - create("tomcat", Paths.get("/home/user/tomcat8/logs")), - create("apache", Paths.get("/var/log/apache2")), - create("traefik", Paths.get("/home/user/che/traefik/log.txt"))); - - @Override - String getReadLogsCommand( - String workspaceId, Path testLogsDirectory, Path logLocationInsideWorkspace) { - return format( - "if [[ $(docker exec -i $(docker ps -q -f name=%1$s) bash -c '[ -d %2$s ] && echo true || echo false') == true ]]; then " - + "docker cp $(docker ps -q -f name=%1$s | head -1):%2$s %3$s; fi", - workspaceId, logLocationInsideWorkspace, testLogsDirectory); - } - - @Override - List getLogInfos() { - return logInfos; - } - - @Override - boolean canWorkspaceLogsBeRead() { - return dockerUtil.isCheRunLocally(); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestOpenshiftWorkspaceLogsReader.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestOpenshiftWorkspaceLogsReader.java deleted file mode 100644 index 62559dcf08..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestOpenshiftWorkspaceLogsReader.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.workspace.TestWorkspaceLogsReader.LogInfo.create; - -import com.google.common.collect.ImmutableList; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - -/** @author Dmytro Nochevnov */ -public class CheTestOpenshiftWorkspaceLogsReader extends TestWorkspaceLogsReader { - - private final List logInfos = - ImmutableList.of( - create("bootstrapper", Paths.get("/workspace_logs/bootstrapper")), - create("exec-agent", Paths.get("/workspace_logs/exec-agent")), - create("ws-agent", Paths.get("/workspace_logs/ws-agent"))); - - @Override - String getReadLogsCommand( - String workspaceId, Path testLogsDirectory, Path logLocationInsideWorkspace) { - return format( - "docker cp $(docker ps -q -f name=k8s_container_%s | head -1):%s %s", - workspaceId, logLocationInsideWorkspace, testLogsDirectory); - } - - @Override - List getLogInfos() { - return logInfos; - } - - @Override - boolean canWorkspaceLogsBeRead() { - return true; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspaceUrlResolver.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspaceUrlResolver.java deleted file mode 100644 index 5ff80d5929..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/core/workspace/CheTestWorkspaceUrlResolver.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.core.workspace; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.concurrent.ExecutionException; -import org.eclipse.che.selenium.core.provider.TestIdeUrlProvider; - -/** @author Anatolii Bazko */ -@Singleton -public class CheTestWorkspaceUrlResolver implements TestWorkspaceUrlResolver { - - @Inject private TestIdeUrlProvider testIdeUrlProvider; - - @Override - public URL resolve(TestWorkspace testWorkspace) throws MalformedURLException { - try { - return new URL( - testIdeUrlProvider.get() - + testWorkspace.getOwner().getName() - + "/" - + testWorkspace.getName()); - } catch (ExecutionException | InterruptedException e) { - throw new IllegalStateException(e); - } - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/Loader.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/Loader.java deleted file mode 100644 index 2087817300..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/Loader.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject; - -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.UPDATING_PROJECT_TIMEOUT_SEC; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.utils.WaitUtils; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.FindBy; -import org.openqa.selenium.support.PageFactory; - -/** @author Anna Shumilova */ -@Singleton -public class Loader { - - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - - @Inject - public Loader( - SeleniumWebDriver seleniumWebDriver, SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - - PageFactory.initElements(seleniumWebDriver, this); - } - - private interface Locators { - String PREFIX_ID = "gwt-debug-"; - String LOADER_ID = PREFIX_ID + "loader-panel"; - String MESSAGE_CONTAINER_ID = PREFIX_ID + "loader-message"; - } - - @FindBy(id = Locators.LOADER_ID) - private WebElement loader; - - @FindBy(id = Locators.MESSAGE_CONTAINER_ID) - private WebElement messContainer; - - /** Waits for Loader to hide. */ - public void waitOnClosed() { - // in this pace pause, because loader can appear not at once - WaitUtils.sleepQuietly(1); - - seleniumWebDriverHelper.waitInvisibility(loader, UPDATING_PROJECT_TIMEOUT_SEC); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/PageObjectsInjectorImpl.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/PageObjectsInjectorImpl.java deleted file mode 100644 index 8021fa5867..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/PageObjectsInjectorImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.util.HashMap; -import java.util.Map; -import org.eclipse.che.selenium.core.CheSeleniumWebDriverRelatedModule; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.action.ActionsFactory; -import org.eclipse.che.selenium.core.entrance.Entrance; -import org.eclipse.che.selenium.core.pageobject.PageObjectsInjector; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.eclipse.che.selenium.core.webdriver.UploadUtil; -import org.eclipse.che.selenium.core.webdriver.WebDriverWaitFactory; -import org.eclipse.che.selenium.pageobject.site.CheLoginPage; - -/** @author Dmytro Nochevnov */ -@Singleton -public class PageObjectsInjectorImpl extends PageObjectsInjector { - @Inject private CheSeleniumWebDriverRelatedModule cheSeleniumWebDriverRelatedModule; - @Inject private ActionsFactory actionsFactory; - - @Inject - @Named("che.multiuser") - private boolean isMultiuser; - - @Inject private UploadUtil uploadUtil; - - @Override - public Map, Object> getDependenciesWithWebdriver(SeleniumWebDriver seleniumWebDriver) { - SeleniumWebDriverHelper seleniumWebDriverHelper = - new SeleniumWebDriverHelper( - seleniumWebDriver, - new WebDriverWaitFactory(seleniumWebDriver), - actionsFactory, - uploadUtil); - - Map, Object> dependencies = new HashMap<>(); - dependencies.put( - Entrance.class, - cheSeleniumWebDriverRelatedModule.getEntrance( - isMultiuser, - new CheLoginPage(seleniumWebDriver, seleniumWebDriverHelper), - seleniumWebDriver)); - - return dependencies; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/Swagger.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/Swagger.java deleted file mode 100644 index 7bc8ae79d3..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/Swagger.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.ELEMENT_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.MINIMUM_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.REDRAW_UI_ELEMENTS_TIMEOUT_SEC; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.stream.Collectors; -import org.eclipse.che.api.workspace.shared.dto.WorkspaceDto; -import org.eclipse.che.commons.json.JsonHelper; -import org.eclipse.che.commons.json.JsonParseException; -import org.eclipse.che.dto.server.DtoFactory; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.utils.WaitUtils; -import org.everrest.core.impl.provider.json.JsonValue; -import org.openqa.selenium.By; -import org.openqa.selenium.NoSuchElementException; -import org.openqa.selenium.StaleElementReferenceException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.FindBy; -import org.openqa.selenium.support.PageFactory; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.ExpectedConditions; -import org.openqa.selenium.support.ui.FluentWait; -import org.openqa.selenium.support.ui.Wait; -import org.openqa.selenium.support.ui.WebDriverWait; - -/** @author Andrey Chizhikov */ -@Singleton -public class Swagger { - - private final SeleniumWebDriver seleniumWebDriver; - - @Inject - public Swagger(SeleniumWebDriver seleniumWebDriver) { - this.seleniumWebDriver = seleniumWebDriver; - PageFactory.initElements(seleniumWebDriver, this); - } - - private interface Locators { - String WORKSPACE = "//a[@href='#!/workspace']"; - String PROJECT = "//a[@href='#!/project']"; - - String GET_PROJECT = "//a[@href='#!/project/getProjects']"; - String GET_PROJECT_TRY_IT_OUT = "//li[@id='resource_project']//input[@value='Try it out!']"; - String GET_WS_ID_RESPONSE_BODY = "//li[@id='resource_project']//code"; - - String GET_WORKSPACES = "//a[@href='#!/workspace/getWorkspaces']"; - String TRY_IT_OUT = "//li[@id='workspace_getWorkspaces']//input[@value='Try it out!']"; - String RESPONSE_BODY = "//li[@id='workspace_getWorkspaces']//code"; - String TRY_IT_OUT_RUNTIME = "//li[@id='workspace_getWorkspaces']//input[@value='Try it out!']"; - String RESPONSE_BODY_RUNTIME = "//li[@id='workspace_getWorkspaces']//code"; - String BASE_URL_INPUT = "//input[@id='input_baseUrl']"; - String EXPLORE = "//a[@id='explore']"; - } - - @FindBy(xpath = Locators.WORKSPACE) - WebElement workSpaceLink; - - /** expand 'workspace' item */ - private void expandWorkSpaceItem() { - Wait fluentWait = - new FluentWait(seleniumWebDriver) - .withTimeout(ELEMENT_TIMEOUT_SEC, SECONDS) - .pollingEvery(MINIMUM_SEC, SECONDS) - .ignoring(StaleElementReferenceException.class, NoSuchElementException.class); - fluentWait.until((ExpectedCondition) input -> workSpaceLink.isEnabled()); - workSpaceLink.click(); - } - - /** collapse 'workspace' item */ - private void collapseWorkSpaceItem() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(ExpectedConditions.elementToBeClickable(workSpaceLink)) - .click(); - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(ExpectedConditions.invisibilityOfElementLocated(By.id("workspace_endpoint_list"))); - } - - /** - * Clicks on the element by Xpath - * - * @param xPath web element Xpath - */ - private void clickElementByXpath(String xPath) { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(ExpectedConditions.elementToBeClickable(By.xpath(xPath))) - .click(); - } - - /** - * Clicks on the 'Try it out' by Xpath - * - * @param xPath web element Xpath - */ - private void clickTryItOutByXpath(String xPath) { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(ExpectedConditions.elementToBeClickable(By.xpath(xPath))) - .click(); - } - - /** - * get wsId from the text that has been graped from the swagger page - * - * @return result search by key - */ - public List getWsNamesFromWorkspacePage() { - expandWorkSpaceItem(); - clickElementByXpath(Locators.GET_WORKSPACES); - clickTryItOutByXpath(Locators.TRY_IT_OUT); - List workspaces = new ArrayList(); - // Sometimes when we get text from swagger page the JSON may be in rendering state. In this case - // we get invalid data. - // In this loop we perform 2 attempts with 500 msec. delay for getting correct data after full - // rendering page. - for (int i = 0; i < 2; i++) { - try { - workspaces = - DtoFactory.getInstance() - .createListDtoFromJson( - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until( - ExpectedConditions.visibilityOfElementLocated( - By.xpath(Locators.RESPONSE_BODY))) - .getText(), - WorkspaceDto.class); - break; - } catch (RuntimeException ex) { - WaitUtils.sleepQuietly(500, MILLISECONDS); - } - } - return workspaces - .stream() - .map(workspaceDto -> workspaceDto.getConfig().getName()) - .collect(Collectors.toList()); - } - - /** - * create URL - * - * @param port number of port - * @param machineToken authorization token for machine - * @param workspaceName name of workspace - * @return String - * @throws JsonParseException - */ - public String createURLByExposedPort(String port, String machineToken, String workspaceName) - throws JsonParseException { - String json; - String url; - String serverAddress = ""; - expandWorkSpaceItem(); - clickTryItOutByXpath(Locators.TRY_IT_OUT_RUNTIME); - json = - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until( - ExpectedConditions.visibilityOfElementLocated( - By.xpath(Locators.RESPONSE_BODY_RUNTIME))) - .getText(); - JsonValue jsonValue = JsonHelper.parseJson(json); - JsonValue foundValue = null; - Iterator jsonIterator = jsonValue.getElements(); - while (jsonIterator.hasNext()) { - JsonValue value = jsonIterator.next(); - JsonValue config = value.getElement("config"); - JsonValue defaultEnv = config.getElement("defaultEnv"); - if (defaultEnv.isString() && workspaceName.equals(defaultEnv.getStringValue())) { - foundValue = value; - break; - } - } - if (foundValue != null) { - serverAddress = - foundValue - .getElement("runtime") - .getElement("devMachine") - .getElement("runtime") - .getElement("servers") - .getElement(port) - .getElement("url") - .toString() - .replaceAll("\"", ""); - } - - url = serverAddress + "/docs/swagger.json?token=" + machineToken; - collapseWorkSpaceItem(); - return url; - } - - /** click on 'project' link */ - private void clickOnProjectLink() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(ExpectedConditions.elementToBeClickable(By.xpath(Locators.PROJECT))) - .click(); - } - - /** - * enter URL and click 'Explore' - * - * @param URL URL - */ - private void enterURLAndClickExplore(String URL) { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Locators.BASE_URL_INPUT))) - .clear(); - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Locators.BASE_URL_INPUT))) - .sendKeys(URL); - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Locators.EXPLORE))) - .click(); - } - - /** - * @param URL URL - * @return return list names of projects from workspace - * @throws JsonParseException - */ - public List getNamesOfProjects(String URL) throws JsonParseException { - String json; - List projectsList = new ArrayList<>(); - enterURLAndClickExplore(URL); - clickOnProjectLink(); - clickElementByXpath(Locators.GET_PROJECT); - clickTryItOutByXpath(Locators.GET_PROJECT_TRY_IT_OUT); - WaitUtils.sleepQuietly(2); - json = - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until( - ExpectedConditions.visibilityOfElementLocated( - By.xpath(Locators.GET_WS_ID_RESPONSE_BODY))) - .getText(); - Iterator jsonHelperIterator = JsonHelper.parseJson(json).getElements(); - - while (jsonHelperIterator.hasNext()) { - projectsList.add( - jsonHelperIterator.next().getElement("name").toString().replaceAll("\"", "")); - } - - return projectsList; - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/TestWebElementRenderChecker.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/TestWebElementRenderChecker.java deleted file mode 100644 index de640f0b6d..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/TestWebElementRenderChecker.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject; - -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.ELEMENT_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; -import org.openqa.selenium.Dimension; -import org.openqa.selenium.StaleElementReferenceException; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.FluentWait; - -@Singleton -public class TestWebElementRenderChecker { - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - - @Inject - public TestWebElementRenderChecker( - SeleniumWebDriver seleniumWebDriver, SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - } - - /** - * wait until element have the same size between two checks it means that element is fully opened - * - * @param webElement list or context menu which need check - * @param seconds timeout for check - */ - public void waitElementIsRendered(WebElement webElement, int seconds) { - waitElementIsStatic(getFluentWait(seconds), webElement); - } - - /** - * wait until element have the same size between two checks it means that element is fully opened - * - * @param webElement list or context menu which need check - */ - public void waitElementIsRendered(WebElement webElement) { - waitElementIsRendered(webElement, LOAD_PAGE_TIMEOUT_SEC); - } - - /** - * wait until element have the same size between two checks it means that element is fully opened - * - * @param locator list or context menu Xpath which need check - */ - public void waitElementIsRendered(By locator) { - waitElementIsRendered(waitAndGetWebElement(locator)); - } - - /** - * wait until element have the same size between two checks it means that element is fully opened - * - * @param locator list or context menu Xpath which need check - */ - public void waitElementIsRendered(By locator, int seconds) { - waitElementIsRendered(waitAndGetWebElement(locator), seconds); - } - - private Boolean dimensionsAreEquivalent(AtomicInteger sizeHashCode, Dimension newDimension) { - return sizeHashCode.get() == getSizeHashCode(newDimension); - } - - private FluentWait getFluentWait(int seconds) { - return new FluentWait(seleniumWebDriver) - .withTimeout(seconds, TimeUnit.SECONDS) - .pollingEvery(200, TimeUnit.MILLISECONDS) - .ignoring(StaleElementReferenceException.class); - } - - private void waitElementIsStatic(FluentWait webDriverWait, WebElement webElement) { - AtomicInteger sizeHashCode = new AtomicInteger(); - - webDriverWait.until( - (ExpectedCondition) - driver -> { - Dimension newDimension = waitAndGetWebElement(webElement).getSize(); - - if (dimensionsAreEquivalent(sizeHashCode, newDimension)) { - return true; - } else { - sizeHashCode.set(getSizeHashCode(newDimension)); - return false; - } - }); - } - - /** - * height is multiplied because we must avoid the situation when, in fact, different parties will - * give the same sum for example 15 + 25 == 25 + 15, but 15 + 25*10000 != 25 + 15*10000 - * - * @param dimension consist partial sizes - * @return partial sizes sum with shift - */ - private int getSizeHashCode(Dimension dimension) { - return dimension.getWidth() + (dimension.getHeight() * 10000); - } - - private WebElement waitAndGetWebElement(WebElement webElement) { - return seleniumWebDriverHelper.waitVisibility(webElement, ELEMENT_TIMEOUT_SEC); - } - - private WebElement waitAndGetWebElement(By locator) { - return seleniumWebDriverHelper.waitVisibility(locator, ELEMENT_TIMEOUT_SEC); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/AddOrImportForm.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/AddOrImportForm.java deleted file mode 100644 index fb4f5663e6..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/AddOrImportForm.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static java.util.stream.Collectors.toMap; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.ADD_BUTTON_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.ADD_OR_CANCEL_BUTTON_XPATH_TEMPLATE; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.ADD_OR_IMPORT_PROJECT_BUTTON_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.BLANK_BUTTON_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.BLANK_FORM_DESCRIPTION_FIELD_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.BLANK_FORM_NAME_ERROR_MESSAGE_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.BLANK_FORM_NAME_FIELD_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.CANCEL_BUTTON_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.GITHUG_BUTTON_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.GIT_BUTTON_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.SAMPLES_BUTTON_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.TOOLTIP_XPATH_TEMPLATE; -import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.ZIP_BUTTON_ID; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.eclipse.che.selenium.core.webdriver.WebDriverWaitFactory; -import org.openqa.selenium.By; -import org.openqa.selenium.TimeoutException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.PageFactory; -import org.openqa.selenium.support.ui.ExpectedCondition; - -/** @author Ihor Okhrimenko */ -@Singleton -public class AddOrImportForm { - - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final WebDriverWaitFactory webDriverWaitFactory; - private static final int DEFAULT_TIMEOUT = LOAD_PAGE_TIMEOUT_SEC; - - @Inject - AddOrImportForm( - SeleniumWebDriver seleniumWebDriver, - SeleniumWebDriverHelper seleniumWebDriverHelper, - WebDriverWaitFactory webDriverWaitFactory) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - this.webDriverWaitFactory = webDriverWaitFactory; - - PageFactory.initElements(seleniumWebDriver, this); - } - - public interface Locators { - String ADD_OR_IMPORT_PROJECT_BUTTON_ID = "ADD_PROJECT"; - String ADD_OR_CANCEL_BUTTON_XPATH_TEMPLATE = "//*[@id='%s']/button"; - - // "Add or Import Project" form buttons - String SAMPLES_BUTTON_ID = "samples-button"; - String BLANK_BUTTON_ID = "blank-button"; - String GIT_BUTTON_ID = "git-button"; - String GITHUG_BUTTON_ID = "github-button"; - String ZIP_BUTTON_ID = "zip-button"; - String ADD_BUTTON_ID = "add-project-button"; - String CANCEL_BUTTON_ID = "cancel-button"; - - String CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE = "sample-%s"; - String PROJECT_TAB_XPATH_TEMPLATE = "//toggle-single-button[@id='%s']/div/button/div"; - String PROJECT_TAB_BY_NAME_XPATH_TEMPLATE = - "//div[@class='%s']//span[text()='console-java-simple']"; - - // Blank tab fields - String BLANK_FORM_NAME_FIELD_XPATH = "//input[@name='name']"; - String BLANK_FORM_DESCRIPTION_FIELD_XPATH = "//input[@name='description']"; - String BLANK_FORM_NAME_ERROR_MESSAGE_XPATH = - "//div[@id='project-source-selector']//div[@id='new-workspace-error-message']/div"; - - String TOOLTIP_XPATH_TEMPLATE = "//*[contains(@class, 'tooltip') and @content='%s']"; - } - - public WebElement waitAddOrImportProjectButton(int timeout) { - return seleniumWebDriverHelper.waitVisibility(By.id(ADD_OR_IMPORT_PROJECT_BUTTON_ID), timeout); - } - - public WebElement waitAddOrImportProjectButton() { - return waitAddOrImportProjectButton(DEFAULT_TIMEOUT); - } - - public void clickOnAddOrImportProjectButton() { - waitAddOrImportProjectButton().click(); - } - - public void clickOnSamplesButton() { - seleniumWebDriverHelper.waitAndClick(By.id(SAMPLES_BUTTON_ID)); - } - - public void clickOnBlankButton() { - seleniumWebDriverHelper.waitAndClick(By.id(BLANK_BUTTON_ID)); - } - - public void clickOnGitButton() { - seleniumWebDriverHelper.waitAndClick(By.id(GIT_BUTTON_ID)); - } - - public void clickOnGitHubButton() { - seleniumWebDriverHelper.waitAndClick(By.id(GITHUG_BUTTON_ID)); - } - - public void clickOnZipButton() { - seleniumWebDriverHelper.waitAndClick(By.id(ZIP_BUTTON_ID)); - } - - public void clickOnAddButton() { - seleniumWebDriverHelper.waitAndClick(By.id(ADD_BUTTON_ID)); - } - - public void addSampleToWorkspace(String sampleName) { - waitAddOrImportFormOpened(); - - if (!isSampleCheckboxEnabled(sampleName)) { - clickOnSampleCheckbox(sampleName); - } - - waitSampleCheckboxEnabled(sampleName); - clickOnAddButton(); - waitProjectTabAppearance(sampleName); - } - - public void clickOnCancelButton() { - seleniumWebDriverHelper.waitAndClick(By.id(CANCEL_BUTTON_ID)); - } - - public void waitAddOrImportFormOpened() { - seleniumWebDriverHelper.waitAllVisibilityBy( - asList( - By.id(SAMPLES_BUTTON_ID), - By.id(BLANK_BUTTON_ID), - By.id(GIT_BUTTON_ID), - By.id(GITHUG_BUTTON_ID), - By.id(ZIP_BUTTON_ID), - By.id(ADD_BUTTON_ID), - By.id(CANCEL_BUTTON_ID))); - } - - public void waitAddOrImportFormClosed() { - seleniumWebDriverHelper.waitAllInvisibilityBy( - asList( - By.id(SAMPLES_BUTTON_ID), - By.id(BLANK_BUTTON_ID), - By.id(GIT_BUTTON_ID), - By.id(GITHUG_BUTTON_ID), - By.id(ZIP_BUTTON_ID), - By.id(ADD_BUTTON_ID), - By.id(CANCEL_BUTTON_ID))); - } - - private void waitSelectionOfHeaderButton(String buttonId) { - String locator = format("//che-toggle-joined-button[@id='%s']/button", buttonId); - seleniumWebDriverHelper.waitAttributeContainsValue( - By.xpath(locator), "class", "che-toggle-button-enabled"); - } - - public void waitSamplesButtonSelected() { - waitSelectionOfHeaderButton(SAMPLES_BUTTON_ID); - } - - public void waitBlankButtonSelected() { - waitSelectionOfHeaderButton(BLANK_BUTTON_ID); - } - - public void waitGitButtonSelected() { - waitSelectionOfHeaderButton(GIT_BUTTON_ID); - } - - public void waitGitHubButtonSelected() { - waitSelectionOfHeaderButton(GITHUG_BUTTON_ID); - } - - public void waitZipButtonSelected() { - waitSelectionOfHeaderButton(ZIP_BUTTON_ID); - } - - private void waitButtonDisableState(WebElement button, boolean state) { - seleniumWebDriverHelper.waitAttributeEqualsTo(button, "aria-disabled", Boolean.toString(state)); - } - - private WebElement waitAddButton() { - return seleniumWebDriverHelper.waitVisibility( - By.xpath(format(ADD_OR_CANCEL_BUTTON_XPATH_TEMPLATE, ADD_BUTTON_ID))); - } - - private WebElement waitCancelButton() { - return seleniumWebDriverHelper.waitVisibility( - By.xpath(format(ADD_OR_CANCEL_BUTTON_XPATH_TEMPLATE, CANCEL_BUTTON_ID))); - } - - public void waitAddButtonDisabled() { - waitButtonDisableState(waitAddButton(), true); - } - - public void waitCancelButtonDisabled() { - waitButtonDisableState(waitCancelButton(), true); - } - - public void waitAddButtonEnabled() { - waitButtonDisableState(waitAddButton(), false); - } - - public void waitCancelButtonEnabled() { - waitButtonDisableState(waitCancelButton(), false); - } - - public void waitGitTabOpened() { - waitGitButtonSelected(); - waitGitUrlField(); - } - - public WebElement waitGitUrlField() { - return seleniumWebDriverHelper.waitVisibility(waitElementByNameAttribute("remoteGitURL")); - } - - public void typeToGitUrlField(String text) { - seleniumWebDriverHelper.setValue(waitGitUrlField(), text); - } - - public WebElement waitConnectYourGithubAccountButton() { - return seleniumWebDriverHelper.waitVisibility( - By.xpath("//*[@id='import-github-project-button']/*[contains(@class, 'che-button')]")); - } - - public void clickConnectYourGithubAccountButton() { - seleniumWebDriverHelper.waitAndClick(waitConnectYourGithubAccountButton()); - } - - private WebElement waitElementByNameAttribute(String nameAttribute) { - return seleniumWebDriverHelper.waitVisibility( - By.xpath(format("//input[@name='%s']", nameAttribute))); - } - - private void waitTextInTooltip(String expectedText) { - seleniumWebDriverHelper.waitTextEqualsTo( - By.xpath(format(TOOLTIP_XPATH_TEMPLATE, expectedText)), expectedText); - } - - public void clickOnProjectTab(String tabName) { - waitProjectTabAppearance(tabName); - seleniumWebDriverHelper.moveCursorTo(By.id(tabName)); - - try { - waitTextInTooltip(tabName); - } catch (TimeoutException ex) { - // sometimes the tooltip does not display on the CI - } - - seleniumWebDriverHelper.waitAndClick(By.id(tabName)); - } - - private List getSamples() { - return seleniumWebDriverHelper.waitVisibilityOfAllElements( - By.xpath("//div[@class='add-import-project-sources']//md-item")); - } - - private String getSampleName(WebElement samplesItem) { - return asList(seleniumWebDriverHelper.waitVisibilityAndGetText(samplesItem).split("\n")).get(0); - } - - private String getSampleDescription(WebElement samplesItem) { - return asList(seleniumWebDriverHelper.waitVisibilityAndGetText(samplesItem).split("\n")).get(1); - } - - private Map getSamplesNamesAndDescriptions() { - return getSamples() - .stream() - .collect( - toMap(element -> getSampleName(element), element -> getSampleDescription(element))); - } - - public Set getSamplesNames() { - return getSamplesNamesAndDescriptions().keySet(); - } - - public String getSampleDescription(String sampleName) { - return getSamplesNamesAndDescriptions().get(sampleName); - } - - public void waitSamplesWithDescriptions(Map expectedSamplesWithDescriptions) { - webDriverWaitFactory - .get() - .until( - (ExpectedCondition) - driver -> expectedSamplesWithDescriptions.equals(getSamplesNamesAndDescriptions())); - } - - public void clickOnSampleCheckbox(String sampleName) { - String checkboxId = format(CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE, sampleName); - - seleniumWebDriverHelper.waitAndClick( - By.xpath(format("//*[@id='%s']/md-checkbox/div", checkboxId))); - } - - public boolean isSampleCheckboxEnabled(String sampleName) { - String checkboxId = format(CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE, sampleName); - String checkboxLocator = format("//div[@id='%s']/md-checkbox", checkboxId); - return seleniumWebDriverHelper - .waitVisibilityAndGetAttribute(By.xpath(checkboxLocator), "aria-checked") - .equals("true"); - } - - private void waitSampleCheckboxState(String sampleName, boolean state) { - String checkboxId = format(CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE, sampleName); - String locator = format("//div[@id='%s']/md-checkbox", checkboxId); - - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(locator), "aria-checked", Boolean.toString(state)); - } - - public void waitSampleCheckboxEnabled(String sampleName) { - waitSampleCheckboxState(sampleName, true); - } - - public void waitSampleCheckboxDisabled(String sampleName) { - waitSampleCheckboxState(sampleName, false); - } - - public void waitProjectTabAppearance(String tabName) { - seleniumWebDriverHelper.waitVisibility(By.id(tabName)); - } - - public void waitProjectTabDisappearance(String tabName) { - seleniumWebDriverHelper.waitInvisibility(By.id(tabName)); - } - - public void waitTextInBlankNameField(String expectedText) { - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(BLANK_FORM_NAME_FIELD_XPATH), "value", expectedText); - } - - public void typeToBlankNameField(String text) { - seleniumWebDriverHelper.setValue(By.xpath(BLANK_FORM_NAME_FIELD_XPATH), text); - } - - public void waitNameFieldErrorMessageInBlankForm(String errorMessage) { - seleniumWebDriverHelper.waitTextEqualsTo( - By.xpath(BLANK_FORM_NAME_ERROR_MESSAGE_XPATH), errorMessage); - } - - public void waitErrorMessageDissappearanceInBlankNameField() { - seleniumWebDriverHelper.waitInvisibility(By.xpath(BLANK_FORM_NAME_ERROR_MESSAGE_XPATH)); - } - - public void waitTextInBlankDescriptionField(String expectedText) { - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(BLANK_FORM_DESCRIPTION_FIELD_XPATH), "value", expectedText); - } - - public void typeToBlankDescriptionField(String text) { - seleniumWebDriverHelper.setValue(By.xpath(BLANK_FORM_DESCRIPTION_FIELD_XPATH), text); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/CreateWorkspaceHelper.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/CreateWorkspaceHelper.java deleted file mode 100644 index d242bf19f0..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/CreateWorkspaceHelper.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Devfile; -import org.eclipse.che.selenium.pageobject.dashboard.workspaces.Workspaces; -import org.eclipse.che.selenium.pageobject.theia.TheiaIde; - -/** - * Class cover creation of workspaces on Dashboard - * - * @author Skoryk Serhii - */ -@Singleton -public class CreateWorkspaceHelper { - - @Inject private Dashboard dashboard; - @Inject private Workspaces workspaces; - @Inject private NewWorkspace newWorkspace; - @Inject private TheiaIde theiaIde; - - public String createAndStartWorkspace(Devfile devfile) { - String workspaceName; - - dashboard.waitDashboardToolbarTitle(); - dashboard.selectWorkspacesItemOnDashboard(); - workspaces.clickOnAddWorkspaceBtn(); - - newWorkspace.clickOnGetStartedTab(); - newWorkspace.waitGetStartedTabActive(); - newWorkspace.selectDevfileFromGetStartedList(devfile); - - workspaceName = theiaIde.waitOpenedWorkspaceIsReadyToUse(); - - return workspaceName.substring(workspaceName.indexOf("java"), workspaceName.lastIndexOf("?")); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/Dashboard.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/Dashboard.java deleted file mode 100644 index 0ef33424f8..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/Dashboard.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.ELEMENT_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.EXPECTED_MESS_IN_CONSOLE_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOADER_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.REDRAW_UI_ELEMENTS_TIMEOUT_SEC; -import static org.openqa.selenium.support.ui.ExpectedConditions.invisibilityOfElementLocated; -import static org.openqa.selenium.support.ui.ExpectedConditions.textToBePresentInElement; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.google.inject.name.Named; -import java.util.List; -import javax.annotation.PreDestroy; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.client.TestUserPreferencesServiceClient; -import org.eclipse.che.selenium.core.client.keycloak.TestKeycloakSettingsServiceClient; -import org.eclipse.che.selenium.core.entrance.Entrance; -import org.eclipse.che.selenium.core.provider.TestDashboardUrlProvider; -import org.eclipse.che.selenium.core.user.DefaultTestUser; -import org.eclipse.che.selenium.core.utils.WaitUtils; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.eclipse.che.selenium.core.webdriver.WebDriverWaitFactory; -import org.eclipse.che.selenium.pageobject.TestWebElementRenderChecker; -import org.eclipse.che.selenium.pageobject.ocp.OpenShiftLoginPage; -import org.eclipse.che.selenium.pageobject.site.LoginPage; -import org.openqa.selenium.By; -import org.openqa.selenium.TimeoutException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.FindBy; -import org.openqa.selenium.support.PageFactory; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.WebDriverWait; - -/** @author Musienko Maxim */ -@Singleton -public class Dashboard { - protected final SeleniumWebDriver seleniumWebDriver; - protected final DefaultTestUser defaultUser; - - private final TestDashboardUrlProvider testDashboardUrlProvider; - private final Entrance entrance; - private final LoginPage loginPage; - private final TestWebElementRenderChecker testWebElementRenderChecker; - private final TestKeycloakSettingsServiceClient testKeycloakSettingsServiceClient; - private final TestUserPreferencesServiceClient testUserPreferencesServiceClient; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final WebDriverWaitFactory webDriverWaitFactory; - private final boolean isMultiuser; - - @Inject private OpenShiftLoginPage openShiftLoginPage; - - @Inject - public Dashboard( - SeleniumWebDriver seleniumWebDriver, - DefaultTestUser defaultUser, - TestDashboardUrlProvider testDashboardUrlProvider, - Entrance entrance, - LoginPage loginPage, - TestWebElementRenderChecker testWebElementRenderChecker, - TestKeycloakSettingsServiceClient testKeycloakSettingsServiceClient, - SeleniumWebDriverHelper seleniumWebDriverHelper, - WebDriverWaitFactory webDriverWaitFactory, - TestUserPreferencesServiceClient testUserPreferencesServiceClient, - @Named("che.multiuser") boolean isMultiuser) { - this.seleniumWebDriver = seleniumWebDriver; - this.defaultUser = defaultUser; - this.testDashboardUrlProvider = testDashboardUrlProvider; - this.entrance = entrance; - this.loginPage = loginPage; - this.testWebElementRenderChecker = testWebElementRenderChecker; - this.testKeycloakSettingsServiceClient = testKeycloakSettingsServiceClient; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - this.webDriverWaitFactory = webDriverWaitFactory; - this.isMultiuser = isMultiuser; - this.testUserPreferencesServiceClient = testUserPreferencesServiceClient; - PageFactory.initElements(seleniumWebDriver, this); - } - - public enum MenuItem { - DASHBOARD("Dashboard"), - WORKSPACES("Workspaces"), - STACKS("Stacks"), - FACTORIES("Factories"), - USERS("Users"), - ORGANIZATIONS("Organizations"), - SETTINGS("Settings"), - CREATE_TEAM("Create Team"); - - private final String title; - - MenuItem(String title) { - this.title = title; - } - } - - public interface Locators { - String DASHBOARD_TOOLBAR_TITLE = "navbar"; - String NAVBAR_NOTIFICATION_CONTAINER = "navbar-notification-container"; - String COLLAPSE_DASH_NAVBAR_BTN = "ide-iframe-button-link"; - String NOTIFICATION_CONTAINER = "che-notification-container"; - String DASHBOARD_ITEM = "dashboard-item"; - String WORKSPACES_ITEM = "workspaces-item"; - String STACKS_ITEM = "stacks-item"; - String FACTORIES_ITEM = "factories-item"; - String ADMINISTRATION_ITEM = "administration-item"; - String ORGANIZATIONS_ITEM = "organization-item"; - String RESENT_WS_NAVBAR = "//div[@class='admin-navbar-menu recent-workspaces']"; - String LEFT_SIDE_BAR = "//div[@class='left-sidebar-container']"; - String USER_PANEL = "navbar-user-panel"; - String DEVELOPERS_FACE_XPATH = "developers-face"; - String USER_NAME = "user-name"; - String LICENSE_NAG_MESSAGE_XPATH = "//div[contains(@class, 'license-message')]"; - String TOOLBAR_TITLE_NAME = - "//div[contains(@class,'che-toolbar')]//span[contains(text(),'%s')]"; - String WORKSPACE_NAME_IN_RECENT_LIST = "//span[@title='%s']"; - } - - @FindBy(id = Locators.DASHBOARD_TOOLBAR_TITLE) - WebElement dashboardTitle; - - @FindBy(id = Locators.COLLAPSE_DASH_NAVBAR_BTN) - WebElement collapseDashNavbarBtn; - - @FindBy(id = Locators.DASHBOARD_ITEM) - WebElement dashboardItem; - - @FindBy(id = Locators.WORKSPACES_ITEM) - WebElement workspacesItem; - - @FindBy(id = Locators.STACKS_ITEM) - WebElement stacksItem; - - @FindBy(id = Locators.FACTORIES_ITEM) - WebElement factoriesItem; - - @FindBy(id = Locators.DEVELOPERS_FACE_XPATH) - WebElement developersFace; - - @FindBy(id = Locators.USER_NAME) - WebElement userName; - - @FindBy(id = Locators.NOTIFICATION_CONTAINER) - WebElement notificationPopUp; - - @FindBy(xpath = Locators.LICENSE_NAG_MESSAGE_XPATH) - WebElement licenseNagMessage; - - /** - * Gets digit which displays near "Workspaces" item on dashboard and means count of the existing - * workspaces. - * - * @return count of workspaces - */ - public int getWorkspacesCountInWorkspacesItem() { - return Integer.parseInt( - seleniumWebDriverHelper - .waitVisibilityAndGetText(workspacesItem) - .replace("Workspaces\n (", "") - .replace(")", "")); - } - - public void waitWorkspacesCountInWorkspacesItem(int expectedCount) { - webDriverWaitFactory - .get() - .until( - (ExpectedCondition) - driver -> expectedCount == getWorkspacesCountInWorkspacesItem()); - } - - /** wait button with drop dawn icon (left top corner) */ - public void waitDashboardToolbarTitle() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC).until(visibilityOf(dashboardTitle)); - } - - /** click on the 'Dashboard' item on the dashboard */ - public void selectDashboardItemOnDashboard() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(dashboardItem)) - .click(); - } - - /** click on the 'Workspaces' item on the dashboard */ - public void selectWorkspacesItemOnDashboard() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(workspacesItem)) - .click(); - } - - /** click on the 'Stacks' item on the dashboard */ - public void selectStacksItemOnDashboard() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(stacksItem)) - .click(); - } - - /** click on the 'Factories' item on the dashboard */ - public void selectFactoriesOnDashbord() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(factoriesItem)) - .click(); - } - - /** - * * wait expected text in the pop up notification - * - * @param notification - */ - public void waitNotificationMessage(String notification) { - new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(textToBePresentInElement(notificationPopUp, notification)); - } - - /** wait closing of notification pop up */ - public void waitNotificationIsClosed() { - WaitUtils.sleepQuietly(1); - new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) - .until(invisibilityOfElementLocated(By.id(Locators.NOTIFICATION_CONTAINER))); - } - - /** wait opening of notification pop up */ - public void waitNotificationIsOpen() { - new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) - .until(visibilityOf(notificationPopUp)); - } - - /** Wait developer avatar is present on dashboard */ - public void waitDeveloperFaceImg() { - new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(visibilityOf(developersFace)); - } - - /** - * Wait user name is present on dashboard - * - * @param name name of user - */ - public Boolean checkUserName(String name) { - return new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(visibilityOf(userName)) - .getText() - .equals(name); - } - - /** - * Get text of nag message which displays at the top of Dashboard, or throw an exception if nag - * message doesn't appear in some time. - */ - public String getLicenseNagMessage() { - return new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(licenseNagMessage)) - .getText(); - } - - /** Wait until nag message disappears. */ - public void waitNagMessageDisappear() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(invisibilityOfElementLocated(By.xpath(Locators.LICENSE_NAG_MESSAGE_XPATH))); - } - - /** Open dashboard as default uses */ - public void open() { - seleniumWebDriver.get(testDashboardUrlProvider.get().toString()); - openShiftLoginPage.login(); - entrance.login(defaultUser); - waitDashboardToolbarTitle(); - } - - /** Open dashboard with provided username and password */ - public void open(String userName, String userPassword) { - seleniumWebDriver.get(testDashboardUrlProvider.get().toString()); - openShiftLoginPage.login(); - if (loginPage.isOpened()) { - loginPage.login(userName, userPassword); - } - } - - public void logout() { - if (!isMultiuser) { - return; - } - - String logoutUrl = - format( - "%s?redirect_uri=%s#/workspaces", - testKeycloakSettingsServiceClient.read().getKeycloakLogoutEndpoint(), - testDashboardUrlProvider.get()); - - seleniumWebDriver.navigate().to(logoutUrl); - } - - /** - * Wait toolbar name is present on dashboard - * - * @param titleName name of user - */ - public void waitToolbarTitleName(String titleName) { - new WebDriverWait(seleniumWebDriver, LOADER_TIMEOUT_SEC) - .until( - visibilityOfElementLocated(By.xpath(format(Locators.TOOLBAR_TITLE_NAME, titleName)))); - } - - /** Return true if workspaces present on the navigation panel */ - public boolean workspacesIsPresent() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.LEFT_SIDE_BAR))); - - List workspaces = - seleniumWebDriver.findElements(By.xpath(Locators.RESENT_WS_NAVBAR)); - return !(workspaces.size() == 0); - } - - public boolean isWorkspacePresentedInRecentList(String workspaceName) { - try { - return new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until( - visibilityOfElementLocated( - By.xpath(format(Locators.WORKSPACE_NAME_IN_RECENT_LIST, workspaceName)))) - .isDisplayed(); - } catch (TimeoutException ex) { - return false; - } - } - - public void clickOnUsernameButton() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.id(Locators.USER_NAME))) - .click(); - } - - public void clickOnAccountItem() { - testWebElementRenderChecker.waitElementIsRendered(By.id("menu_container_1")); - - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath("//span[text()=' Account']"))) - .click(); - } - - public void clickOnLogoutItem() { - testWebElementRenderChecker.waitElementIsRendered(By.id("menu_container_1")); - - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath("//span[text()=' Logout']"))) - .click(); - } - - @PreDestroy - public void close() { - seleniumWebDriver.quit(); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/NewWorkspace.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/NewWorkspace.java deleted file mode 100644 index 2b222c2967..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/NewWorkspace.java +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static java.util.stream.Collectors.toList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.WIDGET_TIMEOUT_SEC; -import static org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Locators.BOTTOM_CREATE_BUTTON_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Locators.DEVFILE_ROW_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Locators.ERROR_MESSAGE; -import static org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Locators.ORGANIZATIONS_LIST_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Locators.TOOLBAR_TITLE_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Locators.TOP_CREATE_BUTTON_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Locators.TOP_DROPDOWN_BUTTON_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.NewWorkspace.Locators.TOP_EDIT_BUTTON_XPATH; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.constant.TestTimeoutsConstants; -import org.eclipse.che.selenium.core.utils.WaitUtils; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.eclipse.che.selenium.core.webdriver.WebDriverWaitFactory; -import org.eclipse.che.selenium.pageobject.TestWebElementRenderChecker; -import org.openqa.selenium.By; -import org.openqa.selenium.TimeoutException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.FindBy; -import org.openqa.selenium.support.PageFactory; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.testng.Assert; - -/** - * @author Ann Shumilova - * @author Ihor Okhrimenko - */ -@Singleton -public class NewWorkspace { - - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final WebDriverWaitFactory webDriverWaitFactory; - private final TestWebElementRenderChecker testWebElementRenderChecker; - private final AddOrImportForm addOrImportForm; - private static final int DEFAULT_TIMEOUT = TestTimeoutsConstants.DEFAULT_TIMEOUT; - - @Inject - public NewWorkspace( - SeleniumWebDriver seleniumWebDriver, - SeleniumWebDriverHelper seleniumWebDriverHelper, - WebDriverWaitFactory webDriverWaitFactory, - TestWebElementRenderChecker testWebElementRenderChecker, - AddOrImportForm addOrImportForm) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - this.webDriverWaitFactory = webDriverWaitFactory; - this.testWebElementRenderChecker = testWebElementRenderChecker; - this.addOrImportForm = addOrImportForm; - PageFactory.initElements(seleniumWebDriver, this); - } - - public interface Locators { - String WORKSPACE_NAME_INPUT = "workspace-name-input"; - String ERROR_MESSAGE = "new-workspace-error-message"; - String TOOLBAR_TITLE_ID = "New_Workspace"; - String DEVFILE_ROW_XPATH = "//div[@data-devfile-id='%s']"; - String MACHINE_NAME = - "//span[contains(@class,'ram-settings-machine-item-item-name') and text()='%s']"; - String ORGANIZATIONS_LIST_ID = "namespace-selector"; - String ORGANIZATION_ITEM = "//md-menu-item[text()='%s']"; - // buttons - String TOP_CREATE_BUTTON_XPATH = "//button[@name='split-button']"; - String TOP_DROPDOWN_BUTTON_XPATH = "//button[@name='dropdown-toggle']"; - String TOP_EDIT_BUTTON_XPATH = "//span[text()='Create & Proceed Editing']"; - String BOTTOM_CREATE_BUTTON_XPATH = "//*[@id='create-workspace-ready-to-go-button']"; - String CUSTOM_WORKSPACE_TAB_XPATH = "//md-tab-item//span[text()='Custom Workspace']"; - String CUSTOM_WORKSPACE_TITLE_XPATH = "//div[@title='Create Custom Workspace']"; - String WORKSPACE_NAME_INPUT_XPATH = "//input[@name='workspaceName']"; - String OPEN_DIVFILES_LIST_XPATH = "//button[contains(@id,'select-single-typeahead-expanded')]"; - String DEVFILE_ITEM_IN_LIST_XPATH = "//button/span[text()='%s']"; - String SELECTED_DEVFILE_ITEM_XPATH = - "//div/input[contains(@id,'select-single-typeahead-expanded')]"; - String CREATE_AND_START_BUTTON_XPATH = "//button[@title='Create & Open']"; - - String DEFVILE_ITEM_XPATH2 = "//div[@devfile='devfile']//b[text()='%s']"; - String GET_STARTED_TAB_XPATH = "//md-tab-item//span[text()='Get Started']"; - String GET_STARTED_TITLE_XPATH = "//div[@title='Getting Started with Eclipse Che']"; - } - - public enum Devfile { - APACHE_CAMEL("Apache Camel based projects on Che 7"), - DOT_NET(".NET Core with Theia IDE"), - GO("Go with Theia IDE"), - JAVA_GRADLE("Java Gradle"), - JAVA_MAVEN("Java Maven"), - PYTHON("Python with Theia IDE"); - - // wsnext-helloworld-openshift - private final String id; - - Devfile(String id) { - this.id = id; - } - - public static Devfile getById(String id) { - Optional first = - asList(values()).stream().filter(devfile -> devfile.getId().equals(id)).findFirst(); - first.orElseThrow( - () -> new RuntimeException(String.format("Devfile with id '%s' not found.", id))); - return first.get(); - } - - public String getId() { - return this.id; - } - } - - @FindBy(id = TOOLBAR_TITLE_ID) - WebElement toolbarTitle; - - @FindBy(id = Locators.WORKSPACE_NAME_INPUT_XPATH) - WebElement workspaceNameInput; - - @FindBy(xpath = BOTTOM_CREATE_BUTTON_XPATH) - WebElement bottomCreateWorkspaceButton; - - @FindBy(xpath = TOP_CREATE_BUTTON_XPATH) - WebElement topCreateWorkspaceButton; - - @FindBy(xpath = TOP_DROPDOWN_BUTTON_XPATH) - WebElement topDropdownButton; - - @FindBy(xpath = TOP_EDIT_BUTTON_XPATH) - WebElement topEditWorkspaceButton; - - public void clickOnGetStartedTab() { - seleniumWebDriverHelper.waitAndClick(By.xpath(Locators.GET_STARTED_TAB_XPATH)); - } - - public void waitGetStartedTabActive() { - seleniumWebDriverHelper.waitVisibility(By.xpath(Locators.GET_STARTED_TAB_XPATH)); - } - - public void selectDevfileFromGetStartedList(Devfile devfile) { - seleniumWebDriverHelper.waitAndClick( - By.xpath(format(Locators.DEFVILE_ITEM_XPATH2, devfile.getId()))); - } - - public void clickOnCustomWorkspacesTab() { - seleniumWebDriverHelper.waitAndClick(By.xpath(Locators.CUSTOM_WORKSPACE_TAB_XPATH)); - } - - public void waitCustomWorkspacesTab() { - seleniumWebDriverHelper.waitVisibility(By.xpath(Locators.CUSTOM_WORKSPACE_TITLE_XPATH)); - } - - public void typeWorkspaceName(String name) { - seleniumWebDriverHelper.waitAndClick(By.xpath(Locators.WORKSPACE_NAME_INPUT_XPATH)); - seleniumWebDriverHelper.setValue(By.xpath(Locators.WORKSPACE_NAME_INPUT_XPATH), name); - Assert.assertEquals(getWorkspaceNameValue(), name); - } - - public String getWorkspaceNameValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue( - By.xpath(Locators.WORKSPACE_NAME_INPUT_XPATH)); - } - - public void openDevfilesList() { - seleniumWebDriverHelper.waitAndClick(By.xpath(Locators.OPEN_DIVFILES_LIST_XPATH)); - } - - public void selectDevfileFromList(Devfile devfile) { - seleniumWebDriverHelper.waitAndClick( - By.xpath(format(Locators.DEVFILE_ITEM_IN_LIST_XPATH, devfile.getId()))); - WaitUtils.sleepQuietly(5); - } - - public String getSelectedDevfileName() { - return seleniumWebDriverHelper.waitVisibilityAndGetText( - By.xpath(Locators.SELECTED_DEVFILE_ITEM_XPATH)); - } - - public void clickOnCreateAndOpenButton() { - seleniumWebDriverHelper.waitAndClick(By.xpath(Locators.CREATE_AND_START_BUTTON_XPATH)); - } - - private void waitButtonDisableState(WebElement button, boolean state) { - seleniumWebDriverHelper.waitAttributeEqualsTo(button, "aria-disabled", Boolean.toString(state)); - } - - private WebElement waitElementByNameAttribute(String nameAttribute) { - return seleniumWebDriverHelper.waitVisibility( - By.xpath(format("//input[@name='%s']", nameAttribute))); - } - - public void waitWorkspaceNameFieldValue(String expectedName) { - seleniumWebDriverHelper.waitSuccessCondition( - (driver) -> getWorkspaceNameValue().equals(expectedName)); - } - - public void waitErrorMessage(String message) { - seleniumWebDriverHelper.waitTextEqualsTo(By.id(ERROR_MESSAGE), message); - } - - public void waitErrorMessageDisappearance() { - seleniumWebDriverHelper.waitInvisibility(By.id(ERROR_MESSAGE)); - } - - public boolean isMachineExists(String machineName) { - return seleniumWebDriver - .findElements(By.xpath(format(Locators.MACHINE_NAME, machineName))) - .size() - > 0; - } - - public void waitToolbar() { - waitToolbar(WIDGET_TIMEOUT_SEC); - } - - public void waitToolbar(int timeout) { - seleniumWebDriverHelper.waitVisibility(By.id(TOOLBAR_TITLE_ID), timeout); - } - - public boolean isDevfileVisible(Devfile devfile) { - return seleniumWebDriver - .findElements(By.xpath(format(DEVFILE_ROW_XPATH, devfile.getId()))) - .size() - > 0; - } - - public void selectDevfile(Devfile devfile) { - waitDevfiles(asList(devfile)); - try { - seleniumWebDriverHelper.waitAndClick(By.xpath(format(DEVFILE_ROW_XPATH, devfile.getId()))); - waitDevfileSelected(devfile); - } catch (TimeoutException ex) { - seleniumWebDriverHelper.waitAndClick(By.xpath(format(DEVFILE_ROW_XPATH, devfile.getId()))); - } - } - - public boolean isCreateWorkspaceButtonEnabled() { - return !Boolean.valueOf( - seleniumWebDriverHelper.waitVisibilityAndGetAttribute( - By.xpath(BOTTOM_CREATE_BUTTON_XPATH), "aria-disabled")); - } - - public void waitTopCreateWorkspaceButtonDisabled() { - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(TOP_CREATE_BUTTON_XPATH), "aria-disabled", "true"); - } - - public void waitTopCreateWorkspaceButtonEnabled() { - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(TOP_CREATE_BUTTON_XPATH), "aria-disabled", "false"); - } - - public void waitBottomCreateWorkspaceButtonEnabled() { - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(BOTTOM_CREATE_BUTTON_XPATH), "aria-disabled", "false"); - } - - public void waitBottomCreateWorkspaceButtonDisabled() { - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(BOTTOM_CREATE_BUTTON_XPATH), "aria-disabled", "true"); - } - - public void clickOnCreateButtonAndOpenInIDE() { - // need to move cursor to button to avoid failure https://github.com/eclipse/che/issues/12309 - seleniumWebDriverHelper.waitVisibility(bottomCreateWorkspaceButton); - seleniumWebDriverHelper.moveCursorTo(bottomCreateWorkspaceButton); - bottomCreateWorkspaceButton.click(); - } - - public void clickOnCreateButtonAndEditWorkspace() { - waitTopCreateButton(); - - seleniumWebDriverHelper.waitAndClick(topDropdownButton); - seleniumWebDriverHelper.waitAndClick(topEditWorkspaceButton); - } - - public void clickOnBottomCreateButton() { - seleniumWebDriverHelper.waitAndClick(bottomCreateWorkspaceButton); - } - - public void openOrganizationsList() { - seleniumWebDriverHelper.waitAndClick(By.id(ORGANIZATIONS_LIST_ID)); - } - - public void selectOrganizationFromList(String organizationName) { - seleniumWebDriverHelper.waitAndClick( - By.xpath(format(Locators.ORGANIZATION_ITEM, organizationName))); - } - - public WebElement waitTopCreateButton(int timeout) { - return seleniumWebDriverHelper.waitVisibility(By.xpath(TOP_CREATE_BUTTON_XPATH), timeout); - } - - public WebElement waitTopCreateButton() { - return waitTopCreateButton(DEFAULT_TIMEOUT); - } - - public void clickOnTopCreateButton() { - waitTopCreateButton().click(); - } - - public WebElement waitNameField(int timeout) { - return seleniumWebDriverHelper.waitVisibility(workspaceNameInput, timeout); - } - - public WebElement waitNameField() { - return waitNameField(DEFAULT_TIMEOUT); - } - - public void waitBottomCreateButton(int timeout) { - seleniumWebDriverHelper.waitVisibility(bottomCreateWorkspaceButton, timeout); - } - - public void waitBottomCreateButton() { - waitBottomCreateButton(DEFAULT_TIMEOUT); - } - - public void waitMainActionButtons(int timeout) { - waitTopCreateButton(timeout); - addOrImportForm.waitAddOrImportProjectButton(timeout); - waitBottomCreateButton(timeout); - } - - public void waitMainActionButtons() { - waitMainActionButtons(DEFAULT_TIMEOUT); - } - - public void waitPageLoad(int timeout) { - waitToolbar(timeout); - waitNameField(timeout); - waitMainActionButtons(timeout); - } - - public void waitPageLoad() { - waitPageLoad(DEFAULT_TIMEOUT); - } - - public List getAvailableDevfiles() { - return seleniumWebDriverHelper - .waitPresenceOfAllElements(By.xpath("//div[@data-devfile-id]")) - .stream() - .map(webElement -> Devfile.getById(webElement.getAttribute("data-devfile-id"))) - .collect(toList()); - } - - public void waitDevfileSelected(Devfile devfile) { - String selectedDevfileXpath = - format( - "//div[@data-devfile-id='%s' and contains(@class, 'devfile-selector-item-selected')]", - devfile.getId()); - seleniumWebDriverHelper.waitVisibility(By.xpath(selectedDevfileXpath)); - } - - public List getVisibleDevfiles() { - return seleniumWebDriverHelper - .waitPresenceOfAllElements(By.xpath("//div[@data-devfile-id]")) - .stream() - .filter(seleniumWebDriverHelper::isVisible) - .map(webElement -> Devfile.getById(webElement.getAttribute("data-devfile-id"))) - .collect(Collectors.toList()); - } - - public void waitVisibleDevfiles(List expectedVisibleDevfiles) { - webDriverWaitFactory - .get() - .until( - (ExpectedCondition) - driver -> getVisibleDevfiles().equals(expectedVisibleDevfiles)); - } - - public void waitDevfiles(List expectedDevfiles) { - expectedDevfiles.forEach( - devfile -> - seleniumWebDriverHelper.waitPresence( - By.xpath(format("//div[@data-devfile-id='%s']", devfile.getId())))); - } - - public void waitDevfilesCount(int expectedCount) { - webDriverWaitFactory - .get() - .until((ExpectedCondition) driver -> expectedCount == getAvailableDevfilesCount()); - } - - public int getAvailableDevfilesCount() { - return getAvailableDevfiles().size(); - } - - public void waitDevfilesNotPresent(List devfilesIdForChecking) { - devfilesIdForChecking.forEach( - devfile -> - webDriverWaitFactory - .get() - .until( - (ExpectedCondition) - driver -> !getAvailableDevfiles().contains(devfile))); - } - - public void waitDevfilesOrder(List expectedOrder) { - webDriverWaitFactory - .get() - .until((ExpectedCondition) driver -> expectedOrder.equals(getAvailableDevfiles())); - } - - public void clickNameButton() { - seleniumWebDriverHelper.waitAndClick(By.xpath("//div[@che-column-title='Name']/div")); - } - - public void clickOnTitlePlaceCoordinate() { - seleniumWebDriverHelper.moveCursorTo( - seleniumWebDriverHelper.waitPresence(By.id(TOOLBAR_TITLE_ID))); - seleniumWebDriverHelper.getAction().click().perform(); - } - - public void clickOnAddStackButton() { - seleniumWebDriverHelper.waitAndClick(By.id("add-stack-button")); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/ProjectOptions.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/ProjectOptions.java deleted file mode 100644 index 0c70213223..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/ProjectOptions.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.pageobject.dashboard.ProjectOptions.Locators.CANCEL_PROJECT_OPTIONS_BUTTON_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.ProjectOptions.Locators.PROJECT_NAME_ERROR_MESSAGE_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.ProjectOptions.Locators.REPOSITORY_URL_ERROR_MESSAGE_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.ProjectOptions.Locators.SAVE_PROJECT_OPTIONS_BUTTON_XPATH; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.PageFactory; - -/** @author Ihor Okhrimenko */ -@Singleton -public class ProjectOptions { - - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - - @Inject - ProjectOptions( - SeleniumWebDriver seleniumWebDriver, SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - PageFactory.initElements(seleniumWebDriver, this); - } - - public interface Locators { - String CANCEL_PROJECT_OPTIONS_BUTTON_XPATH = "//button[@name='cancelButton']"; - String SAVE_PROJECT_OPTIONS_BUTTON_XPATH = "//che-button-primary//button[@name='saveButton']"; - String PROJECT_NAME_ERROR_MESSAGE_XPATH = - "//div[@che-name='projectName']//div[@id='new-workspace-error-message']/div"; - String REPOSITORY_URL_ERROR_MESSAGE_XPATH = - "//div[@che-name='projectGitURL']//div[@id='new-workspace-error-message']/div"; - } - - public void waitProjectOptionsForm() { - waitProjectNameField(); - waitDescriptionField(); - waitRepositoryUrlField(); - } - - public WebElement waitProjectNameField() { - return waitElementByNameAttribute("projectName"); - } - - public void waitProjectNameFieldValue(String expectedValue) { - seleniumWebDriverHelper.waitValueEqualsTo(waitProjectNameField(), expectedValue); - } - - public void setValueOfNameField(String value) { - seleniumWebDriverHelper.setValue(waitProjectNameField(), value); - } - - private WebElement waitElementByNameAttribute(String nameAttribute) { - return seleniumWebDriverHelper.waitVisibility( - By.xpath(format("//input[@name='%s']", nameAttribute))); - } - - public WebElement waitDescriptionField() { - return waitElementByNameAttribute("projectDescription"); - } - - public void waitDescriptionFieldValue(String expectedValue) { - seleniumWebDriverHelper.waitValueEqualsTo(waitDescriptionField(), expectedValue); - } - - public void typeTextInDescriptionField(String text) { - seleniumWebDriverHelper.setValue(waitDescriptionField(), text); - } - - public WebElement waitRepositoryUrlField() { - return waitElementByNameAttribute("projectGitURL"); - } - - public void typeTextInRepositoryUrlField(String value) { - seleniumWebDriverHelper.setValue(waitRepositoryUrlField(), value); - } - - public void waitRepositoryUrlFieldValue(String expectedValue) { - seleniumWebDriverHelper.waitValueEqualsTo(waitRepositoryUrlField(), expectedValue); - } - - public WebElement waitRemoveButton() { - return seleniumWebDriverHelper.waitVisibility(By.xpath("//button[@name='removeButton']")); - } - - public void clickOnRemoveButton() { - seleniumWebDriverHelper.waitAndClick(waitRemoveButton()); - } - - public WebElement waitSaveButton() { - return seleniumWebDriverHelper.waitVisibility(By.xpath(SAVE_PROJECT_OPTIONS_BUTTON_XPATH)); - } - - public WebElement waitCancelButton() { - return seleniumWebDriverHelper.waitVisibility(By.xpath(CANCEL_PROJECT_OPTIONS_BUTTON_XPATH)); - } - - public void clickOnSaveButton() { - waitSaveButton().click(); - } - - public void clickOnCancelButton() { - waitCancelButton().click(); - } - - private void waitButtonDisableState(WebElement button, boolean state) { - seleniumWebDriverHelper.waitAttributeEqualsTo(button, "aria-disabled", Boolean.toString(state)); - } - - public void waitSaveButtonEnabling() { - waitButtonDisableState(waitSaveButton(), false); - } - - public void waitSaveButtonDisabling() { - waitButtonDisableState(waitSaveButton(), true); - } - - public void waitCancelButtonEnabling() { - waitButtonDisableState(waitCancelButton(), false); - } - - public void waitCancelButtonDisabling() { - waitButtonDisableState(waitCancelButton(), true); - } - - public void waitProjectNameErrorMessage(String expectedMessage) { - seleniumWebDriverHelper.waitTextEqualsTo( - By.xpath(PROJECT_NAME_ERROR_MESSAGE_XPATH), expectedMessage); - } - - public void waitProjectNameErrorDisappearance() { - seleniumWebDriverHelper.waitInvisibility(By.xpath(PROJECT_NAME_ERROR_MESSAGE_XPATH)); - } - - public void waitRepositoryUrlErrorMessage(String expectedMessage) { - seleniumWebDriverHelper.waitTextEqualsTo( - By.xpath(REPOSITORY_URL_ERROR_MESSAGE_XPATH), expectedMessage); - } - - public void waitRepositoryUrlErrorDisappearance() { - seleniumWebDriverHelper.waitInvisibility(By.xpath(REPOSITORY_URL_ERROR_MESSAGE_XPATH)); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/ProjectSourcePage.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/ProjectSourcePage.java deleted file mode 100644 index 0d2d189721..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/ProjectSourcePage.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.ELEMENT_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOADER_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.REDRAW_UI_ELEMENTS_TIMEOUT_SEC; -import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable; -import static org.openqa.selenium.support.ui.ExpectedConditions.invisibilityOfElementLocated; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.action.ActionsFactory; -import org.openqa.selenium.By; -import org.openqa.selenium.TimeoutException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.FindBy; -import org.openqa.selenium.support.PageFactory; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.WebDriverWait; - -/** @author Ann Shumilova */ -@Singleton -public class ProjectSourcePage { - - private final SeleniumWebDriver seleniumWebDriver; - private final ActionsFactory actionsFactory; - - @Inject - public ProjectSourcePage(SeleniumWebDriver seleniumWebDriver, ActionsFactory actionsFactory) { - this.seleniumWebDriver = seleniumWebDriver; - this.actionsFactory = actionsFactory; - PageFactory.initElements(seleniumWebDriver, this); - } - - public enum Sources { - SAMPLES("samples"), - BLANK("blank"), - GIT("git"), - GITHUB("github"), - ZIP("zip"); - - private final String title; - - Sources(String title) { - this.title = title; - } - } - - private interface Locators { - String ADD_OR_IMPORT_PROJECT_BUTTON = "ADD_PROJECT"; - String PROJECT_SOURCE_SELECTOR = "project-source-selector"; - String SAMPLES_BUTTON = "%s-button"; - String SAMPLE_CHECKBOX = "//div[@id='sample-%s']/md-checkbox"; - String TEMPLATE_NAME = "//span[contains(@class,'template-selector-item-name')]"; - String TEMPLATE_DESCRIPTION = "//span[contains(@class,'template-selector-item-description')]"; - String GIT_REPO_XPATH = "remote-git-url-input"; - String ZIP_XPATH = "remote-zip-url-input"; - String ZIP_SKIP_ROOT_XPATH = "zip-skip-root-folder-checkbox"; - String ADD_PROJECT_BUTTON = "add-project-button"; - String CANCEL_BUTTON = "cancelButton"; - String SAVE_BUTTON = "saveButton"; - String REMOVE_BUTTON = "removeButton"; - - String PROJECT_NAME = "//input[@name='projectName']"; - String PROJECT_DESCRIPTION = "//input[@name='projectDescription']"; - String CONNECT_GITHUB_ACCOUNT_BUTTON = - "//*[@id='import-github-project-button']/*[contains(@class, 'che-button')]"; - String GITHUB_PROJECTS_LIST = "//*[contains(@class,'import-github-project-repositories-list')]"; - String GITHUB_PROJECT_CHECKBOX = "//md-checkbox[@aria-label='GitHub repository %s']"; - - String LOGIN_FIELD = "login_field"; - String PASS_FIELD = "password"; - String SIGN_IN_BTN = "input[value='Sign in']"; - String AUTHORIZE_BUTTON = "//button[@id='js-oauth-authorize-btn']"; - } - - public interface Template { - String WEB_JAVA_SPRING = "web-java-spring"; - String CONSOLE_JAVA_SIMPLE = "console-java-simple"; - String WEB_JAVA_PETCLINIC = "web-java-petclinic"; - String CONSOLE_PYTHON3_SIMPLE = "console-python3-simple"; - } - - @FindBy(id = Locators.ADD_OR_IMPORT_PROJECT_BUTTON) - WebElement addOrImportProjectButton; - - @FindBy(id = Locators.PROJECT_SOURCE_SELECTOR) - WebElement projectSourceSelector; - - @FindBy(id = Locators.GIT_REPO_XPATH) - WebElement gitRepositoryInput; - - @FindBy(id = Locators.ZIP_XPATH) - WebElement zipLocationInput; - - @FindBy(id = Locators.ZIP_SKIP_ROOT_XPATH) - WebElement zipSkipRoot; - - @FindBy(name = Locators.CANCEL_BUTTON) - WebElement cancelButton; - - @FindBy(name = Locators.SAVE_BUTTON) - WebElement saveButton; - - @FindBy(name = Locators.REMOVE_BUTTON) - WebElement removeButton; - - @FindBy(id = Locators.ADD_PROJECT_BUTTON) - WebElement addProjectButton; - - @FindBy(id = Locators.LOGIN_FIELD) - WebElement loginField; - - @FindBy(id = Locators.PASS_FIELD) - WebElement passField; - - @FindBy(css = Locators.SIGN_IN_BTN) - WebElement signInBtn; - - @FindBy(xpath = Locators.AUTHORIZE_BUTTON) - WebElement authorizeBtn; - - public void clickOnAddOrImportProjectButton() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(visibilityOf(addOrImportProjectButton)) - .click(); - } - - // wait that the Project Source Selector visible - public void waitOpened() { - new WebDriverWait(seleniumWebDriver, LOADER_TIMEOUT_SEC) - .until(visibilityOf(projectSourceSelector)); - } - - /** - * select type of created project - * - * @param source is type of the existing templates - */ - public void selectSourceTab(Sources source) { - WebElement sourceTab = - seleniumWebDriver.findElement(By.id(String.format(Locators.SAMPLES_BUTTON, source.title))); - sourceTab.click(); - } - - /** - * Select project sample - * - * @param name name of sample - */ - public void selectSample(String name) { - WebElement sample = - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(format(Locators.SAMPLE_CHECKBOX, name)))); - sample.click(); - } - - /** - * Enter Git URL for project in the 'New Project' tab - * - * @param url URL for project on git repository - */ - public void typeGitRepositoryLocation(String url) { - gitRepositoryInput.clear(); - gitRepositoryInput.sendKeys(url); - } - - /** - * Enter ZIP URL for project in the 'New Project' tab - * - * @param url URL for zip archive - */ - public void typeZipLocation(String url) { - zipLocationInput.clear(); - zipLocationInput.sendKeys(url); - } - - public void skipRootFolder() { - zipSkipRoot.click(); - } - - public void clickOnAddProjectButton() { - addProjectButton.click(); - } - - public void clickOnCancelChangesButton() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(cancelButton)) - .click(); - } - - public void clickOnSaveChangesButton() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(saveButton)) - .click(); - } - - public void clickOnRemoveProjectButton() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(removeButton)) - .click(); - } - - public void waitCreatedProjectButton(String projectName) { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.id(projectName))); - } - - public boolean isProjectNotExists(String projectName) { - return new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(invisibilityOfElementLocated(By.id(projectName))); - } - - public void clickOnCreateProjectButton(String projectName) { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.id(projectName))) - .click(); - } - - public String getProjectName() { - return new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.PROJECT_NAME))) - .getAttribute("value"); - } - - public void changeProjectName(String name) { - WebElement webElement = seleniumWebDriver.findElement(By.xpath(Locators.PROJECT_NAME)); - webElement.clear(); - webElement.sendKeys(name); - } - - public String getProjectDescription() { - return new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.PROJECT_DESCRIPTION))) - .getAttribute("value"); - } - - public void changeProjectDescription(String description) { - WebElement webElement = seleniumWebDriver.findElement(By.xpath(Locators.PROJECT_DESCRIPTION)); - webElement.clear(); - webElement.sendKeys(description); - } - - public boolean isConnectGitHubAccountButtonVisible() { - return new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.CONNECT_GITHUB_ACCOUNT_BUTTON))) - .isDisplayed(); - } - - public void clickOnConnectGithubAccountButton() { - new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.CONNECT_GITHUB_ACCOUNT_BUTTON))) - .click(); - } - - public boolean isGithubProjectsListDisplayed() { - try { - waitGithubProjectList(); - return true; - } catch (TimeoutException ex) { - return false; - } - } - - public void waitGithubProjectList() { - new WebDriverWait(seleniumWebDriver, LOADER_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.GITHUB_PROJECTS_LIST))) - .isDisplayed(); - } - - public void selectProjectFromList(String projectName) { - WebElement project = - seleniumWebDriver.findElement( - By.xpath(format(Locators.GITHUB_PROJECT_CHECKBOX, projectName))); - actionsFactory.createAction(seleniumWebDriver).moveToElement(project).perform(); - project.click(); - } - - /** Wait web elements on github login form. */ - public void waitAuthorizationPageOpened() { - new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) - .until( - (ExpectedCondition) - elem -> - loginField.isDisplayed() && passField.isDisplayed() && signInBtn.isDisplayed()); - } - - /** - * type login to login field - * - * @param login - */ - public void typeLogin(String login) { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC).until(visibilityOf(loginField)); - loginField.sendKeys(login); - } - - /** - * type password to password field - * - * @param password - */ - public void typePassword(String password) { - passField.sendKeys(password); - } - - /** wait closing github login form */ - public void waitClosingLoginPage() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(invisibilityOfElementLocated(By.id(Locators.PASS_FIELD))); - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(invisibilityOfElementLocated(By.id(Locators.LOGIN_FIELD))); - } - - /** click on the SignIn button on github auth form */ - public void clickOnSignInButton() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(elementToBeClickable(signInBtn)); - signInBtn.click(); - } - - /** - * wait and check if Authorization button is present. - * - * @return true if button is present, false otherwise - */ - public boolean isAuthorizeButtonPresent() { - try { - waitAuthorizeBtn(); - return true; - } catch (Exception e) { - return false; - } - } - - /** wait for Authorize button. */ - public void waitAuthorizeBtn() { - new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC).until(visibilityOf(authorizeBtn)); - } - - /** click on Authorize button */ - public void clickOnAuthorizeBtn() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(elementToBeClickable(authorizeBtn)); - authorizeBtn.click(); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/Account.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/Account.java deleted file mode 100644 index 3cc677a823..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/Account.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.account; - -import static java.lang.String.format; - -import com.google.inject.Singleton; -import java.util.Objects; - -/** @author Igor Ohrimenko */ -@Singleton -public class Account { - private String login; - private String email; - private String firstName; - private String lastName; - - public Account withLogin(String login) { - this.login = login; - return this; - } - - public Account withEmail(String email) { - this.email = email; - return this; - } - - public Account withFirstName(String firstName) { - this.firstName = firstName; - return this; - } - - public Account withLastName(String lastName) { - this.lastName = lastName; - return this; - } - - public String getLogin() { - return this.login; - } - - public String getEmail() { - return this.email; - } - - public String getFirstName() { - return this.firstName; - } - - public String getLastName() { - return this.lastName; - } - - @Override - public boolean equals(Object accountToCompare) { - return accountToCompare instanceof Account - && Objects.equals(login, ((Account) accountToCompare).getLogin()) - && Objects.equals(email, ((Account) accountToCompare).getEmail()) - && Objects.equals(firstName, ((Account) accountToCompare).getFirstName()) - && Objects.equals(lastName, ((Account) accountToCompare).getLastName()); - } - - @Override - public int hashCode() { - return Objects.hash(login, email, firstName, lastName); - } - - @Override - public String toString() { - return format( - "%s{login=%s, email=%s, firstName=%s, lastName=%s}", - this.getClass().getSimpleName(), - this.getLogin(), - this.getEmail(), - getFirstName(), - getLastName()); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/DashboardAccount.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/DashboardAccount.java deleted file mode 100644 index 76f3ee3521..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/DashboardAccount.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.account; - -import static java.util.Arrays.asList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.ELEMENT_TIMEOUT_SEC; -import static org.eclipse.che.selenium.pageobject.dashboard.account.DashboardAccount.Locators.EDIT_BUTTON; -import static org.eclipse.che.selenium.pageobject.dashboard.account.DashboardAccount.Locators.EMAIL_FIELD; -import static org.eclipse.che.selenium.pageobject.dashboard.account.DashboardAccount.Locators.FIRST_NAME_FIELD; -import static org.eclipse.che.selenium.pageobject.dashboard.account.DashboardAccount.Locators.LAST_NAME_FIELD; -import static org.eclipse.che.selenium.pageobject.dashboard.account.DashboardAccount.Locators.LOGIN_FIELD; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; - -/** @author Igor Ohrimenko */ -@Singleton -public class DashboardAccount { - - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - - @Inject - public DashboardAccount(SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - } - - interface Locators { - String EMAIL_FIELD = "email"; - String LOGIN_FIELD = "login_name"; - String FIRST_NAME_FIELD = "first_name"; - String LAST_NAME_FIELD = "last_name"; - String EDIT_BUTTON = "editButton"; - String TITLE_ID = "Account"; - } - - public Account getAllFields() { - Account account = new Account(); - - account.withEmail(getEmailFieldValue()); - account.withLogin(getLoginFieldValue()); - account.withFirstName(getFirstNameFieldValue()); - account.withLastName(getLastNameFieldValue()); - - return account; - } - - public String getEmailFieldValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.name(EMAIL_FIELD)); - } - - public String getLoginFieldValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.name(LOGIN_FIELD)); - } - - public String getFirstNameFieldValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.name(FIRST_NAME_FIELD)); - } - - public String getLastNameFieldValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.name(LAST_NAME_FIELD)); - } - - public String getTitle() { - return seleniumWebDriverHelper.waitVisibility(By.id(Locators.TITLE_ID)).getText(); - } - - public void clickOnEditButton() { - seleniumWebDriverHelper.waitAndClick(By.name(EDIT_BUTTON)); - } - - public void waitPageIsLoaded() { - asList(EMAIL_FIELD, LOGIN_FIELD, FIRST_NAME_FIELD, LAST_NAME_FIELD, EDIT_BUTTON) - .forEach( - locator -> - seleniumWebDriverHelper.waitVisibility(By.name(locator), ELEMENT_TIMEOUT_SEC)); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakAccountPage.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakAccountPage.java deleted file mode 100644 index 71fbf9e43a..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakAccountPage.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.account; - -import static java.util.Arrays.asList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakAccountPage.AccountPageLocators.CANCEL_BUTTON; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakAccountPage.AccountPageLocators.EMAIL_FIELD_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakAccountPage.AccountPageLocators.ERROR_ALERT; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakAccountPage.AccountPageLocators.FIRST_NAME_FIELD_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakAccountPage.AccountPageLocators.LAST_NAME_FIELD_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakAccountPage.AccountPageLocators.SAVE_BUTTON; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakAccountPage.AccountPageLocators.SUCCESS_ALERT; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakAccountPage.AccountPageLocators.USERNAME_FIELD_ID; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.WebDriverWait; - -/** @author Igor Ohrimenko */ -@Singleton -public class KeycloakAccountPage { - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final KeycloakHeaderButtons keycloakHeaderButtons; - private final WebDriverWait loadPageWait; - - @Inject - protected KeycloakAccountPage( - SeleniumWebDriver seleniumWebDriver, - SeleniumWebDriverHelper seleniumWebDriverHelper, - KeycloakHeaderButtons keycloakHeaderButtons) { - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - this.keycloakHeaderButtons = keycloakHeaderButtons; - this.loadPageWait = new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC); - } - - interface AccountPageLocators { - String USERNAME_FIELD_ID = "username"; - String EMAIL_FIELD_ID = "email"; - String FIRST_NAME_FIELD_ID = "firstName"; - String LAST_NAME_FIELD_ID = "lastName"; - - String SAVE_BUTTON = "//button[text()='Save']"; - String CANCEL_BUTTON = "//button[text()='Cancel']"; - - String SUCCESS_ALERT = "//div[@class='alert alert-success']"; - String ERROR_ALERT = "//div[@class='alert alert-error']"; - } - - public void waitAccountPageIsLoaded() { - keycloakHeaderButtons.waitAllHeaderButtonsAreVisible(); - waitAllBodyFieldsAndButtonsIsVisible(); - } - - public Account getAllFields() { - return new Account() - .withLogin(getUserNameValue()) - .withEmail(getEmailValue()) - .withFirstName(getFirstNameValue()) - .withLastName(getLastNameValue()); - } - - public String getUserNameValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.id(USERNAME_FIELD_ID)); - } - - public String getEmailValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.id(EMAIL_FIELD_ID)); - } - - public String getFirstNameValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.id(FIRST_NAME_FIELD_ID)); - } - - public String getLastNameValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.id(LAST_NAME_FIELD_ID)); - } - - public void setUserNameValue(String value) { - seleniumWebDriverHelper.setValue(By.id(USERNAME_FIELD_ID), value); - } - - public void setEmailValue(String value) { - seleniumWebDriverHelper.setValue(By.id(EMAIL_FIELD_ID), value); - } - - public void setFirstNameValue(String value) { - seleniumWebDriverHelper.setValue(By.id(FIRST_NAME_FIELD_ID), value); - } - - public void setLastNameValue(String value) { - seleniumWebDriverHelper.setValue(By.id(LAST_NAME_FIELD_ID), value); - } - - public boolean usernameFieldIsDisabled() { - return seleniumWebDriverHelper - .waitVisibility(By.id(USERNAME_FIELD_ID)) - .getAttribute("disabled") - .equals("true"); - } - - public void clickOnSaveButton() { - seleniumWebDriverHelper.waitAndClick(By.xpath(SAVE_BUTTON)); - } - - public void clickOnCancelButton() { - seleniumWebDriverHelper.waitAndClick(By.xpath(CANCEL_BUTTON)); - } - - public void waitTextInErrorAlert(String expectedText) { - loadPageWait.until( - (ExpectedCondition) - driver -> - seleniumWebDriverHelper - .waitVisibility(By.xpath(ERROR_ALERT)) - .getText() - .equals(expectedText)); - } - - public void waitTextInSuccessAlert(String expectedText) { - loadPageWait.until( - (ExpectedCondition) - driver -> - seleniumWebDriverHelper - .waitVisibility(By.xpath(SUCCESS_ALERT)) - .getText() - .equals(expectedText)); - } - - private void waitAllBodyFieldsAndButtonsIsVisible() { - asList( - By.xpath(SAVE_BUTTON), - By.xpath(CANCEL_BUTTON), - By.id(USERNAME_FIELD_ID), - By.id(EMAIL_FIELD_ID), - By.id(FIRST_NAME_FIELD_ID), - By.id(LAST_NAME_FIELD_ID)) - .forEach(locator -> seleniumWebDriverHelper.waitVisibility(locator)); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakFederatedIdentitiesPage.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakFederatedIdentitiesPage.java deleted file mode 100644 index ea5d4e539a..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakFederatedIdentitiesPage.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.account; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakFederatedIdentitiesPage.Locators.GITHUB_INPUT_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakFederatedIdentitiesPage.Locators.GITHUB_REMOVE_BUTTON_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakFederatedIdentitiesPage.Locators.TITLE_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakPasswordPage.PasswordLocators.SUCCESS_ALERT; -import static org.openqa.selenium.By.xpath; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import javax.ws.rs.NotSupportedException; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.client.keycloak.TestKeycloakSettingsServiceClient; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.WebDriverWait; - -/** @author Dmytro Nochevnov */ -@Singleton -public class KeycloakFederatedIdentitiesPage { - - private static final String IDENTITY_PROVIDER_REMOVED_SUCCESSFULLY_MESSAGE = - "Identity provider removed successfully."; - - private static final NotSupportedException NOT_SUPPORTED_EXCEPTION = - new NotSupportedException( - "Keycloak Federated Identities page can be used in Multi User Eclipse Che only."); - - private final WebDriverWait loadPageWait; - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final KeycloakHeaderButtons keycloakHeaderButtons; - private final TestKeycloakSettingsServiceClient testKeycloakSettingsServiceClient; - - @Inject - public KeycloakFederatedIdentitiesPage( - SeleniumWebDriver seleniumWebDriver, - SeleniumWebDriverHelper seleniumWebDriverHelper, - KeycloakHeaderButtons keycloakHeaderButtons, - TestKeycloakSettingsServiceClient testKeycloakSettingsServiceClient) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - this.keycloakHeaderButtons = keycloakHeaderButtons; - this.testKeycloakSettingsServiceClient = testKeycloakSettingsServiceClient; - this.loadPageWait = new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC); - } - - interface Locators { - String GITHUB_REMOVE_BUTTON_ID = "remove-link-github"; - String TITLE_XPATH = "//div[@id='tab-content']//h2[text()='Federated Identities']"; - String GITHUB_INPUT_XPATH = "*//div[@id='federated-identities']//input"; - } - - public void open() { - String identityPageUrl = - format( - "%s/identity", testKeycloakSettingsServiceClient.read().getKeycloakProfileEndpoint()); - - seleniumWebDriver.navigate().to(identityPageUrl); - waitPageIsLoaded(); - } - - public void ensureGithubIdentityIsAbsent() { - if (!getGitHubIdentityFieldValue().isEmpty()) { - removeGithubIdentity(); - } - } - - public String getGitHubIdentityFieldValue() { - return seleniumWebDriverHelper.waitVisibilityAndGetValue(By.xpath(GITHUB_INPUT_XPATH)); - } - - public void removeGithubIdentity() { - seleniumWebDriverHelper.waitAndClick(By.id(GITHUB_REMOVE_BUTTON_ID)); - waitTextInSuccessAlert(IDENTITY_PROVIDER_REMOVED_SUCCESSFULLY_MESSAGE); - } - - private void waitPageIsLoaded() { - keycloakHeaderButtons.waitAllHeaderButtonsAreVisible(); - waitAllBodyFieldsAndButtonsIsVisible(); - } - - private void waitTextInSuccessAlert(String expectedText) { - loadPageWait.until( - (ExpectedCondition) - driver -> - seleniumWebDriverHelper - .waitVisibility(xpath(SUCCESS_ALERT)) - .getText() - .equals(expectedText)); - } - - private void waitAllBodyFieldsAndButtonsIsVisible() { - asList(xpath(TITLE_XPATH)).forEach(locator -> seleniumWebDriverHelper.waitVisibility(locator)); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakHeaderButtons.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakHeaderButtons.java deleted file mode 100644 index 1bb4335b36..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakHeaderButtons.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.account; - -import static org.openqa.selenium.By.xpath; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.Arrays; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; - -/** @author Igor Ohrimenko */ -@Singleton -public class KeycloakHeaderButtons { - private enum Button { - ACCOUNT("Account"), - PASSWORD("Password"), - AUTHENTICATOR("Authenticator"), - FEDERATED_IDENTITIES("Federated Identity"), - SESSIONS("Sessions"), - APPLICATIONS("Applications"); - - private static final String BUTTON_XPATH_TEMPLATE = "//div[@id='tabs-menu']//a[text()='%s']"; - - private final String text; - - Button(String text) { - this.text = text; - } - - private By getXpath() { - return xpath(String.format(BUTTON_XPATH_TEMPLATE, text)); - } - } - - private SeleniumWebDriverHelper seleniumWebDriverHelper; - - @Inject - public KeycloakHeaderButtons(SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - } - - /** click on the "Account" button in the header oh the page */ - public void clickOnAccountButton() { - clickOnButton(Button.ACCOUNT); - } - - /** click on the "Password" button in the header oh the page */ - public void clickOnPasswordButton() { - clickOnButton(Button.PASSWORD); - } - - /** click on the "Authenticator" button in the header oh the page */ - public void clickOnAuthenticatorButton() { - clickOnButton(Button.AUTHENTICATOR); - } - - /** click on the "Federated Identity" button in the header oh the page */ - public void clickOnFederatedIdentitiesButton() { - clickOnButton(Button.FEDERATED_IDENTITIES); - } - - /** click on the "Session" button in the header oh the page */ - public void clickOnSessionsButton() { - clickOnButton(Button.SESSIONS); - } - - /** click on the "Application" button in the header oh the page */ - public void clickOnApplicationsButton() { - clickOnButton(Button.APPLICATIONS); - } - - private void clickOnButton(Button button) { - seleniumWebDriverHelper.waitAndClick(button.getXpath()); - } - - /** wait until all buttons which placed in the header of the page will be visible */ - public void waitAllHeaderButtonsAreVisible() { - Arrays.asList( - Button.ACCOUNT.getXpath(), - Button.PASSWORD.getXpath(), - Button.AUTHENTICATOR.getXpath(), - Button.SESSIONS.getXpath(), - Button.APPLICATIONS.getXpath()) - .forEach(locator -> seleniumWebDriverHelper.waitVisibility(locator)); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakPasswordPage.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakPasswordPage.java deleted file mode 100644 index 43c07a2848..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/account/KeycloakPasswordPage.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.account; - -import static java.util.Arrays.asList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakPasswordPage.PasswordLocators.ERROR_ALERT; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakPasswordPage.PasswordLocators.NEW_PASSWORD_CONFIRMATION_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakPasswordPage.PasswordLocators.NEW_PASSWORD_FIELD_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakPasswordPage.PasswordLocators.PASSWORD_FIELD_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakPasswordPage.PasswordLocators.SAVE_BUTTON; -import static org.eclipse.che.selenium.pageobject.dashboard.account.KeycloakPasswordPage.PasswordLocators.SUCCESS_ALERT; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; -import org.openqa.selenium.support.ui.ExpectedCondition; -import org.openqa.selenium.support.ui.WebDriverWait; - -/** @author Igor Ohrimenko */ -@Singleton -public class KeycloakPasswordPage { - private final WebDriverWait loadPageWait; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final KeycloakHeaderButtons keycloakHeaderButtons; - - @Inject - public KeycloakPasswordPage( - SeleniumWebDriver seleniumWebDriver, - SeleniumWebDriverHelper seleniumWebDriverHelper, - KeycloakHeaderButtons keycloakHeaderButtons) { - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - this.keycloakHeaderButtons = keycloakHeaderButtons; - this.loadPageWait = new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC); - } - - interface PasswordLocators { - String PASSWORD_FIELD_ID = "password"; - String NEW_PASSWORD_FIELD_ID = "password-new"; - String NEW_PASSWORD_CONFIRMATION_ID = "password-confirm"; - - String SAVE_BUTTON = "//button[text()='Save']"; - - String ERROR_ALERT = "//div[@class='alert alert-error']"; - String SUCCESS_ALERT = "//div[@class='alert alert-success']"; - } - - public void waitPasswordPageIsLoaded() { - keycloakHeaderButtons.waitAllHeaderButtonsAreVisible(); - waitAllBodyFieldsAndButtonsIsVisible(); - } - - public void setPasswordFieldValue(String value) { - seleniumWebDriverHelper.setValue(By.id(PASSWORD_FIELD_ID), value); - } - - public void setNewPasswordFieldValue(String value) { - seleniumWebDriverHelper.setValue(By.id(NEW_PASSWORD_FIELD_ID), value); - } - - public void setNewPasswordConfirmationFieldValue(String value) { - seleniumWebDriverHelper.setValue(By.id(NEW_PASSWORD_CONFIRMATION_ID), value); - } - - public void clickOnSavePasswordButton() { - seleniumWebDriverHelper.waitAndClick(By.xpath(SAVE_BUTTON)); - } - - public void waitTextInErrorAlert(String expectedText) { - loadPageWait.until( - (ExpectedCondition) - driver -> - seleniumWebDriverHelper - .waitVisibility(By.xpath(ERROR_ALERT)) - .getText() - .equals(expectedText)); - } - - public void waitTextInSuccessAlert(String expectedText) { - loadPageWait.until( - (ExpectedCondition) - driver -> - seleniumWebDriverHelper - .waitVisibility(By.xpath(SUCCESS_ALERT)) - .getText() - .equals(expectedText)); - } - - private void waitAllBodyFieldsAndButtonsIsVisible() { - asList( - By.id(PASSWORD_FIELD_ID), - By.id(NEW_PASSWORD_FIELD_ID), - By.id(NEW_PASSWORD_CONFIRMATION_ID), - By.xpath(SAVE_BUTTON)) - .forEach(locator -> seleniumWebDriverHelper.waitVisibility(locator)); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceConfig.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceConfig.java deleted file mode 100644 index 815000b7d5..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceConfig.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.workspaces; - -import static java.lang.String.format; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceConfig.Locators.CONFIG_EDITOR; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceConfig.Locators.CONFIG_FORM; - -import com.google.common.base.Joiner; -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; -import org.openqa.selenium.support.PageFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -public class WorkspaceConfig { - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final Logger LOG = LoggerFactory.getLogger(WorkspaceConfig.class); - - @Inject - public WorkspaceConfig( - SeleniumWebDriver seleniumWebDriver, SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - PageFactory.initElements(seleniumWebDriver, this); - } - - public interface Locators { - String CONFIG_FORM = "//ng-form[@name='workspaceDevfileForm']"; - String CONFIG_EDITOR = "//ng-form[@name='workspaceConfigForm']//div[@class='CodeMirror-code']"; - } - - public void waitConfigForm() { - seleniumWebDriverHelper.waitVisibility(By.xpath(CONFIG_FORM)); - } - - public String getWorkspaceConfig() { - return seleniumWebDriverHelper.waitVisibilityAndGetText(By.xpath(CONFIG_EDITOR), 20); - } - - public String createExpectedWorkspaceConfig(String workspaceName) - throws IOException, URISyntaxException { - String expectedWorkspaceConfTemplate = Joiner.on('\n').join(getConfigFileContent()); - return format(expectedWorkspaceConfTemplate, workspaceName); - } - - private Path getConfigTemplatePath() throws URISyntaxException { - URL fileUrl = - getClass() - .getResource("/org/eclipse/che/selenium/dashboard/expectedWorkspaceConfTemplate.txt"); - - return Paths.get(fileUrl.toURI()); - } - - private List getConfigFileContent() throws URISyntaxException, IOException { - return Files.readAllLines(getConfigTemplatePath()); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceDetails.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceDetails.java deleted file mode 100644 index 893336c967..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceDetails.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.workspaces; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.ELEMENT_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.EXPECTED_MESS_IN_CONSOLE_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOADER_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.REDRAW_UI_ELEMENTS_TIMEOUT_SEC; -import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable; -import static org.openqa.selenium.support.ui.ExpectedConditions.textToBePresentInElement; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.utils.WaitUtils; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.eclipse.che.selenium.pageobject.Loader; -import org.eclipse.che.selenium.pageobject.dashboard.Dashboard; -import org.openqa.selenium.By; -import org.openqa.selenium.TimeoutException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.FindBy; -import org.openqa.selenium.support.PageFactory; -import org.openqa.selenium.support.ui.WebDriverWait; - -/** - * @author Alex - * @author Andrey Chizhikov - */ -@Singleton -public class WorkspaceDetails { - - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final Loader loader; - private final Dashboard dashboard; - - private interface Locators { - String WORKSPACE_STATE = "workspace-status"; - String RUN_WORKSPACE_BTN = "run-workspace-button"; - String STOP_WORKSPACE_BTN = "stop-workspace-button"; - String OPEN_IN_IDE_WS_BTN = "open-in-ide-button"; - String TAB_NAMES_IN_WS = "//md-pagination-wrapper//span[text()='%s']"; - String SAVE_CHANGED_BUTTON = "//button[@name='save-button']"; - String APPLY_CHANGES_BUTTON = "//che-button-save-flat[@class='apply-button']"; - String CANCEL_CHANGES_BUTTON = "//button[@name='cancel-button']"; - String CANCEL_DIALOG_BUTTON = "//md-dialog[@role='dialog']//button/span[text()='Cancel']"; - String CLOSE_DIALOG_BUTTON_NAME = "close-dialog-button"; - String DELETE_DIALOG_BUTTON = "//*[@id='ok-dialog-button']/*[contains(@class, 'che-button')]"; - String UPDATE_DIALOG_BUTTON = "//md-dialog[@role='dialog']//button/span[text()='Update']"; - String ADD_DIALOG_BUTTON = "//md-dialog[@role='dialog']//button/span[text()='Add']"; - String TOOLBAR_TITLE_NAME = - "//div[contains(@class,'che-toolbar')]//span[contains(text(),'%s')]"; - String ORGANIZATION_NAME_ID = "namespace-name"; - String OPEN_ORGANIZATION_BUTTON_ID = "open-namespace-button"; - String CONFIRM_WORKSPACE_DELETION_ID = "enable-button"; - } - - public enum WorkspaceDetailsTab { - OVERVIEW("Overview"), - PROJECTS("Projects"), - MACHINES("Containers"), - SERVERS("Servers"), - ENV_VARIABLES("Env Variables"), - VOLUMES("Volumes"), - CONFIG("Config"), - SSH("SSH"), - SHARE("Share"); - - private final String tabTitle; - - WorkspaceDetailsTab(String tabTitle) { - this.tabTitle = tabTitle; - } - - public String getTabTitle() { - return this.tabTitle; - } - } - - public enum StateWorkspace { - STOPPED("Stopped"), - STARTING("Starting"), - RUNNING("Running"), - STOPPING("Stopping"); - - private final String status; - - StateWorkspace(String status) { - this.status = status; - } - - public String getStatus() { - return status; - } - } - - public enum ActionButton { - SAVE_BUTTON(By.className("save-button")), - APPLY_BUTTON(By.className("apply-button")), - CANCEL_BUTTON(By.className("cancel-button")); - - private By buttonLocator; - - ActionButton(By buttonLocator) { - this.buttonLocator = buttonLocator; - } - - public By getLocator() { - return this.buttonLocator; - } - } - - @Inject - public WorkspaceDetails( - SeleniumWebDriver seleniumWebDriver, - SeleniumWebDriverHelper seleniumWebDriverHelper, - Loader loader, - Dashboard dashboard) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - this.loader = loader; - this.dashboard = dashboard; - PageFactory.initElements(seleniumWebDriver, this); - } - - @FindBy(id = Locators.RUN_WORKSPACE_BTN) - WebElement runWorkspaceBtn; - - @FindBy(id = Locators.STOP_WORKSPACE_BTN) - WebElement stopWorkspaceBtn; - - @FindBy(id = Locators.OPEN_IN_IDE_WS_BTN) - WebElement openInIdeWsBtn; - - @FindBy(id = Locators.WORKSPACE_STATE) - WebElement workspaceState; - - @FindBy(xpath = Locators.SAVE_CHANGED_BUTTON) - WebElement saveBtn; - - @FindBy(xpath = Locators.APPLY_CHANGES_BUTTON) - WebElement applyButton; - - @FindBy(xpath = Locators.CANCEL_CHANGES_BUTTON) - WebElement cancelBtn; - - @FindBy(xpath = Locators.DELETE_DIALOG_BUTTON) - WebElement deleteBtn; - - @FindBy(name = Locators.CLOSE_DIALOG_BUTTON_NAME) - WebElement closeBtn; - - @FindBy(id = Locators.CONFIRM_WORKSPACE_DELETION_ID) - WebElement confirmWorkspaceDeletion; - - public WebElement wait(ActionButton actionButton) { - return seleniumWebDriverHelper.waitVisibility(actionButton.getLocator()); - } - - public void waitAllInvisibility(ActionButton... actionButtons) { - asList(actionButtons) - .forEach( - actionButton -> seleniumWebDriverHelper.waitInvisibility(actionButton.getLocator())); - } - - public void waitAndClickOn(ActionButton actionButton) { - wait(actionButton).click(); - } - - private void waitState(ActionButton actionButton, boolean enabled) { - waitState(actionButton.getLocator(), enabled); - } - - private void waitState(By locator, boolean enabled) { - final String buttonStateAttribute = "aria-disabled"; - seleniumWebDriverHelper.waitAttributeEqualsTo( - locator, buttonStateAttribute, Boolean.toString(!enabled)); - } - - public void waitAllDisabled(ActionButton... actionButtons) { - asList(actionButtons).forEach(actionButton -> waitState(actionButton, false)); - } - - public void waitAllEnabled(ActionButton... actionButtons) { - asList(actionButtons).forEach(actionButton -> waitState(actionButton, true)); - } - - /** - * Check state of workspace in 'Workspace Information' - * - * @param stateWorkspace expected state of workspace - */ - public void checkStateOfWorkspace(StateWorkspace stateWorkspace) { - new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(textToBePresentInElement(workspaceState, stateWorkspace.getStatus())); - } - - public void checkStateOfWorkspace(StateWorkspace stateWorkspace, int timeout) { - new WebDriverWait(seleniumWebDriver, timeout) - .until(textToBePresentInElement(workspaceState, stateWorkspace.getStatus())); - } - - /** click on 'RUN' button in 'Workspace Information' */ - public void clickOnRunWorkspace() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(elementToBeClickable(runWorkspaceBtn)) - .click(); - } - - /** click on 'STOP' button in 'Workspace Information' */ - public void clickOnStopWorkspace() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(elementToBeClickable(stopWorkspaceBtn)) - .click(); - } - - /** wait 'Open in IDE' btn on All workspaces page' */ - public void waitOpenInIdeWsEBtn() { - new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(visibilityOf(openInIdeWsBtn)); - } - - /** click 'Open in IDE btn on All workspaces page' */ - public void clickOpenInIdeWsBtn() { - dashboard.waitNotificationIsClosed(); - waitOpenInIdeWsEBtn(); - new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(elementToBeClickable(openInIdeWsBtn)) - .click(); - } - - /** - * Select tab into workspace menu - * - * @param tab is the tab name into workspace menu - */ - public void selectTabInWorkspaceMenu(WorkspaceDetailsTab tab) { - loader.waitOnClosed(); - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until( - visibilityOfElementLocated( - By.xpath(format(Locators.TAB_NAMES_IN_WS, tab.getTabTitle())))) - .click(); - } - - public void clickOnSaveChangesBtn() { - loader.waitOnClosed(); - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(saveBtn)) - .click(); - } - - public void clickOnApplyChangesBtn() { - loader.waitOnClosed(); - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(applyButton)) - .click(); - } - - public void clickOnCancelChangesBtn() { - // this timeout is needed for the Cancel to appears after renaming of a workspace - WaitUtils.sleepQuietly(3); - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(cancelBtn)) - .click(); - } - - /** Click on the delete/remove button in the dialog window */ - public void clickOnDeleteButtonInDialogWindow() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(deleteBtn)) - .click(); - } - - public void clickOnCloseButtonInDialogWindow() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(closeBtn)) - .click(); - } - - public void clickOnCancelButtonInDialogWindow() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.CANCEL_DIALOG_BUTTON))) - .click(); - } - - public void clickOnUpdateButtonInDialogWindow() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.UPDATE_DIALOG_BUTTON))) - .click(); - } - - public void clickOnAddButtonInDialogWindow() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.xpath(Locators.ADD_DIALOG_BUTTON))) - .click(); - } - - /** - * Wait toolbar name is present on dashboard - * - * @param titleName name of user - */ - public void waitToolbarTitleName(String titleName) { - new WebDriverWait(seleniumWebDriver, LOADER_TIMEOUT_SEC) - .until( - visibilityOfElementLocated(By.xpath(format(Locators.TOOLBAR_TITLE_NAME, titleName)))); - } - - public String getOrganizationName() { - return new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.id(Locators.ORGANIZATION_NAME_ID))) - .getText(); - } - - public void clickOnOpenOrganizationButton() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOfElementLocated(By.id(Locators.OPEN_ORGANIZATION_BUTTON_ID))) - .click(); - } - - public void confirmWorkspaceDeletion() { - seleniumWebDriverHelper.waitNoExceptions( - () -> setConfirmWorkspaceDeletionCheckbox(), ELEMENT_TIMEOUT_SEC, TimeoutException.class); - } - - public void setConfirmWorkspaceDeletionCheckbox() { - seleniumWebDriverHelper.waitAndClick(confirmWorkspaceDeletion); - seleniumWebDriverHelper.waitElementIsSelected(confirmWorkspaceDeletion); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceOverview.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceOverview.java deleted file mode 100644 index 1093e586c0..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceOverview.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.workspaces; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.ELEMENT_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.EXPECTED_MESS_IN_CONSOLE_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.REDRAW_UI_ELEMENTS_TIMEOUT_SEC; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceOverview.Locators.AS_FILE_BUTTON_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceOverview.Locators.AS_FILE_CONFIG_BODY_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceOverview.Locators.EXPORT_WS_FORM_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceOverview.Locators.PRIVATE_CLOUD_BUTTON_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceOverview.Locators.SAVE_BUTTON_XPATH; -import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable; -import static org.openqa.selenium.support.ui.ExpectedConditions.invisibilityOfElementLocated; -import static org.openqa.selenium.support.ui.ExpectedConditions.textToBePresentInElementValue; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.eclipse.che.selenium.pageobject.TestWebElementRenderChecker; -import org.openqa.selenium.By; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.FindBy; -import org.openqa.selenium.support.PageFactory; -import org.openqa.selenium.support.ui.WebDriverWait; - -@Singleton -public class WorkspaceOverview { - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - private final TestWebElementRenderChecker testWebElementRenderChecker; - - @Inject - public WorkspaceOverview( - SeleniumWebDriver seleniumWebDriver, - SeleniumWebDriverHelper seleniumWebDriverHelper, - TestWebElementRenderChecker testWebElementRenderChecker) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - this.testWebElementRenderChecker = testWebElementRenderChecker; - PageFactory.initElements(seleniumWebDriver, this); - } - - public interface Locators { - String NAME_WORKSPACE_INPUT = "//input[@placeholder='Name of the workspace *']"; - String DELETE_WORKSPACE_BTN = "//button[text()='Delete']"; - String WORKSPACE_TITLE = "//div[contains(@class,'toolbar-info')]/span[text()='%s']"; - String EXPORT_WORKSPACE_BTN = - "//button[contains(@class, 'che-button')][text()='Export as a file']"; - String DOWNLOAD_WORKSPACE_BTN = "//che-button-default[@che-button-title='download']"; - String CLIPBOARD_JSON_WS_BTN = "//che-button-default[@che-button-title='clipboard']"; - String HIDE_JSON_WS_BTN = "//span[text()='Close']"; - String WORKSPACE_JSON_CONTENT = "//div[@class='CodeMirror-code']"; - String WS_NAME_ERROR_MESSAGES = "//che-error-messages"; - String EXPORT_WS_FORM_XPATH = "//che-popup[@title='Export Workspace']"; - String AS_FILE_CONFIG_BODY_XPATH = - "//che-popup[@title='Export Workspace']//div[@class='CodeMirror-code']"; - String SAVE_BUTTON_XPATH = "//che-button-save-flat[@che-button-title='Save']"; - String AS_FILE_BUTTON_XPATH = "//md-tab-item/span[text()='As a File']"; - String PRIVATE_CLOUD_BUTTON_XPATH = "//md-tab-item/span[text()='To Private Cloud']"; - } - - @FindBy(xpath = Locators.NAME_WORKSPACE_INPUT) - WebElement nameWorkspaceInput; - - @FindBy(xpath = Locators.DELETE_WORKSPACE_BTN) - WebElement deleteWorkspaceBtn; - - @FindBy(xpath = Locators.EXPORT_WORKSPACE_BTN) - WebElement exportWsButton; - - @FindBy(xpath = Locators.DOWNLOAD_WORKSPACE_BTN) - WebElement downloadWsJsonBtn; - - @FindBy(xpath = Locators.CLIPBOARD_JSON_WS_BTN) - WebElement clipboardWsJsonBtn; - - @FindBy(xpath = Locators.HIDE_JSON_WS_BTN) - WebElement hideJsonWsBtn; - - @FindBy(xpath = Locators.WORKSPACE_JSON_CONTENT) - WebElement workspaceJsonContent; - - @FindBy(xpath = Locators.WS_NAME_ERROR_MESSAGES) - WebElement errorMessages; - - /** - * Check name of workspace in 'Overview' tab - * - * @param nameWorkspace expected name of workspace - */ - public void checkNameWorkspace(String nameWorkspace) { - new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) - .until( - visibilityOfElementLocated(By.xpath(format(Locators.WORKSPACE_TITLE, nameWorkspace)))); - } - - public void waitNameFieldValue(String workspaceName) { - seleniumWebDriverHelper.waitSuccessCondition( - driver -> - seleniumWebDriverHelper - .waitVisibilityAndGetValue(nameWorkspaceInput) - .equals(workspaceName)); - } - - public void waitUntilNoErrorsDisplayed() { - seleniumWebDriverHelper.waitAttributeEqualsTo(nameWorkspaceInput, "aria-invalid", "false"); - } - - public void waitErrorBorderOfNameField() { - seleniumWebDriverHelper.waitAttributeEqualsTo(nameWorkspaceInput, "aria-invalid", "true"); - } - - public void waitSaveButton() { - seleniumWebDriverHelper.waitVisibility(By.xpath(SAVE_BUTTON_XPATH)); - } - - public void waitDisabledSaveButton() { - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(SAVE_BUTTON_XPATH), "aria-disabled", "true"); - } - - public void waitEnabledSaveButton() { - seleniumWebDriverHelper.waitAttributeEqualsTo( - By.xpath(SAVE_BUTTON_XPATH), "aria-disabled", "false"); - } - - public void waitExportWsFormOpened() { - seleniumWebDriverHelper.waitVisibility(By.xpath(EXPORT_WS_FORM_XPATH)); - } - - public String getAsFileFormText() { - return seleniumWebDriverHelper.waitVisibilityAndGetText(By.xpath(AS_FILE_CONFIG_BODY_XPATH)); - } - - public void waitConfiguration(String... expectedConfiguration) { - asList(expectedConfiguration).forEach(config -> getAsFileFormText().contains(config)); - } - - public void clickOnAsFileButton() { - seleniumWebDriverHelper.waitAndClick(By.xpath(AS_FILE_BUTTON_XPATH)); - } - - public void waitExportWorkspaceFormOpened() { - seleniumWebDriverHelper.waitVisibility(By.xpath(EXPORT_WS_FORM_XPATH)); - testWebElementRenderChecker.waitElementIsRendered(By.xpath(EXPORT_WS_FORM_XPATH)); - } - - public void waitExportWorkspaceFormClosed() { - seleniumWebDriverHelper.waitInvisibility(By.xpath(EXPORT_WS_FORM_XPATH)); - } - - public boolean isAsFileTabOpened() { - final String asFileButtonParentContainer = AS_FILE_BUTTON_XPATH + "/parent::md-tab-item"; - return seleniumWebDriverHelper - .waitVisibilityAndGetAttribute(By.xpath(asFileButtonParentContainer), "aria-selected") - .equals("true"); - } - - public void waitAsFileTabOpened() { - seleniumWebDriverHelper.waitSuccessCondition(driver -> isAsFileTabOpened()); - } - - public void waitAsFileTabClosed() { - seleniumWebDriverHelper.waitSuccessCondition(driver -> !isAsFileTabOpened()); - } - - public void clickOnToPrivateCloudButton() { - seleniumWebDriverHelper.waitAndClick(By.xpath(PRIVATE_CLOUD_BUTTON_XPATH)); - } - - public boolean isToPrivateCloudTabOpened() { - final String privateCloudButtonParentContainer = - PRIVATE_CLOUD_BUTTON_XPATH + "/parent::md-tab-item"; - return seleniumWebDriverHelper - .waitVisibilityAndGetAttribute(By.xpath(privateCloudButtonParentContainer), "aria-selected") - .equals("true"); - } - - public void waitToPrivateCloudTabOpened() { - seleniumWebDriverHelper.waitSuccessCondition(driver -> isToPrivateCloudTabOpened()); - } - - public void waitToPrivateCloudTabClosed() { - seleniumWebDriverHelper.waitSuccessCondition(driver -> !isToPrivateCloudTabOpened()); - } - - public void clickOnDownloadButton() { - final String downloadButtonXpath = "//che-button-default [@che-button-title='download']"; - seleniumWebDriverHelper.waitAndClick(By.xpath(downloadButtonXpath)); - } - - public void clickOnClipboardButton() { - final String clipboardButtonXpath = "//che-button-default [@che-button-title='clipboard']"; - seleniumWebDriverHelper.waitAndClick(By.xpath(clipboardButtonXpath)); - } - - public void clickOnCloseExportWorkspaceFormButton() { - final String closeButtonXpath = "//che-button-notice [@che-button-title='Close']"; - seleniumWebDriverHelper.waitAndClick(By.xpath(closeButtonXpath)); - } - - public void clickOnCloseExportWorkspaceFormIcon() { - final String closeFormIcon = EXPORT_WS_FORM_XPATH + "//i"; - seleniumWebDriverHelper.waitAndClick(By.xpath(closeFormIcon)); - } - - public void waitNameErrorMessage(String expectedMessage) { - seleniumWebDriverHelper.waitSuccessCondition( - driver -> isWorkspaceNameErrorMessageEquals(expectedMessage)); - } - - public Boolean isWorkspaceNameErrorMessageEquals(String message) { - return errorMessages.getText().equals(message); - } - - public void waitWorkspaceNameErrorMessageNotVisible() { - seleniumWebDriverHelper.waitInvisibility(errorMessages); - } - - public void checkOnWorkspaceNameErrorAbsence() { - new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC) - .until(invisibilityOfElementLocated(By.xpath("//che-error-messages/div"))); - } - - public void enterNameWorkspace(String nameWorkspace) { - new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(visibilityOf(nameWorkspaceInput)) - .clear(); - new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(visibilityOf(nameWorkspaceInput)) - .sendKeys(nameWorkspace); - new WebDriverWait(seleniumWebDriver, EXPECTED_MESS_IN_CONSOLE_SEC) - .until(textToBePresentInElementValue(nameWorkspaceInput, nameWorkspace)); - } - - public void clickExportWorkspaceBtn() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(exportWsButton)) - .click(); - } - - /** click on 'DELETE' button in 'Delete workspace' */ - public void clickOnDeleteWorkspace() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(elementToBeClickable(deleteWorkspaceBtn)) - .click(); - } - - public void isDeleteWorkspaceButtonExists() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(deleteWorkspaceBtn)); - } - - public void waitDownloadWorkspaceJsonFileBtn() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(elementToBeClickable(downloadWsJsonBtn)); - } - - public void waitClipboardWorkspaceJsonFileBtn() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(elementToBeClickable(clipboardWsJsonBtn)); - } - - public void clickOnHideWorkspaceJsonFileBtn() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(hideJsonWsBtn)) - .click(); - } - - public void clickIntoWorkspaceJsonContent() { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until(visibilityOf(workspaceJsonContent)) - .click(); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceProjects.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceProjects.java deleted file mode 100644 index 8c57d08489..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceProjects.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.workspaces; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.ELEMENT_TIMEOUT_SEC; -import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.REDRAW_UI_ELEMENTS_TIMEOUT_SEC; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjects.Locators.ADD_NEW_PROJECT_BUTTON; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjects.Locators.CHECKBOX_BY_PROJECT_NAME_XPATH_TEMPLATE; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjects.Locators.DELETE_BUTTON_MESSAGE_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjects.Locators.DELETE_BUTTON_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjects.Locators.NOTIFICATION_CONTAINER_ID; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjects.Locators.SEARCH_FIELD_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjects.Locators.SELECT_ALL_CHECKBOX_XPATH; -import static org.openqa.selenium.support.ui.ExpectedConditions.invisibilityOfElementLocated; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import org.eclipse.che.selenium.core.SeleniumWebDriver; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.PageFactory; -import org.openqa.selenium.support.ui.WebDriverWait; - -/** - * @author Musienko Maxim - * @author Ihor Okhrimenko - */ -@Singleton -public class WorkspaceProjects { - - private final SeleniumWebDriver seleniumWebDriver; - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - - @Inject - public WorkspaceProjects( - SeleniumWebDriver seleniumWebDriver, SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.seleniumWebDriver = seleniumWebDriver; - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - PageFactory.initElements(seleniumWebDriver, this); - } - - public interface Locators { - String PROJECT_BY_NAME = "//div[@aria-label='project-item']/span[text()='%s']"; - String DELETE_PROJECT = "//button/span[text()='Delete']"; - String ADD_NEW_PROJECT_BUTTON = "//che-button-primary[@che-button-title='Add Project']/button"; - String PROJECT_CHECKBOX = "//md-checkbox[contains(@aria-label, 'Project %s')]"; - String SEARCH_FIELD_XPATH = "//workspace-details-projects//input[@placeholder='Search']"; - String NOTIFICATION_CONTAINER_ID = "che-notification-container"; - String DELETE_BUTTON_XPATH = "//che-button-primary[@che-button-title='Delete']"; - String DELETE_BUTTON_MESSAGE_XPATH = "//che-list-header-delete-button/span"; - String SELECT_ALL_CHECKBOX_XPATH = "//md-checkbox[@aria-label='Project list']/div"; - String CHECKBOX_BY_PROJECT_NAME_XPATH_TEMPLATE = "//md-checkbox[@aria-label='Project %s']"; - } - - public enum BottomButton { - SAVE_BUTTON("save-button"), - APPLY_BUTTON("apply-button"), - CANCEL_BUTTON("cancel-button"); - - private final String buttonNameAttribute; - - BottomButton(String buttonNameAttribute) { - this.buttonNameAttribute = buttonNameAttribute; - } - - public By getLocator() { - return By.className(this.buttonNameAttribute); - } - } - - public void clickOnSelectAllCheckbox() { - seleniumWebDriverHelper.waitAndClick(By.xpath(SELECT_ALL_CHECKBOX_XPATH)); - } - - public WebElement waitDeleteButton() { - return seleniumWebDriverHelper.waitVisibility(By.xpath(DELETE_BUTTON_XPATH)); - } - - public void waitDeleteButtonDisappearance() { - seleniumWebDriverHelper.waitInvisibility(By.xpath(DELETE_BUTTON_XPATH)); - } - - public void clickOnDeleteButton() { - waitDeleteButton().click(); - } - - public void waitDeleteButtonMessage(String expectedMessage) { - seleniumWebDriverHelper.waitTextContains( - By.xpath(DELETE_BUTTON_MESSAGE_XPATH), expectedMessage); - } - - public void waitDeleteButtonMessageDisappearance() { - seleniumWebDriverHelper.waitInvisibility(By.xpath(DELETE_BUTTON_MESSAGE_XPATH)); - } - - public void waitDeleteButtonDisabling() { - waitState(By.xpath(DELETE_BUTTON_XPATH), false); - } - - public void waitDeleteButtonEnabling() { - waitState(By.xpath(DELETE_BUTTON_XPATH), true); - } - - public void typeToSearchField(String text) { - seleniumWebDriverHelper.setValue(waitSearchField(), text); - } - - public void waitNotification(String expectedText) { - seleniumWebDriverHelper.waitTextContains(By.id(NOTIFICATION_CONTAINER_ID), expectedText); - } - - public WebElement wait(BottomButton button) { - return seleniumWebDriverHelper.waitVisibility(button.getLocator()); - } - - public void waitInvisibility(BottomButton... bottomButtons) { - asList(bottomButtons) - .forEach(button -> seleniumWebDriverHelper.waitInvisibility(button.getLocator())); - } - - public void waitAndClickOn(BottomButton button) { - wait(button).click(); - } - - private void waitState(BottomButton button, boolean enabled) { - waitState(button.getLocator(), enabled); - } - - private void waitState(By locator, boolean enabled) { - final String buttonStateAttribute = "aria-disabled"; - seleniumWebDriverHelper.waitAttributeEqualsTo( - locator, buttonStateAttribute, Boolean.toString(!enabled)); - } - - public void waitDisabled(BottomButton... buttons) { - asList(buttons).forEach(button -> waitState(button, false)); - } - - public void waitEnabled(BottomButton... buttons) { - asList(buttons).forEach(button -> waitState(button, true)); - } - - /** - * wait the project is present in the 'All projects' tab - * - * @param projectName name of project - */ - public void waitProjectIsPresent(String projectName) { - new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) - .until( - visibilityOfElementLocated( - By.xpath(String.format(Locators.PROJECT_BY_NAME, projectName)))); - } - - /** - * wait the project is not present in the 'All projects' tab - * - * @param projectName name of project - */ - public void waitProjectIsNotPresent(String projectName) { - new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) - .until( - invisibilityOfElementLocated( - By.xpath(String.format(Locators.PROJECT_BY_NAME, projectName)))); - } - - /** click on the Add Project button */ - public void clickOnAddNewProjectButton() { - waitAddNewProjectButton().click(); - } - - public WebElement waitAddNewProjectButton() { - return seleniumWebDriverHelper.waitVisibility(By.xpath(ADD_NEW_PROJECT_BUTTON)); - } - - /** click on the Add Project button */ - public void selectProject(String projectName) { - new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) - .until( - visibilityOfElementLocated( - By.xpath(String.format(Locators.PROJECT_CHECKBOX, projectName)))) - .click(); - } - - public WebElement waitSearchField() { - return seleniumWebDriverHelper.waitVisibility(By.xpath(SEARCH_FIELD_XPATH)); - } - - public void waitProjectDetailsPage() { - waitSearchField(); - waitAddNewProjectButton(); - } - - public boolean isCheckboxEnabled(String projectName) { - final String checkboxLocator = format(CHECKBOX_BY_PROJECT_NAME_XPATH_TEMPLATE, projectName); - final String checkboxStateAttribute = "aria-checked"; - return seleniumWebDriverHelper - .waitVisibilityAndGetAttribute(By.xpath(checkboxLocator), checkboxStateAttribute) - .equals("true"); - } - - public void waitCheckboxEnabled(String... projectNames) { - asList(projectNames) - .forEach( - projectName -> - seleniumWebDriverHelper.waitSuccessCondition( - driver -> isCheckboxEnabled(projectName))); - } - - public void waitCheckboxDisabled(String... projectNames) { - asList(projectNames) - .forEach( - projectName -> - seleniumWebDriverHelper.waitSuccessCondition( - driver -> !isCheckboxEnabled(projectName))); - } - - public void clickOnCheckbox(String... projectNames) { - asList(projectNames) - .forEach( - projectName -> { - String checkboxLocator = format(CHECKBOX_BY_PROJECT_NAME_XPATH_TEMPLATE, projectName); - seleniumWebDriverHelper.waitAndClick(By.xpath(checkboxLocator)); - }); - } -} diff --git a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceProjectsSamples.java b/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceProjectsSamples.java deleted file mode 100644 index 08da2a713f..0000000000 --- a/tests/legacy-e2e/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/dashboard/workspaces/WorkspaceProjectsSamples.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2012-2018 Red Hat, Inc. - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - */ -package org.eclipse.che.selenium.pageobject.dashboard.workspaces; - -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjectsSamples.ActionButton.ADD_BUTTON; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjectsSamples.ActionButton.CANCEL_BUTTON; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjectsSamples.Locators.CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjectsSamples.Locators.SAMPLE_ITEM_TEMPLATE_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjectsSamples.Locators.TAB_STATE_TEMPLATE_XPATH; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjectsSamples.TabButton.GITHUB_BUTTON; -import static org.eclipse.che.selenium.pageobject.dashboard.workspaces.WorkspaceProjectsSamples.TabButton.GIT_BUTTON; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import java.util.List; -import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; -import org.openqa.selenium.By; -import org.openqa.selenium.WebElement; - -@Singleton -public class WorkspaceProjectsSamples { - - private final SeleniumWebDriverHelper seleniumWebDriverHelper; - - @Inject - private WorkspaceProjectsSamples(SeleniumWebDriverHelper seleniumWebDriverHelper) { - this.seleniumWebDriverHelper = seleniumWebDriverHelper; - } - - public interface Locators { - String SAMPLE_ITEM_TEMPLATE_XPATH = - "//ng-transclude[@class='che-list-item-content']//span[text()='%s']"; - String TAB_STATE_TEMPLATE_XPATH = "//che-toggle-joined-button[@id='%s']/button"; - String CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE = "sample-%s"; - } - - private interface Button { - String get(); - } - - public enum TabButton implements Button { - SAMPLES_BUTTON("samples-button"), - BLANK_BUTTON("blank-button"), - GIT_BUTTON("git-button"), - GITHUB_BUTTON("github-button"), - ZIP_BUTTON("zip-button"); - - private final String buttonId; - - TabButton(String buttonId) { - this.buttonId = buttonId; - } - - @Override - public String get() { - return this.buttonId; - } - } - - public enum ActionButton implements Button { - CANCEL_BUTTON("cancel-button"), - ADD_BUTTON("add-project-button"); - - private final String buttonId; - - ActionButton(String buttonId) { - this.buttonId = buttonId; - } - - @Override - public String get() { - return this.buttonId; - } - } - - public void waitSamplesForm() { - waitButtons(asList(GIT_BUTTON, GITHUB_BUTTON, CANCEL_BUTTON, ADD_BUTTON)); - } - - public WebElement waitButton(Button button) { - return seleniumWebDriverHelper.waitVisibility(By.id(button.get())); - } - - public void clickOnButton(Button button) { - waitButton(button).click(); - } - - public void waitTabSelected(TabButton tabButton) { - String tabXpath = format(TAB_STATE_TEMPLATE_XPATH, tabButton.get()); - seleniumWebDriverHelper.waitAttributeContainsValue( - By.xpath(tabXpath), "class", "che-toggle-button-enabled"); - } - - public void waitTabNotSelected(TabButton tabButton) { - String tabXpath = format(TAB_STATE_TEMPLATE_XPATH, tabButton.get()); - seleniumWebDriverHelper.waitAttributeContainsValue( - By.xpath(tabXpath), "class", "che-toggle-button-disabled"); - } - - public void waitButtons(List