From 385afa48fc61ad19edac36edd30c06092fd50f44 Mon Sep 17 00:00:00 2001 From: mdolhalo Date: Wed, 26 Jul 2023 17:03:01 +0200 Subject: [PATCH] fix: reformat code Signed-off-by: mdolhalo --- tests/e2e/configs/inversify.config.ts | 12 +- tests/e2e/configs/inversify.types.ts | 54 +- tests/e2e/configs/mocharc.ts | 42 +- tests/e2e/constants/APITestConstants.ts | 77 +- tests/e2e/constants/BaseTestConstants.ts | 87 +- tests/e2e/constants/ChromeDriverConstants.ts | 58 +- tests/e2e/constants/FactoryTestConstants.ts | 60 +- tests/e2e/constants/MonacoConstants.ts | 20 +- tests/e2e/constants/OAuthConstants.ts | 92 +- tests/e2e/constants/ReporterConstants.ts | 56 +- tests/e2e/constants/TimeoutConstants.ts | 202 +-- tests/e2e/driver/ChromeDriver.ts | 88 +- tests/e2e/driver/IDriver.ts | 2 +- .../pageobjects/dashboard/CreateWorkspace.ts | 104 +- tests/e2e/pageobjects/dashboard/Dashboard.ts | 144 +- tests/e2e/pageobjects/dashboard/Workspaces.ts | 277 ++-- .../workspace-details/WorkspaceDetails.ts | 185 ++- .../pageobjects/git-providers/OauthPage.ts | 272 ++-- .../pageobjects/ide/CheCodeLocatorLoader.ts | 80 +- .../login/interfaces/ICheLoginPage.ts | 2 +- .../login/interfaces/IOcpLoginPage.ts | 2 +- .../login/kubernetes/DexLoginPage.ts | 54 +- .../login/kubernetes/KubernetesLoginPage.ts | 22 +- .../login/openshift/OcpLoginPage.ts | 100 +- .../login/openshift/OcpRedHatLoginPage.ts | 42 +- .../login/openshift/OcpUserLoginPage.ts | 28 +- .../login/openshift/RedHatLoginPage.ts | 85 +- .../openshift/RegularUserOcpCheLoginPage.ts | 46 +- .../openshift/OcpApplicationPage.ts | 32 +- .../openshift/OcpImportFromGitPage.ts | 108 +- .../e2e/pageobjects/openshift/OcpMainPage.ts | 128 +- tests/e2e/specs/MochaHooks.ts | 88 +- tests/e2e/specs/SmokeTest.spec.ts | 68 +- .../specs/api/ContainerOverridesAPI.spec.ts | 46 +- tests/e2e/specs/api/EmptyWorkspaceAPI.spec.ts | 100 +- tests/e2e/specs/api/PodOverridesAPI.spec.ts | 58 +- .../specs/dashboard-samples/Quarkus.spec.ts | 62 +- .../RecommendedExtensions.spec.ts | 300 ++--- .../DevConsoleIntegration.spec.ts | 128 +- tests/e2e/specs/factory/Factory.spec.ts | 300 ++--- .../specs/factory/NoSetupRepoFactory.spec.ts | 374 ++--- .../specs/factory/RefusedOAuthFactory.spec.ts | 362 ++--- .../miscellaneous/PredefinedNamespace.spec.ts | 104 +- tests/e2e/tests-library/LoginTests.ts | 58 +- .../e2e/tests-library/ProjectAndFileTests.ts | 26 +- .../tests-library/WorkspaceHandlingTests.ts | 170 ++- tests/e2e/utils/BrowserTabsUtil.ts | 138 +- tests/e2e/utils/CheReporter.ts | 10 +- .../utils/DevWorkspaceConfigurationHelper.ts | 116 +- tests/e2e/utils/DevfilesRegistryHelper.ts | 102 +- tests/e2e/utils/DriverHelper.ts | 1199 ++++++++--------- .../KubernetesCommandLineToolsExecutor.ts | 3 +- tests/e2e/utils/ScreenCatcher.ts | 84 +- tests/e2e/utils/ShellExecutor.ts | 20 +- tests/e2e/utils/StringUtil.ts | 58 +- .../request-handlers/CheApiRequestHandler.ts | 166 +-- .../headers/IAuthorizationHeaderHandler.ts | 2 +- tests/e2e/utils/workspace/ApiUrlResolver.ts | 46 +- .../e2e/utils/workspace/ITestWorkspaceUtil.ts | 58 +- .../e2e/utils/workspace/TestWorkspaceUtil.ts | 236 ++-- tests/e2e/utils/workspace/WorkspaceStatus.ts | 6 +- 61 files changed, 3525 insertions(+), 3524 deletions(-) diff --git a/tests/e2e/configs/inversify.config.ts b/tests/e2e/configs/inversify.config.ts index ca7b660684f..f88ac8e44c3 100644 --- a/tests/e2e/configs/inversify.config.ts +++ b/tests/e2e/configs/inversify.config.ts @@ -12,7 +12,7 @@ import 'reflect-metadata'; import { Container } from 'inversify'; import { IDriver } from '../driver/IDriver'; import { ChromeDriver } from '../driver/ChromeDriver'; -import { TYPES, CLASSES } from './inversify.types'; +import { CLASSES, TYPES } from './inversify.types'; import { TestWorkspaceUtil } from '../utils/workspace/TestWorkspaceUtil'; import { IOcpLoginPage } from '../pageobjects/login/interfaces/IOcpLoginPage'; import { OcpUserLoginPage } from '../pageobjects/login/openshift/OcpUserLoginPage'; @@ -73,10 +73,10 @@ e2eContainer.bind(CLASSES.ApiUrlResolver).to(ApiUrlResolver); e2eContainer.bind(CLASSES.WorkspaceHandlingTests).to(WorkspaceHandlingTests); e2eContainer.bind(CLASSES.RedHatLoginPage).to(RedHatLoginPage); -BaseTestConstants.TS_PLATFORM === Platform.OPENSHIFT ? - OAuthConstants.TS_SELENIUM_VALUE_OPENSHIFT_OAUTH ? - e2eContainer.bind(TYPES.CheLogin).to(RegularUserOcpCheLoginPage) : - e2eContainer.bind(TYPES.CheLogin).to(OcpRedHatLoginPage) : - e2eContainer.bind(TYPES.CheLogin).to(KubernetesLoginPage); +BaseTestConstants.TS_PLATFORM === Platform.OPENSHIFT ? + OAuthConstants.TS_SELENIUM_VALUE_OPENSHIFT_OAUTH ? + e2eContainer.bind(TYPES.CheLogin).to(RegularUserOcpCheLoginPage) : + e2eContainer.bind(TYPES.CheLogin).to(OcpRedHatLoginPage) : + e2eContainer.bind(TYPES.CheLogin).to(KubernetesLoginPage); export { e2eContainer }; diff --git a/tests/e2e/configs/inversify.types.ts b/tests/e2e/configs/inversify.types.ts index a09d4d84057..3c62c453165 100644 --- a/tests/e2e/configs/inversify.types.ts +++ b/tests/e2e/configs/inversify.types.ts @@ -9,36 +9,36 @@ **********************************************************************/ const TYPES: any = { - Driver: Symbol.for('Driver'), - CheLogin: Symbol.for('CheLogin'), - OcpLogin: Symbol.for('OcpLogin'), - WorkspaceUtil: Symbol.for('WorkspaceUtil'), - IAuthorizationHeaderHandler: Symbol.for('IAuthorizationHeaderHandler'), - ITokenHandler: Symbol.for('ITokenHandler') + Driver: Symbol.for('Driver'), + CheLogin: Symbol.for('CheLogin'), + OcpLogin: Symbol.for('OcpLogin'), + WorkspaceUtil: Symbol.for('WorkspaceUtil'), + IAuthorizationHeaderHandler: Symbol.for('IAuthorizationHeaderHandler'), + ITokenHandler: Symbol.for('ITokenHandler') }; const CLASSES: any = { - DriverHelper: 'DriverHelper', - Dashboard: 'Dashboard', - Workspaces: 'Workspaces', - WorkspaceDetails: 'WorkspaceDetails', - ScreenCatcher: 'ScreenCatcher', - OcpLoginPage: 'OcpLoginPage', - CheApiRequestHandler: 'CheApiRequestHandler', - CreateWorkspace: 'CreateWorkspace', - BrowserTabsUtil: 'BrowserTabsUtil', - ProjectAndFileTests: 'ProjectAndFileTests', - StringUtil: 'StringUtil', - ApiUrlResolver: 'ApiUrlResolver', - LoginTests: 'LoginTests', - WorkspaceHandlingTests: 'WorkspaceHandlingTests', - RedHatLoginPage: 'RedHatLoginPage', - KubernetesLoginPage: 'KubernetesLoginPage', - DexLoginPage: 'DexLoginPage', - OcpRedHatLoginPage: 'OcpRedHatLoginPage', - OcpApplicationPage: 'OcpApplicationPage', - OcpMainPage: 'OcpMainPage', - OcpImportFromGitPage: 'OcpImportFromGitPage' + DriverHelper: 'DriverHelper', + Dashboard: 'Dashboard', + Workspaces: 'Workspaces', + WorkspaceDetails: 'WorkspaceDetails', + ScreenCatcher: 'ScreenCatcher', + OcpLoginPage: 'OcpLoginPage', + CheApiRequestHandler: 'CheApiRequestHandler', + CreateWorkspace: 'CreateWorkspace', + BrowserTabsUtil: 'BrowserTabsUtil', + ProjectAndFileTests: 'ProjectAndFileTests', + StringUtil: 'StringUtil', + ApiUrlResolver: 'ApiUrlResolver', + LoginTests: 'LoginTests', + WorkspaceHandlingTests: 'WorkspaceHandlingTests', + RedHatLoginPage: 'RedHatLoginPage', + KubernetesLoginPage: 'KubernetesLoginPage', + DexLoginPage: 'DexLoginPage', + OcpRedHatLoginPage: 'OcpRedHatLoginPage', + OcpApplicationPage: 'OcpApplicationPage', + OcpMainPage: 'OcpMainPage', + OcpImportFromGitPage: 'OcpImportFromGitPage' }; export { TYPES, CLASSES }; diff --git a/tests/e2e/configs/mocharc.ts b/tests/e2e/configs/mocharc.ts index cbf6a79d584..7cf68f461a8 100644 --- a/tests/e2e/configs/mocharc.ts +++ b/tests/e2e/configs/mocharc.ts @@ -13,25 +13,25 @@ import { TimeoutConstants } from '../constants/TimeoutConstants'; module.exports = { - timeout: 1200000, - reporter: 'dist/utils/CheReporter.js', - ui: 'tdd', - require: [ - 'dist/specs/MochaHooks.js', - 'ts-node/register', - ], - bail: true, - 'full-trace': true, - spec: - // variable MOCHA_DIRECTORY uses in command "test-all-devfiles" and sets up automatically. - // you can set it up to run files from specific directory with export environmental variable. - process.env.MOCHA_DIRECTORY ? - // to run one file (name without extension). uses in "test", "test-all-devfiles". - process.env.USERSTORY ? - `dist/specs/${process.env.MOCHA_DIRECTORY}/${process.env.USERSTORY}.spec.js` - : `dist/specs/${process.env.MOCHA_DIRECTORY}/**.spec.js` - : process.env.USERSTORY ? - [`dist/specs/**/${process.env.USERSTORY}.spec.js`, `dist/specs/${process.env.USERSTORY}.spec.js`] - : [`dist/specs/**/**.spec.js`, `dist/specs/**.spec.js`], - retries: TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, + timeout: 1200000, + reporter: 'dist/utils/CheReporter.js', + ui: 'tdd', + require: [ + 'dist/specs/MochaHooks.js', + 'ts-node/register', + ], + bail: true, + 'full-trace': true, + spec: + // variable MOCHA_DIRECTORY uses in command "test-all-devfiles" and sets up automatically. + // you can set it up to run files from specific directory with export environmental variable. + process.env.MOCHA_DIRECTORY ? + // to run one file (name without extension). uses in "test", "test-all-devfiles". + process.env.USERSTORY ? + `dist/specs/${process.env.MOCHA_DIRECTORY}/${process.env.USERSTORY}.spec.js` + : `dist/specs/${process.env.MOCHA_DIRECTORY}/**.spec.js` + : process.env.USERSTORY ? + [`dist/specs/**/${process.env.USERSTORY}.spec.js`, `dist/specs/${process.env.USERSTORY}.spec.js`] + : [`dist/specs/**/**.spec.js`, `dist/specs/**.spec.js`], + retries: TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS }; diff --git a/tests/e2e/constants/APITestConstants.ts b/tests/e2e/constants/APITestConstants.ts index 1ba71c0c3b8..5050e55fc00 100644 --- a/tests/e2e/constants/APITestConstants.ts +++ b/tests/e2e/constants/APITestConstants.ts @@ -11,46 +11,47 @@ import { BaseTestConstants } from './BaseTestConstants'; export enum KubernetesCommandLineTool { - OC = 'oc', - KUBECTL = 'kubectl', + OC = 'oc', + KUBECTL = 'kubectl', } + export const SupportedDevfilesRegistries: any = { - INBUILT_APPLICATION_DEVFILE_REGISTRY_URL: () => `${BaseTestConstants.TS_SELENIUM_BASE_URL}/devfile-registry/devfiles/`, - GIT_HUB_CHE_DEVFILE_REGISTRY_URL: `https://api.github.com/repos/eclipse-che/che-devfile-registry/contents/devfiles/`, + INBUILT_APPLICATION_DEVFILE_REGISTRY_URL: () => `${BaseTestConstants.TS_SELENIUM_BASE_URL}/devfile-registry/devfiles/`, + GIT_HUB_CHE_DEVFILE_REGISTRY_URL: `https://api.github.com/repos/eclipse-che/che-devfile-registry/contents/devfiles/` }; export const APITestConstants: any = { - /** - * Possible values "oc" or "kubectl" - */ - TS_API_TEST_KUBERNETES_COMMAND_LINE_TOOL: process.env.TS_API_TEST_KUBERNETES_COMMAND_LINE_TOOL || KubernetesCommandLineTool.OC, - - /** - * 'quay.io/devfile/universal-developer-image:latest' - * is default assigned by DevWorkspaceConfigurationHelper.generateDevfileContext() using @eclipse-che/che-devworkspace-generator - */ - TS_API_TEST_UDI_IMAGE: process.env.TS_API_TEST_UDI_IMAGE || undefined, - - /** - * https://eclipse-che.github.io/che-plugin-registry/main/v3/plugins/che-incubator/che-code/latest/devfile.yaml - * is default assigned by DevWorkspaceConfigurationHelper.generateDevfileContext() using @eclipse-che/che-devworkspace-generator - */ - TS_API_TEST_CHE_CODE_EDITOR_DEVFILE_URI: process.env.TS_API_TEST_CHE_CODE_EDITOR_DEVFILE_URI || undefined, - - /** - * https://eclipse-che.github.io/che-plugin-registry/main/v3 - * is default assigned by DevWorkspaceConfigurationHelper.generateDevfileContext() using @eclipse-che/che-devworkspace-generator - */ - TS_API_TEST_PLUGIN_REGISTRY_URL: process.env.TS_API_TEST_PLUGIN_REGISTRY_URL || undefined, - - /** - * Namespace on openshift platform - */ - TS_API_TEST_NAMESPACE: process.env.TS_API_TEST_NAMESPACE || undefined, - - /** - * to run all devfile from registry. used in DevfileAcceptanceTestAPI.suite.ts - */ - TS_API_ACCEPTANCE_TEST_REGISTRY_URL(): string { - return process.env.TS_API_ACCEPTANCE_TEST_REGISTRY_URL || SupportedDevfilesRegistries.INBUILT_APPLICATION_DEVFILE_REGISTRY_URL(); - }, + /** + * Possible values "oc" or "kubectl" + */ + TS_API_TEST_KUBERNETES_COMMAND_LINE_TOOL: process.env.TS_API_TEST_KUBERNETES_COMMAND_LINE_TOOL || KubernetesCommandLineTool.OC, + + /** + * 'quay.io/devfile/universal-developer-image:latest' + * is default assigned by DevWorkspaceConfigurationHelper.generateDevfileContext() using @eclipse-che/che-devworkspace-generator + */ + TS_API_TEST_UDI_IMAGE: process.env.TS_API_TEST_UDI_IMAGE || undefined, + + /** + * https://eclipse-che.github.io/che-plugin-registry/main/v3/plugins/che-incubator/che-code/latest/devfile.yaml + * is default assigned by DevWorkspaceConfigurationHelper.generateDevfileContext() using @eclipse-che/che-devworkspace-generator + */ + TS_API_TEST_CHE_CODE_EDITOR_DEVFILE_URI: process.env.TS_API_TEST_CHE_CODE_EDITOR_DEVFILE_URI || undefined, + + /** + * https://eclipse-che.github.io/che-plugin-registry/main/v3 + * is default assigned by DevWorkspaceConfigurationHelper.generateDevfileContext() using @eclipse-che/che-devworkspace-generator + */ + TS_API_TEST_PLUGIN_REGISTRY_URL: process.env.TS_API_TEST_PLUGIN_REGISTRY_URL || undefined, + + /** + * Namespace on openshift platform + */ + TS_API_TEST_NAMESPACE: process.env.TS_API_TEST_NAMESPACE || undefined, + + /** + * to run all devfile from registry. used in DevfileAcceptanceTestAPI.suite.ts + */ + TS_API_ACCEPTANCE_TEST_REGISTRY_URL(): string { + return process.env.TS_API_ACCEPTANCE_TEST_REGISTRY_URL || SupportedDevfilesRegistries.INBUILT_APPLICATION_DEVFILE_REGISTRY_URL(); + } }; diff --git a/tests/e2e/constants/BaseTestConstants.ts b/tests/e2e/constants/BaseTestConstants.ts index 48e24cb53af..96d0d21f073 100644 --- a/tests/e2e/constants/BaseTestConstants.ts +++ b/tests/e2e/constants/BaseTestConstants.ts @@ -8,58 +8,59 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ export enum Platform { - OPENSHIFT = 'openshift', - KUBERNETES = 'kubernetes', + OPENSHIFT = 'openshift', + KUBERNETES = 'kubernetes', } + export const BaseTestConstants: any = { - /** - * Base URL of the application which should be checked - */ - TS_SELENIUM_BASE_URL: !process.env.TS_SELENIUM_BASE_URL ? 'http://sample-url' : process.env.TS_SELENIUM_BASE_URL.replace(/\/$/, ''), + /** + * Base URL of the application which should be checked + */ + TS_SELENIUM_BASE_URL: !process.env.TS_SELENIUM_BASE_URL ? 'http://sample-url' : process.env.TS_SELENIUM_BASE_URL.replace(/\/$/, ''), - /** - * Choose the platform where "che" application deployed, "openshift" by default. - */ - TS_PLATFORM: process.env.TS_PLATFORM || Platform.OPENSHIFT, + /** + * Choose the platform where "che" application deployed, "openshift" by default. + */ + TS_PLATFORM: process.env.TS_PLATFORM || Platform.OPENSHIFT, - /** - * Editor the tests are running against, "code" by default. - * Possible values: "che-code" - */ - TS_SELENIUM_EDITOR: process.env.TS_SELENIUM_EDITOR || 'che-code', + /** + * Editor the tests are running against, "code" by default. + * Possible values: "che-code" + */ + TS_SELENIUM_EDITOR: process.env.TS_SELENIUM_EDITOR || 'che-code', - /** - * File name to check if project was imported - */ - TS_SELENIUM_PROJECT_ROOT_FILE_NAME: process.env.TS_SELENIUM_PROJECT_ROOT_FILE_NAME || 'devfile.yaml', + /** + * File name to check if project was imported + */ + TS_SELENIUM_PROJECT_ROOT_FILE_NAME: process.env.TS_SELENIUM_PROJECT_ROOT_FILE_NAME || 'devfile.yaml', - /** - * Name of workspace created for 'Happy Path' scenario validation. - */ - TS_SELENIUM_HAPPY_PATH_WORKSPACE_NAME: process.env.TS_SELENIUM_HAPPY_PATH_WORKSPACE_NAME || 'EmptyWorkspace', + /** + * Name of workspace created for 'Happy Path' scenario validation. + */ + TS_SELENIUM_HAPPY_PATH_WORKSPACE_NAME: process.env.TS_SELENIUM_HAPPY_PATH_WORKSPACE_NAME || 'EmptyWorkspace', - /** - * This variable specifies that run test is used for load testing and that all artifacts will be sent to ftp client. - */ - TS_LOAD_TESTS: process.env.TS_LOAD_TESTS || 'false', + /** + * This variable specifies that run test is used for load testing and that all artifacts will be sent to ftp client. + */ + TS_LOAD_TESTS: process.env.TS_LOAD_TESTS || 'false', - /** - * Enable Axios request interceptor, false by default - */ - TS_SELENIUM_REQUEST_INTERCEPTOR: process.env.TS_SELENIUM_REQUEST_INTERCEPTOR === 'true', + /** + * Enable Axios request interceptor, false by default + */ + TS_SELENIUM_REQUEST_INTERCEPTOR: process.env.TS_SELENIUM_REQUEST_INTERCEPTOR === 'true', - /** - * Enable Axios response interceptor, false by default - */ - TS_SELENIUM_RESPONSE_INTERCEPTOR: process.env.TS_SELENIUM_RESPONSE_INTERCEPTOR === 'true', + /** + * Enable Axios response interceptor, false by default + */ + TS_SELENIUM_RESPONSE_INTERCEPTOR: process.env.TS_SELENIUM_RESPONSE_INTERCEPTOR === 'true', - /** - * Stop and remove workspace if a test fails. - */ - DELETE_WORKSPACE_ON_FAILED_TEST: process.env.DELETE_WORKSPACE_ON_FAILED_TEST === 'true', + /** + * Stop and remove workspace if a test fails. + */ + DELETE_WORKSPACE_ON_FAILED_TEST: process.env.DELETE_WORKSPACE_ON_FAILED_TEST === 'true', - /** - * Constant, which prolong timeout constants for local debug. - */ - TS_DEBUG_MODE: process.env.TS_DEBUG_MODE === 'true', + /** + * Constant, which prolong timeout constants for local debug. + */ + TS_DEBUG_MODE: process.env.TS_DEBUG_MODE === 'true' }; diff --git a/tests/e2e/constants/ChromeDriverConstants.ts b/tests/e2e/constants/ChromeDriverConstants.ts index f5c318ef2f4..6bf7f3aa5dc 100644 --- a/tests/e2e/constants/ChromeDriverConstants.ts +++ b/tests/e2e/constants/ChromeDriverConstants.ts @@ -8,39 +8,39 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ export const ChromeDriverConstants: any = { - /** - * Remote driver URL. - */ - TS_SELENIUM_REMOTE_DRIVER_URL: process.env.TS_SELENIUM_REMOTE_DRIVER_URL || '', + /** + * Remote driver URL. + */ + TS_SELENIUM_REMOTE_DRIVER_URL: process.env.TS_SELENIUM_REMOTE_DRIVER_URL || '', - /** - * Run browser in "Headless" (hidden) mode, "false" by default. - */ - TS_SELENIUM_HEADLESS: process.env.TS_SELENIUM_HEADLESS === 'true', + /** + * Run browser in "Headless" (hidden) mode, "false" by default. + */ + TS_SELENIUM_HEADLESS: process.env.TS_SELENIUM_HEADLESS === 'true', - /** - * Create instance of chromedriver, "true" by default. Should be "false" to run only API tests. - */ - TS_USE_WEB_DRIVER_FOR_TEST: process.env.TS_USE_WEB_DRIVER_FOR_TEST !== 'false', + /** + * Create instance of chromedriver, "true" by default. Should be "false" to run only API tests. + */ + TS_USE_WEB_DRIVER_FOR_TEST: process.env.TS_USE_WEB_DRIVER_FOR_TEST !== 'false', - /** - * Run browser in "Fullscreen" (kiosk) mode. - * Default to true if undefined - */ - TS_SELENIUM_LAUNCH_FULLSCREEN: (process.env.TS_SELENIUM_LAUNCH_FULLSCREEN !== 'false'), + /** + * Run browser in "Fullscreen" (kiosk) mode. + * Default to true if undefined + */ + TS_SELENIUM_LAUNCH_FULLSCREEN: (process.env.TS_SELENIUM_LAUNCH_FULLSCREEN !== 'false'), - /** - * Run browser with an enabled or disabled W3C protocol (on Chrome 76 and upper, it is enabled by default), "true" by default. - */ - TS_SELENIUM_W3C_CHROME_OPTION: process.env.TS_SELENIUM_W3C_CHROME_OPTION !== 'false', + /** + * Run browser with an enabled or disabled W3C protocol (on Chrome 76 and upper, it is enabled by default), "true" by default. + */ + TS_SELENIUM_W3C_CHROME_OPTION: process.env.TS_SELENIUM_W3C_CHROME_OPTION !== 'false', - /** - * Browser width resolution, "1920" by default. - */ - TS_SELENIUM_RESOLUTION_WIDTH: Number(process.env.TS_SELENIUM_RESOLUTION_WIDTH) || 1920, + /** + * Browser width resolution, "1920" by default. + */ + TS_SELENIUM_RESOLUTION_WIDTH: Number(process.env.TS_SELENIUM_RESOLUTION_WIDTH) || 1920, - /** - * Browser height resolution, "1080" by default. - */ - TS_SELENIUM_RESOLUTION_HEIGHT: Number(process.env.TS_SELENIUM_RESOLUTION_HEIGHT) || 1080, + /** + * Browser height resolution, "1080" by default. + */ + TS_SELENIUM_RESOLUTION_HEIGHT: Number(process.env.TS_SELENIUM_RESOLUTION_HEIGHT) || 1080 }; diff --git a/tests/e2e/constants/FactoryTestConstants.ts b/tests/e2e/constants/FactoryTestConstants.ts index 0fc91faf9bf..cdb8be5d792 100644 --- a/tests/e2e/constants/FactoryTestConstants.ts +++ b/tests/e2e/constants/FactoryTestConstants.ts @@ -10,42 +10,42 @@ import { BaseTestConstants } from './BaseTestConstants'; export enum GitProviderType { - GITHUB = 'github', - GITLAB = 'gitlab', - BITBUCKET = 'bitbucket', - AZURE_DEVOPS = 'azure-devops' + GITHUB = 'github', + GITLAB = 'gitlab', + BITBUCKET = 'bitbucket', + AZURE_DEVOPS = 'azure-devops' } export const FactoryTestConstants: any = { - /** - * Git provider to check in factory tests - */ - TS_SELENIUM_FACTORY_GIT_PROVIDER: process.env.TS_SELENIUM_FACTORY_GIT_PROVIDER || GitProviderType.GITHUB, + /** + * Git provider to check in factory tests + */ + TS_SELENIUM_FACTORY_GIT_PROVIDER: process.env.TS_SELENIUM_FACTORY_GIT_PROVIDER || GitProviderType.GITHUB, - /** - * URL to create factory - */ - TS_SELENIUM_FACTORY_GIT_REPO_URL: process.env.TS_SELENIUM_FACTORY_GIT_REPO_URL || '', + /** + * URL to create factory + */ + TS_SELENIUM_FACTORY_GIT_REPO_URL: process.env.TS_SELENIUM_FACTORY_GIT_REPO_URL || '', - /** - * Git repository name - */ - TS_SELENIUM_PROJECT_NAME: process.env.TS_SELENIUM_PROJECT_NAME || '', + /** + * Git repository name + */ + TS_SELENIUM_PROJECT_NAME: process.env.TS_SELENIUM_PROJECT_NAME || '', - /** - * Is factory repository URL private or no - */ - TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO: process.env.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO === 'true', + /** + * Is factory repository URL private or no + */ + TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO: process.env.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO === 'true', - /** - * Git repository main branch name (main or master) - */ - TS_SELENIUM_FACTORY_GIT_REPO_BRANCH: process.env.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH || 'master', + /** + * Git repository main branch name (main or master) + */ + TS_SELENIUM_FACTORY_GIT_REPO_BRANCH: process.env.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH || 'master', - /** - * Full factory URL - */ - TS_SELENIUM_FACTORY_URL(): string { - return process.env.TS_SELENIUM_FACTORY_URL || BaseTestConstants.TS_SELENIUM_BASE_URL + '/dashboard/#/' + this.TS_SELENIUM_FACTORY_GIT_REPO_URL; - }, + /** + * Full factory URL + */ + TS_SELENIUM_FACTORY_URL(): string { + return process.env.TS_SELENIUM_FACTORY_URL || BaseTestConstants.TS_SELENIUM_BASE_URL + '/dashboard/#/' + this.TS_SELENIUM_FACTORY_GIT_REPO_URL; + } }; diff --git a/tests/e2e/constants/MonacoConstants.ts b/tests/e2e/constants/MonacoConstants.ts index 7a8af0a4199..d53c668f97a 100644 --- a/tests/e2e/constants/MonacoConstants.ts +++ b/tests/e2e/constants/MonacoConstants.ts @@ -8,15 +8,15 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ export const MonacoConstants: any = { - /** - * Base version of VSCode editor for monaco-page-objects, "1.37.0" by default. - */ - TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION: process.env.TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION || '1.37.0', + /** + * Base version of VSCode editor for monaco-page-objects, "1.37.0" by default. + */ + TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION: process.env.TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION || '1.37.0', - /** - * Latest compatible version to be used, based on versions available in - * https://github.com/redhat-developer/vscode-extension-tester/tree/master/locators/lib , - * "1.73.0" by default. - */ - TS_SELENIUM_MONACO_PAGE_OBJECTS_USE_VERSION: process.env.TS_SELENIUM_MONACO_PAGE_OBJECTS_USE_VERSION || '1.73.0', + /** + * Latest compatible version to be used, based on versions available in + * https://github.com/redhat-developer/vscode-extension-tester/tree/master/locators/lib , + * "1.73.0" by default. + */ + TS_SELENIUM_MONACO_PAGE_OBJECTS_USE_VERSION: process.env.TS_SELENIUM_MONACO_PAGE_OBJECTS_USE_VERSION || '1.73.0' }; diff --git a/tests/e2e/constants/OAuthConstants.ts b/tests/e2e/constants/OAuthConstants.ts index bde0ec8270a..03b8227cfb0 100644 --- a/tests/e2e/constants/OAuthConstants.ts +++ b/tests/e2e/constants/OAuthConstants.ts @@ -8,50 +8,50 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ export const OAuthConstants: any = { - /** - * Value of OpenShift oAuth property determines how to login in installed application, - * if 'false' as an user of application, if 'true' as a regular user of OCP. - */ - TS_SELENIUM_VALUE_OPENSHIFT_OAUTH: process.env.TS_SELENIUM_VALUE_OPENSHIFT_OAUTH === 'true', - - /** - * Log into OCP by using appropriate provider title. - */ - TS_OCP_LOGIN_PAGE_PROVIDER_TITLE: process.env.TS_OCP_LOGIN_PAGE_PROVIDER_TITLE || '', - - /** - * Regular username used to login in OCP. - */ - TS_SELENIUM_OCP_USERNAME: process.env.TS_SELENIUM_OCP_USERNAME || '', - - /** - * Password regular user used to login in OCP. - */ - TS_SELENIUM_OCP_PASSWORD: process.env.TS_SELENIUM_OCP_PASSWORD || '', - - /** - * Regular username used to login in Kubernetes. - */ - TS_SELENIUM_K8S_USERNAME: process.env.TS_SELENIUM_K8S_USERNAME || '', - - /** - * Password regular user used to login in Kubernetes. - */ - TS_SELENIUM_K8S_PASSWORD: process.env.TS_SELENIUM_K8S_PASSWORD || '', - - /** - * For login via github for example on https://che-dogfooding.apps.che-dev.x6e0.p1.openshiftapps.com - * For factory tests - */ - TS_SELENIUM_GIT_PROVIDER_OAUTH: process.env.TS_SELENIUM_GIT_PROVIDER_OAUTH === 'true', - - /** - * Git repository username - */ - TS_SELENIUM_GIT_PROVIDER_USERNAME: process.env.TS_SELENIUM_GIT_PROVIDER_USERNAME || '', - - /** - * Git repository password - */ - TS_SELENIUM_GIT_PROVIDER_PASSWORD: process.env.TS_SELENIUM_GIT_PROVIDER_PASSWORD || '', + /** + * Value of OpenShift oAuth property determines how to login in installed application, + * if 'false' as an user of application, if 'true' as a regular user of OCP. + */ + TS_SELENIUM_VALUE_OPENSHIFT_OAUTH: process.env.TS_SELENIUM_VALUE_OPENSHIFT_OAUTH === 'true', + + /** + * Log into OCP by using appropriate provider title. + */ + TS_OCP_LOGIN_PAGE_PROVIDER_TITLE: process.env.TS_OCP_LOGIN_PAGE_PROVIDER_TITLE || '', + + /** + * Regular username used to login in OCP. + */ + TS_SELENIUM_OCP_USERNAME: process.env.TS_SELENIUM_OCP_USERNAME || '', + + /** + * Password regular user used to login in OCP. + */ + TS_SELENIUM_OCP_PASSWORD: process.env.TS_SELENIUM_OCP_PASSWORD || '', + + /** + * Regular username used to login in Kubernetes. + */ + TS_SELENIUM_K8S_USERNAME: process.env.TS_SELENIUM_K8S_USERNAME || '', + + /** + * Password regular user used to login in Kubernetes. + */ + TS_SELENIUM_K8S_PASSWORD: process.env.TS_SELENIUM_K8S_PASSWORD || '', + + /** + * For login via github for example on https://che-dogfooding.apps.che-dev.x6e0.p1.openshiftapps.com + * For factory tests + */ + TS_SELENIUM_GIT_PROVIDER_OAUTH: process.env.TS_SELENIUM_GIT_PROVIDER_OAUTH === 'true', + + /** + * Git repository username + */ + TS_SELENIUM_GIT_PROVIDER_USERNAME: process.env.TS_SELENIUM_GIT_PROVIDER_USERNAME || '', + + /** + * Git repository password + */ + TS_SELENIUM_GIT_PROVIDER_PASSWORD: process.env.TS_SELENIUM_GIT_PROVIDER_PASSWORD || '' }; diff --git a/tests/e2e/constants/ReporterConstants.ts b/tests/e2e/constants/ReporterConstants.ts index bc9138eac7a..1bea6d37a82 100644 --- a/tests/e2e/constants/ReporterConstants.ts +++ b/tests/e2e/constants/ReporterConstants.ts @@ -8,38 +8,38 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ export const ReporterConstants: any = { - /** - * Path to folder with load tests execution report. - */ - TS_SELENIUM_LOAD_TEST_REPORT_FOLDER: process.env.TS_SELENIUM_LOAD_TEST_REPORT_FOLDER || './load-test-folder', + /** + * Path to folder with load tests execution report. + */ + TS_SELENIUM_LOAD_TEST_REPORT_FOLDER: process.env.TS_SELENIUM_LOAD_TEST_REPORT_FOLDER || './load-test-folder', - /** - * Delay between screenshots catching in the milliseconds for the execution screencast. - */ - TS_SELENIUM_DELAY_BETWEEN_SCREENSHOTS: Number(process.env.TS_SELENIUM_DELAY_BETWEEN_SCREENSHOTS) || 1000, + /** + * Delay between screenshots catching in the milliseconds for the execution screencast. + */ + TS_SELENIUM_DELAY_BETWEEN_SCREENSHOTS: Number(process.env.TS_SELENIUM_DELAY_BETWEEN_SCREENSHOTS) || 1000, - /** - * Path to folder with tests execution report. - */ - TS_SELENIUM_REPORT_FOLDER: process.env.TS_SELENIUM_REPORT_FOLDER || './report', + /** + * Path to folder with tests execution report. + */ + TS_SELENIUM_REPORT_FOLDER: process.env.TS_SELENIUM_REPORT_FOLDER || './report', - /** - * Enable or disable storing of execution screencast, "false" by default. - */ - TS_SELENIUM_EXECUTION_SCREENCAST: process.env.TS_SELENIUM_EXECUTION_SCREENCAST === 'true', + /** + * Enable or disable storing of execution screencast, "false" by default. + */ + TS_SELENIUM_EXECUTION_SCREENCAST: process.env.TS_SELENIUM_EXECUTION_SCREENCAST === 'true', - /** - * Delete screencast after execution if all tests passed, "true" by default. - */ - DELETE_SCREENCAST_IF_TEST_PASS: process.env.DELETE_SCREENCAST_IF_TEST_PASS !== 'false', + /** + * Delete screencast after execution if all tests passed, "true" by default. + */ + DELETE_SCREENCAST_IF_TEST_PASS: process.env.DELETE_SCREENCAST_IF_TEST_PASS !== 'false', - /** - * Log level settings, possible variants: 'INFO' (by default), 'DEBUG', 'TRACE'. - */ - TS_SELENIUM_LOG_LEVEL: process.env.TS_SELENIUM_LOG_LEVEL || 'INFO', + /** + * Log level settings, possible variants: 'INFO' (by default), 'DEBUG', 'TRACE'. + */ + TS_SELENIUM_LOG_LEVEL: process.env.TS_SELENIUM_LOG_LEVEL || 'INFO', - /** - * Print all timeout variables when tests launch, default to false - */ - TS_SELENIUM_PRINT_TIMEOUT_VARIABLES: process.env.TS_SELENIUM_PRINT_TIMEOUT_VARIABLES || false, + /** + * Print all timeout variables when tests launch, default to false + */ + TS_SELENIUM_PRINT_TIMEOUT_VARIABLES: process.env.TS_SELENIUM_PRINT_TIMEOUT_VARIABLES || false }; diff --git a/tests/e2e/constants/TimeoutConstants.ts b/tests/e2e/constants/TimeoutConstants.ts index 3508e2688bf..d8524114ae7 100644 --- a/tests/e2e/constants/TimeoutConstants.ts +++ b/tests/e2e/constants/TimeoutConstants.ts @@ -9,105 +9,105 @@ **********************************************************************/ export const TimeoutConstants: any = { - /** - * Default amount of tries, "5" by default. - */ - TS_SELENIUM_DEFAULT_ATTEMPTS: Number(process.env.TS_SELENIUM_DEFAULT_ATTEMPTS) || 5, - - /** - * Default delay in milliseconds between tries, "1000" by default. - */ - TS_SELENIUM_DEFAULT_POLLING: Number(process.env.TS_SELENIUM_DEFAULT_POLLING) || 1000, - - // -------------------------------------------- INSTALLING AND STARTUP -------------------------------------------- - - /** - * Timeout waiting for url, "10 000" by default - */ - TS_SELENIUM_WAIT_FOR_URL: Number(process.env.TS_SELENIUM_WAIT_FOR_URL) || 10_000, - - /** - * Amount of tries for checking workspace status. - */ - TS_SELENIUM_WORKSPACE_STATUS_ATTEMPTS: Number(process.env.TS_SELENIUM_WORKSPACE_STATUS_ATTEMPTS) || 90, - - /** - * Delay in milliseconds between checking workspace status tries. - */ - TS_SELENIUM_WORKSPACE_STATUS_POLLING: Number(process.env.TS_SELENIUM_WORKSPACE_STATUS_POLLING) || 10000, - - /** - * Wait between workspace started and IDE ready to be used, "20 000" by default. - */ - TS_IDE_LOAD_TIMEOUT: Number(process.env.TS_IDE_LOAD_TIMEOUT) || 20_000, - - /** - * Timeout in milliseconds waiting for workspace start, "360 000" by default. - */ - TS_SELENIUM_START_WORKSPACE_TIMEOUT: Number(process.env.TS_SELENIUM_START_WORKSPACE_TIMEOUT) || 360_000, - - /** - * Timeout in milliseconds waiting for page load, "20 000" by default. - */ - TS_SELENIUM_LOAD_PAGE_TIMEOUT: Number(process.env.TS_SELENIUM_LOAD_PAGE_TIMEOUT) || 20_000, - - /** - * Wait for loader absence, "60 000" by default. - */ - TS_WAIT_LOADER_ABSENCE_TIMEOUT: Number(process.env.TS_WAIT_LOADER_ABSENCE_TIMEOUT) || 60_000, - - /** - * Wait for loader absence, "60 000" by default. - */ - TS_WAIT_LOADER_PRESENCE_TIMEOUT: Number(process.env.TS_WAIT_LOADER_PRESENCE_TIMEOUT) || 60_000, - - // -------------------------------------------- DASHBOARD -------------------------------------------- - - /** - * Common timeout for dashboard items, "5 000" by default - */ - TS_COMMON_DASHBOARD_WAIT_TIMEOUT: Number(process.env.TS_COMMON_DASHBOARD_WAIT_TIMEOUT) || 5_000, - - /** - * Timeout for clicking on dashboard menu items, "2 000" by default - */ - TS_CLICK_DASHBOARD_ITEM_TIMEOUT: Number(process.env.TS_CLICK_DASHBOARD_ITEM_TIMEOUT) || 2_000, - - /** - * Timeout for workspace stopped status, "30 000" by default - */ - TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT: Number(process.env.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT) || 30_000, - - // -------------------------------------------- PROJECT TREE -------------------------------------------- - - /** - * Expand item in project tree, "8 000" by default. - */ - TS_EXPAND_PROJECT_TREE_ITEM_TIMEOUT: Number(process.env.TS_EXPAND_PROJECT_TREE_ITEM_TIMEOUT) || 8_000, - - // -------------------------------------------- EDITOR -------------------------------------------- - - /** - * Timeout for inetractions with editor tab - wait, click, select, "8 000" by default. - */ - TS_EDITOR_TAB_INTERACTION_TIMEOUT: Number(process.env.TS_OPEN_PROJECT_TREE_TIMEOUT) || 8_000, - - // -------------------------------------------- IDE -------------------------------------------- - - /** - * Timeout for context menu manipulation, "10 000" by default - */ - TS_DIALOG_WINDOW_DEFAULT_TIMEOUT: Number(process.env.TS_DIALOG_WINDOW_DEFAULT_TIMEOUT) || 10_000, - - /** - * Timeout for clicking on visible item, "5 000" by default - */ - TS_SELENIUM_CLICK_ON_VISIBLE_ITEM: Number(process.env.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM) || 5_000, - - // ----------------------------------------- PLUGINS ----------------------------------------- - - /** - * Common timeout for plugins. - */ - TS_COMMON_PLUGIN_TEST_TIMEOUT: Number(process.env.TS_COMMON_PLUGIN_TEST_TIMEOUT) || 30_000 + /** + * Default amount of tries, "5" by default. + */ + TS_SELENIUM_DEFAULT_ATTEMPTS: Number(process.env.TS_SELENIUM_DEFAULT_ATTEMPTS) || 5, + + /** + * Default delay in milliseconds between tries, "1000" by default. + */ + TS_SELENIUM_DEFAULT_POLLING: Number(process.env.TS_SELENIUM_DEFAULT_POLLING) || 1000, + + // -------------------------------------------- INSTALLING AND STARTUP -------------------------------------------- + + /** + * Timeout waiting for url, "10 000" by default + */ + TS_SELENIUM_WAIT_FOR_URL: Number(process.env.TS_SELENIUM_WAIT_FOR_URL) || 10_000, + + /** + * Amount of tries for checking workspace status. + */ + TS_SELENIUM_WORKSPACE_STATUS_ATTEMPTS: Number(process.env.TS_SELENIUM_WORKSPACE_STATUS_ATTEMPTS) || 90, + + /** + * Delay in milliseconds between checking workspace status tries. + */ + TS_SELENIUM_WORKSPACE_STATUS_POLLING: Number(process.env.TS_SELENIUM_WORKSPACE_STATUS_POLLING) || 10000, + + /** + * Wait between workspace started and IDE ready to be used, "20 000" by default. + */ + TS_IDE_LOAD_TIMEOUT: Number(process.env.TS_IDE_LOAD_TIMEOUT) || 20_000, + + /** + * Timeout in milliseconds waiting for workspace start, "360 000" by default. + */ + TS_SELENIUM_START_WORKSPACE_TIMEOUT: Number(process.env.TS_SELENIUM_START_WORKSPACE_TIMEOUT) || 360_000, + + /** + * Timeout in milliseconds waiting for page load, "20 000" by default. + */ + TS_SELENIUM_LOAD_PAGE_TIMEOUT: Number(process.env.TS_SELENIUM_LOAD_PAGE_TIMEOUT) || 20_000, + + /** + * Wait for loader absence, "60 000" by default. + */ + TS_WAIT_LOADER_ABSENCE_TIMEOUT: Number(process.env.TS_WAIT_LOADER_ABSENCE_TIMEOUT) || 60_000, + + /** + * Wait for loader absence, "60 000" by default. + */ + TS_WAIT_LOADER_PRESENCE_TIMEOUT: Number(process.env.TS_WAIT_LOADER_PRESENCE_TIMEOUT) || 60_000, + + // -------------------------------------------- DASHBOARD -------------------------------------------- + + /** + * Common timeout for dashboard items, "5 000" by default + */ + TS_COMMON_DASHBOARD_WAIT_TIMEOUT: Number(process.env.TS_COMMON_DASHBOARD_WAIT_TIMEOUT) || 5_000, + + /** + * Timeout for clicking on dashboard menu items, "2 000" by default + */ + TS_CLICK_DASHBOARD_ITEM_TIMEOUT: Number(process.env.TS_CLICK_DASHBOARD_ITEM_TIMEOUT) || 2_000, + + /** + * Timeout for workspace stopped status, "30 000" by default + */ + TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT: Number(process.env.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT) || 30_000, + + // -------------------------------------------- PROJECT TREE -------------------------------------------- + + /** + * Expand item in project tree, "8 000" by default. + */ + TS_EXPAND_PROJECT_TREE_ITEM_TIMEOUT: Number(process.env.TS_EXPAND_PROJECT_TREE_ITEM_TIMEOUT) || 8_000, + + // -------------------------------------------- EDITOR -------------------------------------------- + + /** + * Timeout for inetractions with editor tab - wait, click, select, "8 000" by default. + */ + TS_EDITOR_TAB_INTERACTION_TIMEOUT: Number(process.env.TS_OPEN_PROJECT_TREE_TIMEOUT) || 8_000, + + // -------------------------------------------- IDE -------------------------------------------- + + /** + * Timeout for context menu manipulation, "10 000" by default + */ + TS_DIALOG_WINDOW_DEFAULT_TIMEOUT: Number(process.env.TS_DIALOG_WINDOW_DEFAULT_TIMEOUT) || 10_000, + + /** + * Timeout for clicking on visible item, "5 000" by default + */ + TS_SELENIUM_CLICK_ON_VISIBLE_ITEM: Number(process.env.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM) || 5_000, + + // ----------------------------------------- PLUGINS ----------------------------------------- + + /** + * Common timeout for plugins. + */ + TS_COMMON_PLUGIN_TEST_TIMEOUT: Number(process.env.TS_COMMON_PLUGIN_TEST_TIMEOUT) || 30_000 }; diff --git a/tests/e2e/driver/ChromeDriver.ts b/tests/e2e/driver/ChromeDriver.ts index d81e88281e9..52423b1b450 100644 --- a/tests/e2e/driver/ChromeDriver.ts +++ b/tests/e2e/driver/ChromeDriver.ts @@ -10,66 +10,66 @@ import 'chromedriver'; import 'reflect-metadata'; import { injectable } from 'inversify'; -import { ThenableWebDriver, Builder } from 'selenium-webdriver'; +import { Builder, ThenableWebDriver } from 'selenium-webdriver'; import { IDriver } from './IDriver'; import { Options } from 'selenium-webdriver/chrome'; import { ChromeDriverConstants } from '../constants/ChromeDriverConstants'; @injectable() export class ChromeDriver implements IDriver { - private readonly driver: ThenableWebDriver | undefined; + private readonly driver: ThenableWebDriver | undefined; - constructor() { - const options: Options = this.getDriverOptions(); - if (ChromeDriverConstants.TS_USE_WEB_DRIVER_FOR_TEST) { - this.driver = this.getDriverBuilder(options).build(); - } + constructor() { + const options: Options = this.getDriverOptions(); + if (ChromeDriverConstants.TS_USE_WEB_DRIVER_FOR_TEST) { + this.driver = this.getDriverBuilder(options).build(); } + } - get(): ThenableWebDriver { - return this.driver as ThenableWebDriver; - } + get(): ThenableWebDriver { + return this.driver as ThenableWebDriver; + } - async setWindowSize(): Promise { - await (this.driver as ThenableWebDriver) - .manage() - .window() - .setSize(ChromeDriverConstants.TS_SELENIUM_RESOLUTION_WIDTH, ChromeDriverConstants.TS_SELENIUM_RESOLUTION_HEIGHT); - } + async setWindowSize(): Promise { + await (this.driver as ThenableWebDriver) + .manage() + .window() + .setSize(ChromeDriverConstants.TS_SELENIUM_RESOLUTION_WIDTH, ChromeDriverConstants.TS_SELENIUM_RESOLUTION_HEIGHT); + } - private getDriverOptions(): Options { - let options: Options = new Options() - .addArguments('--no-sandbox') - .addArguments('--disable-web-security') - .addArguments('--allow-running-insecure-content') - .addArguments('--ignore-certificate-errors'); - // if 'true' run in 'headless' mode - if (ChromeDriverConstants.TS_SELENIUM_HEADLESS) { - options = options.addArguments('headless'); - } - return options; + private getDriverOptions(): Options { + let options: Options = new Options() + .addArguments('--no-sandbox') + .addArguments('--disable-web-security') + .addArguments('--allow-running-insecure-content') + .addArguments('--ignore-certificate-errors'); + // if 'true' run in 'headless' mode + if (ChromeDriverConstants.TS_SELENIUM_HEADLESS) { + options = options.addArguments('headless'); } + return options; + } - private getDriverBuilder(options: Options): Builder { - const disableW3copts: object = { 'goog:chromeOptions' : { 'w3c' : false }}; - let builder: Builder = new Builder() - .forBrowser('chrome') - .setChromeOptions(options); + private getDriverBuilder(options: Options): Builder { + const disableW3copts: object = { 'goog:chromeOptions': { 'w3c': false } }; + let builder: Builder = new Builder() + .forBrowser('chrome') + .setChromeOptions(options); - // if 'false' w3c protocol is disabled - if (! ChromeDriverConstants.TS_SELENIUM_W3C_CHROME_OPTION) { - builder.withCapabilities(disableW3copts) - .forBrowser('chrome') - .setChromeOptions(options); - } + // if 'false' w3c protocol is disabled + if (!ChromeDriverConstants.TS_SELENIUM_W3C_CHROME_OPTION) { + builder.withCapabilities(disableW3copts) + .forBrowser('chrome') + .setChromeOptions(options); + } - // if 'true' run with remote driver - if (ChromeDriverConstants.TS_SELENIUM_REMOTE_DRIVER_URL) { - builder = builder.usingServer(ChromeDriverConstants.TS_SELENIUM_REMOTE_DRIVER_URL); - } + // if 'true' run with remote driver + if (ChromeDriverConstants.TS_SELENIUM_REMOTE_DRIVER_URL) { + builder = builder.usingServer(ChromeDriverConstants.TS_SELENIUM_REMOTE_DRIVER_URL); + } - return builder; + return builder; - } + } } diff --git a/tests/e2e/driver/IDriver.ts b/tests/e2e/driver/IDriver.ts index d2f8e7213a8..ed130dbad1b 100644 --- a/tests/e2e/driver/IDriver.ts +++ b/tests/e2e/driver/IDriver.ts @@ -10,5 +10,5 @@ import { ThenableWebDriver } from 'selenium-webdriver'; export interface IDriver { - get(): ThenableWebDriver; + get(): ThenableWebDriver; } diff --git a/tests/e2e/pageobjects/dashboard/CreateWorkspace.ts b/tests/e2e/pageobjects/dashboard/CreateWorkspace.ts index 00c14285ced..cf7b68778f6 100644 --- a/tests/e2e/pageobjects/dashboard/CreateWorkspace.ts +++ b/tests/e2e/pageobjects/dashboard/CreateWorkspace.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { CLASSES } from '../../configs/inversify.types'; import { DriverHelper } from '../../utils/DriverHelper'; import { By, Key } from 'selenium-webdriver'; @@ -18,80 +18,80 @@ import { BaseTestConstants } from '../../constants/BaseTestConstants'; @injectable() export class CreateWorkspace { - static readonly FACTORY_URL_LOCATOR: By = By.xpath(`//input[@id="git-repo-url"]`); + static readonly FACTORY_URL_LOCATOR: By = By.xpath(`//input[@id="git-repo-url"]`); - constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - async waitTitleContains(expectedText: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(`text: "${expectedText}"`); + async waitTitleContains(expectedText: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(`text: "${expectedText}"`); - const pageTitleLocator: By = By.xpath(`//h1[contains(text(), '${expectedText}')]`); + const pageTitleLocator: By = By.xpath(`//h1[contains(text(), '${expectedText}')]`); - await this.driverHelper.waitVisibility(pageTitleLocator, timeout); - } + await this.driverHelper.waitVisibility(pageTitleLocator, timeout); + } - async waitPage(timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { - Logger.debug(); + async waitPage(timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { + Logger.debug(); - await this.waitTitleContains('Create Workspace', timeout); - } + await this.waitTitleContains('Create Workspace', timeout); + } - async clickOnSampleNoEditorSelection(sampleName: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - Logger.debug(`sampleName: "${sampleName}"`); + async clickOnSampleNoEditorSelection(sampleName: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + Logger.debug(`sampleName: "${sampleName}"`); - const sampleLocator: By = this.getSampleLocator(sampleName); + const sampleLocator: By = this.getSampleLocator(sampleName); - await this.driverHelper.waitAndClick(sampleLocator, timeout); - } + await this.driverHelper.waitAndClick(sampleLocator, timeout); + } - async clickOnSampleForSpecificEditor(sampleName: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - await this.clickOnEditorsDropdownListButton(sampleName, timeout); + async clickOnSampleForSpecificEditor(sampleName: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + await this.clickOnEditorsDropdownListButton(sampleName, timeout); - Logger.debug(`sampleName: "${sampleName}"`); + Logger.debug(`sampleName: "${sampleName}"`); - const sampleLocator: By = this.getSampleLocatorWithSpecificEditor(sampleName); - await this.driverHelper.waitAndClick(sampleLocator, timeout); - } + const sampleLocator: By = this.getSampleLocatorWithSpecificEditor(sampleName); + await this.driverHelper.waitAndClick(sampleLocator, timeout); + } - async importFromGitUsingUI(factoryUrl: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - Logger.debug(`factoryUrl: "${factoryUrl}"`); - await this.driverHelper.waitVisibility(CreateWorkspace.FACTORY_URL_LOCATOR, timeout); - await this.driverHelper.type(CreateWorkspace.FACTORY_URL_LOCATOR, Key.chord(factoryUrl, Key.ENTER), timeout); - } + async importFromGitUsingUI(factoryUrl: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + Logger.debug(`factoryUrl: "${factoryUrl}"`); + await this.driverHelper.waitVisibility(CreateWorkspace.FACTORY_URL_LOCATOR, timeout); + await this.driverHelper.type(CreateWorkspace.FACTORY_URL_LOCATOR, Key.chord(factoryUrl, Key.ENTER), timeout); + } - private async clickOnEditorsDropdownListButton(sampleName: string, timeout: number): Promise { - Logger.debug(`sampleName: "${sampleName}, editor ${BaseTestConstants.TS_SELENIUM_EDITOR}"`); + private async clickOnEditorsDropdownListButton(sampleName: string, timeout: number): Promise { + Logger.debug(`sampleName: "${sampleName}, editor ${BaseTestConstants.TS_SELENIUM_EDITOR}"`); - const editorDropdownListLocator: By = this.getEditorsDropdownListLocator(sampleName); - await this.driverHelper.waitAndClick(editorDropdownListLocator, timeout); - } + const editorDropdownListLocator: By = this.getEditorsDropdownListLocator(sampleName); + await this.driverHelper.waitAndClick(editorDropdownListLocator, timeout); + } - private getEditorsDropdownListLocator(sampleName: string): By { - return By.xpath(`//div[text()=\'${sampleName}\']//parent::article//button`); - } + private getEditorsDropdownListLocator(sampleName: string): By { + return By.xpath(`//div[text()=\'${sampleName}\']//parent::article//button`); + } - private getSampleLocatorWithSpecificEditor(sampleName: string): By { - let editor: string = ''; - switch (process.env.TS_SELENIUM_EDITOR) { - case 'che-code': - editor = 'code'; - break; - default: - throw new Error(`Unsupported editor ${process.env.TS_SELENIUM_EDITOR}`); - } + private getSampleLocatorWithSpecificEditor(sampleName: string): By { + let editor: string = ''; + switch (process.env.TS_SELENIUM_EDITOR) { + case 'che-code': + editor = 'code'; + break; + default: + throw new Error(`Unsupported editor ${process.env.TS_SELENIUM_EDITOR}`); + } - Logger.trace(`sampleName: ${sampleName}, editor "${editor}"`); + Logger.trace(`sampleName: ${sampleName}, editor "${editor}"`); - return By.xpath(`//div[text()='${sampleName}']//parent::article//span[text()[ + return By.xpath(`//div[text()='${sampleName}']//parent::article//span[text()[ contains( translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '${editor}')] ]//parent::a`); - } + } - private getSampleLocator(sampleName: string): By { - Logger.trace(`sampleName: ${sampleName}, used default editor`); + private getSampleLocator(sampleName: string): By { + Logger.trace(`sampleName: ${sampleName}, used default editor`); - return By.xpath(`//article[contains(@class, 'sample-card')]//div[text()='${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 33c653c14c2..f3ef7ca2a3d 100644 --- a/tests/e2e/pageobjects/dashboard/Dashboard.ts +++ b/tests/e2e/pageobjects/dashboard/Dashboard.ts @@ -19,100 +19,100 @@ import { BaseTestConstants } from '../../constants/BaseTestConstants'; @injectable() export class Dashboard { - private static readonly WORKSPACES_BUTTON: By = By.xpath(`//div[@id='page-sidebar']//a[contains(text(), 'Workspaces (')]`); - private static readonly CREATE_WORKSPACE_BUTTON: By = By.xpath(`//div[@id='page-sidebar']//a[text()='Create Workspace']`); - private static readonly LOADER_PAGE_STEP_TITLES: By = By.xpath('//*[@data-testid="step-title"]'); - private static readonly STARTING_PAGE_LOADER: By = By.css('.main-page-loader'); - private static readonly LOADER_ALERT: By = By.xpath('//*[@data-testid="loader-alert"]'); - private static readonly LOGOUT_BUTTON: By = By.xpath('//button[text()="Logout"]'); - private static readonly USER_SETTINGS_DROPDOWN: By = By.xpath('//header//button/span[text()!=\'\']//parent::button'); + private static readonly WORKSPACES_BUTTON: By = By.xpath(`//div[@id='page-sidebar']//a[contains(text(), 'Workspaces (')]`); + private static readonly CREATE_WORKSPACE_BUTTON: By = By.xpath(`//div[@id='page-sidebar']//a[text()='Create Workspace']`); + private static readonly LOADER_PAGE_STEP_TITLES: By = By.xpath('//*[@data-testid="step-title"]'); + private static readonly STARTING_PAGE_LOADER: By = By.css('.main-page-loader'); + private static readonly LOADER_ALERT: By = By.xpath('//*[@data-testid="loader-alert"]'); + private static readonly LOGOUT_BUTTON: By = By.xpath('//button[text()="Logout"]'); + private static readonly USER_SETTINGS_DROPDOWN: By = By.xpath('//header//button/span[text()!=\'\']//parent::button'); - constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper, - @inject(CLASSES.Workspaces) private readonly workspaces: Workspaces) { - } + constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper, + @inject(CLASSES.Workspaces) private readonly workspaces: Workspaces) { + } - async stopWorkspaceByUI(workspaceName: string): Promise { - Logger.debug(`"${workspaceName}"`); + async stopWorkspaceByUI(workspaceName: string): Promise { + Logger.debug(`"${workspaceName}"`); - await this.clickWorkspacesButton(); - await this.workspaces.waitPage(); - await this.workspaces.waitWorkspaceListItem(workspaceName); - await this.workspaces.waitWorkspaceWithRunningStatus(workspaceName); + await this.clickWorkspacesButton(); + await this.workspaces.waitPage(); + await this.workspaces.waitWorkspaceListItem(workspaceName); + await this.workspaces.waitWorkspaceWithRunningStatus(workspaceName); - await this.workspaces.stopWorkspaceByActionsButton(workspaceName); - await this.workspaces.waitWorkspaceWithStoppedStatus(workspaceName); - } + await this.workspaces.stopWorkspaceByActionsButton(workspaceName); + await this.workspaces.waitWorkspaceWithStoppedStatus(workspaceName); + } - async deleteStoppedWorkspaceByUI(workspaceName: string): Promise { - Logger.debug(`"${workspaceName}"`); + async deleteStoppedWorkspaceByUI(workspaceName: string): Promise { + Logger.debug(`"${workspaceName}"`); - await this.clickWorkspacesButton(); - await this.workspaces.waitPage(); - await this.workspaces.waitWorkspaceListItem(workspaceName); - await this.workspaces.deleteWorkspaceByActionsButton(workspaceName); - await this.workspaces.waitPage(); - await this.workspaces.waitWorkspaceListItemAbsence(workspaceName); - } + await this.clickWorkspacesButton(); + await this.workspaces.waitPage(); + await this.workspaces.waitWorkspaceListItem(workspaceName); + await this.workspaces.deleteWorkspaceByActionsButton(workspaceName); + await this.workspaces.waitPage(); + await this.workspaces.waitWorkspaceListItemAbsence(workspaceName); + } - async stopAndRemoveWorkspaceByUI(workspaceName: string): Promise { - Logger.debug(`"${workspaceName}"`); + async stopAndRemoveWorkspaceByUI(workspaceName: string): Promise { + Logger.debug(`"${workspaceName}"`); - await this.stopWorkspaceByUI(workspaceName); - await this.workspaces.deleteWorkspaceByActionsButton(workspaceName); - await this.workspaces.waitWorkspaceListItemAbsence(workspaceName); - } + await this.stopWorkspaceByUI(workspaceName); + await this.workspaces.deleteWorkspaceByActionsButton(workspaceName); + await this.workspaces.waitWorkspaceListItemAbsence(workspaceName); + } - async openDashboard(): Promise { - Logger.debug(); - await this.driverHelper.getDriver().navigate().to(BaseTestConstants.TS_SELENIUM_BASE_URL); - await this.waitPage(); + async openDashboard(): Promise { + Logger.debug(); + await this.driverHelper.getDriver().navigate().to(BaseTestConstants.TS_SELENIUM_BASE_URL); + await this.waitPage(); - } + } - async waitPage(timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { - Logger.debug(); + async waitPage(timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitVisibility(Dashboard.WORKSPACES_BUTTON, timeout); - await this.driverHelper.waitVisibility(Dashboard.CREATE_WORKSPACE_BUTTON, timeout); - } + await this.driverHelper.waitVisibility(Dashboard.WORKSPACES_BUTTON, timeout); + await this.driverHelper.waitVisibility(Dashboard.CREATE_WORKSPACE_BUTTON, timeout); + } - async clickWorkspacesButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - Logger.debug(); + async clickWorkspacesButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(Dashboard.WORKSPACES_BUTTON, timeout); - } + await this.driverHelper.waitAndClick(Dashboard.WORKSPACES_BUTTON, timeout); + } - async clickCreateWorkspaceButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - Logger.debug(); + async clickCreateWorkspaceButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(Dashboard.CREATE_WORKSPACE_BUTTON, timeout); - } + await this.driverHelper.waitAndClick(Dashboard.CREATE_WORKSPACE_BUTTON, timeout); + } - async getLoaderAlert(timeout: number = TimeoutConstants.TS_WAIT_LOADER_PRESENCE_TIMEOUT): Promise { - Logger.debug(); + async getLoaderAlert(timeout: number = TimeoutConstants.TS_WAIT_LOADER_PRESENCE_TIMEOUT): Promise { + Logger.debug(); - return await this.driverHelper.waitAndGetText(Dashboard.LOADER_ALERT, timeout); - } + return await this.driverHelper.waitAndGetText(Dashboard.LOADER_ALERT, timeout); + } - async waitLoader(timeout: number = TimeoutConstants.TS_WAIT_LOADER_PRESENCE_TIMEOUT): Promise { - Logger.debug(); + async waitLoader(timeout: number = TimeoutConstants.TS_WAIT_LOADER_PRESENCE_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitAllPresence(Dashboard.LOADER_PAGE_STEP_TITLES, timeout); - } + await this.driverHelper.waitAllPresence(Dashboard.LOADER_PAGE_STEP_TITLES, timeout); + } - async waitStartingPageLoaderDisappearance(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(); + async waitStartingPageLoaderDisappearance(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitDisappearance(Dashboard.STARTING_PAGE_LOADER, timeout); - await this.driverHelper.wait(TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING); - } + await this.driverHelper.waitDisappearance(Dashboard.STARTING_PAGE_LOADER, timeout); + await this.driverHelper.wait(TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING); + } - async logout(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(); + async logout(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(); - await this.openDashboard(); - await this.driverHelper.waitAndClick(Dashboard.USER_SETTINGS_DROPDOWN, timeout); - await this.driverHelper.waitAndClick(Dashboard.LOGOUT_BUTTON, timeout); - await this.driverHelper.waitDisappearance(Dashboard.USER_SETTINGS_DROPDOWN, timeout); - } + await this.openDashboard(); + await this.driverHelper.waitAndClick(Dashboard.USER_SETTINGS_DROPDOWN, timeout); + await this.driverHelper.waitAndClick(Dashboard.LOGOUT_BUTTON, timeout); + await this.driverHelper.waitDisappearance(Dashboard.USER_SETTINGS_DROPDOWN, timeout); + } } diff --git a/tests/e2e/pageobjects/dashboard/Workspaces.ts b/tests/e2e/pageobjects/dashboard/Workspaces.ts index 3258f60469b..5ebbf58a43e 100644 --- a/tests/e2e/pageobjects/dashboard/Workspaces.ts +++ b/tests/e2e/pageobjects/dashboard/Workspaces.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { DriverHelper } from '../../utils/DriverHelper'; import { CLASSES } from '../../configs/inversify.types'; import { By, WebElement } from 'selenium-webdriver'; @@ -16,200 +16,199 @@ import { Logger } from '../../utils/Logger'; import { TimeoutConstants } from '../../constants/TimeoutConstants'; export enum WorkspaceStatusUI { - Running = 'green', - Stopped = 'grey' + Running = 'green', + Stopped = 'grey' } @injectable() export class Workspaces { - private static readonly ADD_WORKSPACE_BUTTON_XPATH: string = `//button[text()='Add Workspace']`; - private static readonly WORKSPACE_ITEM_TABLE_NAME_SECTION_XPATH: string = `//td[@data-label="Name"]/span/a`; + private static readonly ADD_WORKSPACE_BUTTON_XPATH: string = `//button[text()='Add Workspace']`; + private static readonly WORKSPACE_ITEM_TABLE_NAME_SECTION_XPATH: string = `//td[@data-label="Name"]/span/a`; - constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { - } + constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { + } - async waitPage(timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { - Logger.debug(); + async waitPage(timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitVisibility(By.xpath(Workspaces.ADD_WORKSPACE_BUTTON_XPATH), timeout); - } + await this.driverHelper.waitVisibility(By.xpath(Workspaces.ADD_WORKSPACE_BUTTON_XPATH), timeout); + } - async clickAddWorkspaceButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - Logger.debug(); + async clickAddWorkspaceButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(By.xpath(Workspaces.ADD_WORKSPACE_BUTTON_XPATH), timeout); - } + await this.driverHelper.waitAndClick(By.xpath(Workspaces.ADD_WORKSPACE_BUTTON_XPATH), timeout); + } - async clickOpenButton(workspaceName: string, timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { - Logger.debug(); + async clickOpenButton(workspaceName: string, timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(this.getOpenButtonLocator(workspaceName), timeout); - } + await this.driverHelper.waitAndClick(this.getOpenButtonLocator(workspaceName), timeout); + } - async waitWorkspaceListItem(workspaceName: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(`"${workspaceName}"`); + async waitWorkspaceListItem(workspaceName: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(`"${workspaceName}"`); - const workspaceListItemLocator: By = By.xpath(this.getWorkspaceListItemLocator(workspaceName)); + const workspaceListItemLocator: By = By.xpath(this.getWorkspaceListItemLocator(workspaceName)); - await this.driverHelper.waitVisibility(workspaceListItemLocator, timeout); - } + await this.driverHelper.waitVisibility(workspaceListItemLocator, timeout); + } - async waitWorkspaceWithRunningStatus(workspaceName: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(`"${workspaceName}"`); + async waitWorkspaceWithRunningStatus(workspaceName: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(`"${workspaceName}"`); - const runningStatusLocator: By = this.getWorkspaceStatusLocator(workspaceName, WorkspaceStatusUI.Running); + const runningStatusLocator: By = this.getWorkspaceStatusLocator(workspaceName, WorkspaceStatusUI.Running); - await this.driverHelper.waitVisibility(runningStatusLocator, timeout); - } + await this.driverHelper.waitVisibility(runningStatusLocator, timeout); + } - async waitWorkspaceWithStoppedStatus(workspaceName: string, timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { - Logger.debug(`"${workspaceName}"`); + async waitWorkspaceWithStoppedStatus(workspaceName: string, timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { + Logger.debug(`"${workspaceName}"`); - const stoppedStatusLocator: By = this.getWorkspaceStatusLocator(workspaceName, WorkspaceStatusUI.Stopped); + const stoppedStatusLocator: By = this.getWorkspaceStatusLocator(workspaceName, WorkspaceStatusUI.Stopped); - await this.driverHelper.waitVisibility(stoppedStatusLocator, timeout); - } + await this.driverHelper.waitVisibility(stoppedStatusLocator, timeout); + } - async clickWorkspaceListItem(workspaceName: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - Logger.debug(`"${workspaceName}"`); + async clickWorkspaceListItem(workspaceName: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + Logger.debug(`"${workspaceName}"`); - const workspaceListItemLocator: By = By.xpath(this.getWorkspaceListItemLocator(workspaceName)); + const workspaceListItemLocator: By = By.xpath(this.getWorkspaceListItemLocator(workspaceName)); - await this.driverHelper.waitAndClick(workspaceListItemLocator, timeout); - } + await this.driverHelper.waitAndClick(workspaceListItemLocator, timeout); + } - async clickActionsButton(workspaceName: string): Promise { - Logger.debug(`of the '${workspaceName}' list item`); + async clickActionsButton(workspaceName: string): Promise { + Logger.debug(`of the '${workspaceName}' list item`); - await this.driverHelper.waitAndClick(this.getActionsLocator(workspaceName)); - } + await this.driverHelper.waitAndClick(this.getActionsLocator(workspaceName)); + } - async waitActionsPopup(workspaceName: string, timeout: number = TimeoutConstants.TS_CONTEXT_MENU_TIMEOUT): Promise { - Logger.debug(`of the '${workspaceName}' list item`); + async waitActionsPopup(workspaceName: string, timeout: number = TimeoutConstants.TS_CONTEXT_MENU_TIMEOUT): Promise { + Logger.debug(`of the '${workspaceName}' list item`); - await this.driverHelper.waitVisibility(this.getExpandedActionsLocator(workspaceName), timeout); - } + await this.driverHelper.waitVisibility(this.getExpandedActionsLocator(workspaceName), timeout); + } - async openActionsPopup(workspaceName: string, timeout: number = TimeoutConstants.TS_CONTEXT_MENU_TIMEOUT): Promise { - Logger.debug(`for the '${workspaceName}' list item`); - await this.clickActionsButton(workspaceName); - await this.waitActionsPopup(workspaceName, timeout); - } + async openActionsPopup(workspaceName: string, timeout: number = TimeoutConstants.TS_CONTEXT_MENU_TIMEOUT): Promise { + Logger.debug(`for the '${workspaceName}' list item`); + await this.clickActionsButton(workspaceName); + await this.waitActionsPopup(workspaceName, timeout); + } - async clickActionsDeleteButton(workspaceName: string): Promise { - Logger.debug(`for the '${workspaceName}' list item`); + async clickActionsDeleteButton(workspaceName: string): Promise { + Logger.debug(`for the '${workspaceName}' list item`); - await this.driverHelper.waitAndClick(this.getActionsPopupButtonLocator(workspaceName, 'Delete Workspace')); - } + await this.driverHelper.waitAndClick(this.getActionsPopupButtonLocator(workspaceName, 'Delete Workspace')); + } + + async clickActionsStopWorkspaceButton(workspaceName: string): Promise { + Logger.debug(`for the '${workspaceName}' list item`); + // todo: workaround because of issue CRW-3649 + try { + await this.driverHelper.waitAndClick(this.getActionsPopupButtonLocator(workspaceName, 'Stop Workspace')); + } catch (e) { + Logger.warn(`for the '${workspaceName}' list item - popup was missed, try to click one more time (issue CRW-3649).`); - async clickActionsStopWorkspaceButton(workspaceName: string): Promise { - Logger.debug(`for the '${workspaceName}' list item`); - // todo: workaround because of issue CRW-3649 - try { - await this.driverHelper.waitAndClick(this.getActionsPopupButtonLocator(workspaceName, 'Stop Workspace')); - } catch (e) { - Logger.warn(`for the '${workspaceName}' list item - popup was missed, try to click one more time (issue CRW-3649).`); - - await this.driverHelper.waitAndClick(this.getActionsLocator(workspaceName)); - await this.driverHelper.waitAndClick(this.getActionsPopupButtonLocator(workspaceName, 'Stop Workspace')); - } + await this.driverHelper.waitAndClick(this.getActionsLocator(workspaceName)); + await this.driverHelper.waitAndClick(this.getActionsPopupButtonLocator(workspaceName, 'Stop Workspace')); } + } - async waitDeleteWorkspaceConfirmationWindow(timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { - Logger.debug(); + async waitDeleteWorkspaceConfirmationWindow(timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { + Logger.debug(); - const confirmationWindowLocator: By = By.xpath(`//div[@aria-label='Delete workspaces confirmation window']`); + const confirmationWindowLocator: By = By.xpath(`//div[@aria-label='Delete workspaces confirmation window']`); - await this.driverHelper.waitVisibility(confirmationWindowLocator, timeout); - } + await this.driverHelper.waitVisibility(confirmationWindowLocator, timeout); + } + async clickToDeleteConfirmationCheckbox(timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { + Logger.debug(`Workspaces.clickToDeleteConfirmationCheckbox`); - async clickToDeleteConfirmationCheckbox(timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { - Logger.debug(`Workspaces.clickToDeleteConfirmationCheckbox`); + const deleteConfirmationCheckboxLocator: By = By.xpath(`//input[@data-testid='confirmation-checkbox']`); - const deleteConfirmationCheckboxLocator: By = By.xpath(`//input[@data-testid='confirmation-checkbox']`); + await this.driverHelper.waitAndClick(deleteConfirmationCheckboxLocator, timeout); + } - await this.driverHelper.waitAndClick(deleteConfirmationCheckboxLocator, timeout); - } + async waitAndClickEnabledConfirmationWindowDeleteButton(timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { + Logger.debug(`Workspaces.waitEnabledConfirmationWindowDeleteButton`); - async waitAndClickEnabledConfirmationWindowDeleteButton(timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { - Logger.debug(`Workspaces.waitEnabledConfirmationWindowDeleteButton`); + const enabledConfirmationWindowDeleteButton: By = By.xpath(`//button[@data-testid='delete-workspace-button' and not(@disabled)]`); - const enabledConfirmationWindowDeleteButton: By = By.xpath(`//button[@data-testid='delete-workspace-button' and not(@disabled)]`); + await this.driverHelper.waitAndClick(enabledConfirmationWindowDeleteButton, timeout); + } - await this.driverHelper.waitAndClick(enabledConfirmationWindowDeleteButton, timeout); - } + async deleteWorkspaceByActionsButton(workspaceName: string, timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { + Logger.debug('Workspaces.deleteWorkspaceByActionsButton'); - async deleteWorkspaceByActionsButton(workspaceName: string, timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { - Logger.debug('Workspaces.deleteWorkspaceByActionsButton'); + await this.waitWorkspaceListItem(workspaceName, timeout); + await this.openActionsPopup(workspaceName, timeout); + await this.clickActionsDeleteButton(workspaceName); + await this.waitDeleteWorkspaceConfirmationWindow(timeout); + await this.clickToDeleteConfirmationCheckbox(timeout); + await this.waitAndClickEnabledConfirmationWindowDeleteButton(timeout); + } - await this.waitWorkspaceListItem(workspaceName, timeout); - await this.openActionsPopup(workspaceName, timeout); - await this.clickActionsDeleteButton(workspaceName); - await this.waitDeleteWorkspaceConfirmationWindow(timeout); - await this.clickToDeleteConfirmationCheckbox(timeout); - await this.waitAndClickEnabledConfirmationWindowDeleteButton(timeout); - } + async stopWorkspaceByActionsButton(workspaceName: string, timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { + Logger.debug('Workspaces.stopWorkspaceByActionsButton'); - async stopWorkspaceByActionsButton(workspaceName: string, timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { - Logger.debug('Workspaces.stopWorkspaceByActionsButton'); + await this.waitWorkspaceListItem(workspaceName, timeout); + await this.openActionsPopup(workspaceName, timeout); + await this.clickActionsStopWorkspaceButton(workspaceName); + } - await this.waitWorkspaceListItem(workspaceName, timeout); - await this.openActionsPopup(workspaceName, timeout); - await this.clickActionsStopWorkspaceButton(workspaceName); - } + async waitWorkspaceListItemAbsence(workspaceName: string, timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { + Logger.debug(`Workspaces.waitWorkspaceListItemAbsence "${workspaceName}"`); - async waitWorkspaceListItemAbsence(workspaceName: string, timeout: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT): Promise { - Logger.debug(`Workspaces.waitWorkspaceListItemAbsence "${workspaceName}"`); + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); + const workspaceListItemLocator: By = By.xpath(this.getWorkspaceListItemLocator(workspaceName)); - const workspaceListItemLocator: By = By.xpath(this.getWorkspaceListItemLocator(workspaceName)); + await this.driverHelper.waitDisappearance(workspaceListItemLocator, attempts, polling); + } - await this.driverHelper.waitDisappearance(workspaceListItemLocator, attempts, polling); - } + async getAllCreatedWorkspacesNames(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug('Workspaces.getAllCreatedWorkspacesNames'); - async getAllCreatedWorkspacesNames(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug('Workspaces.getAllCreatedWorkspacesNames'); - - const workspaceNames: string[] = []; - try { - const workspaceItems: WebElement[] = await this.driverHelper.waitAllPresence(By.xpath(Workspaces.WORKSPACE_ITEM_TABLE_NAME_SECTION_XPATH), timeout); - for (let item of workspaceItems) { - Logger.debug(`Workspaces.getAllCreatedWorkspacesNames - try to get ${workspaceItems.indexOf(item)} items name`); - workspaceNames.push(await item.getText()); - Logger.debug(`Workspaces.getAllCreatedWorkspacesNames - workspace name is "${workspaceNames[workspaceNames.length - 1]}"`); - } - } catch (e) { - Logger.debug(`Workspaces.getAllCreatedWorkspacesNames - ${e}`); - } - - Logger.debug(`Workspaces.getAllCreatedWorkspacesNames - ${workspaceNames.length} workspaces have been created in DevSpaces`); - return workspaceNames; + const workspaceNames: string[] = []; + try { + const workspaceItems: WebElement[] = await this.driverHelper.waitAllPresence(By.xpath(Workspaces.WORKSPACE_ITEM_TABLE_NAME_SECTION_XPATH), timeout); + for (let item of workspaceItems) { + Logger.debug(`Workspaces.getAllCreatedWorkspacesNames - try to get ${workspaceItems.indexOf(item)} items name`); + workspaceNames.push(await item.getText()); + Logger.debug(`Workspaces.getAllCreatedWorkspacesNames - workspace name is "${workspaceNames[workspaceNames.length - 1]}"`); + } + } catch (e) { + Logger.debug(`Workspaces.getAllCreatedWorkspacesNames - ${e}`); } - private getWorkspaceListItemLocator(workspaceName: string): string { - return `//tr[td/span/a[text()='${workspaceName}']]`; - } + Logger.debug(`Workspaces.getAllCreatedWorkspacesNames - ${workspaceNames.length} workspaces have been created in DevSpaces`); + return workspaceNames; + } - private getWorkspaceStatusLocator(workspaceName: string, workspaceStatus: WorkspaceStatusUI): By { - return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}//span[@data-testid='workspace-status-indicator']//*[local-name()='svg' and @fill='${workspaceStatus}']`); - } + private getWorkspaceListItemLocator(workspaceName: string): string { + return `//tr[td/span/a[text()='${workspaceName}']]`; + } - private getActionsLocator(workspaceName: string): By { - return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}/td/div/button[@aria-label='Actions']`); - } + private getWorkspaceStatusLocator(workspaceName: string, workspaceStatus: WorkspaceStatusUI): By { + return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}//span[@data-testid='workspace-status-indicator']//*[local-name()='svg' and @fill='${workspaceStatus}']`); + } - private getExpandedActionsLocator(workspaceName: string): By { - return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}//button[@aria-label='Actions' and @aria-expanded='true']`); - } + private getActionsLocator(workspaceName: string): By { + return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}/td/div/button[@aria-label='Actions']`); + } - private getActionsPopupButtonLocator(workspaceName: string, buttonText: string): By { - return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}//li[@role='menuitem']//button[text()='${buttonText}']`); - } + private getExpandedActionsLocator(workspaceName: string): By { + return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}//button[@aria-label='Actions' and @aria-expanded='true']`); + } - private getOpenButtonLocator(workspaceName: string): By { - return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}//td[@data-key=5]//a[text()='Open']`); - } + private getActionsPopupButtonLocator(workspaceName: string, buttonText: string): By { + return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}//li[@role='menuitem']//button[text()='${buttonText}']`); + } + + private getOpenButtonLocator(workspaceName: string): By { + return By.xpath(`${this.getWorkspaceListItemLocator(workspaceName)}//td[@data-key=5]//a[text()='Open']`); + } } diff --git a/tests/e2e/pageobjects/dashboard/workspace-details/WorkspaceDetails.ts b/tests/e2e/pageobjects/dashboard/workspace-details/WorkspaceDetails.ts index 8f16408638d..529736ba1f6 100644 --- a/tests/e2e/pageobjects/dashboard/workspace-details/WorkspaceDetails.ts +++ b/tests/e2e/pageobjects/dashboard/workspace-details/WorkspaceDetails.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ import { DriverHelper } from '../../../utils/DriverHelper'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { CLASSES, TYPES } from '../../../configs/inversify.types'; import 'reflect-metadata'; import { By } from 'selenium-webdriver'; @@ -20,133 +20,132 @@ import { ProjectAndFileTests } from '../../../tests-library/ProjectAndFileTests' @injectable() export class WorkspaceDetails { - private static readonly RUN_BUTTON_CSS: string = '#run-workspace-button[che-button-title=\'Run\']'; - private static readonly OPEN_BUTTON_CSS: string = '#open-in-ide-button[che-button-title=\'Open\']'; - private static readonly SAVE_BUTTON_CSS: string = 'button[name=\'save-button\']'; - private static readonly ENABLED_SAVE_BUTTON_CSS: string = 'button[name=\'save-button\'][aria-disabled=\'false\']'; - private static readonly WORKSPACE_DETAILS_LOADER_CSS: string = 'workspace-details-overview md-progress-linear'; + private static readonly RUN_BUTTON_CSS: string = '#run-workspace-button[che-button-title=\'Run\']'; + private static readonly OPEN_BUTTON_CSS: string = '#open-in-ide-button[che-button-title=\'Open\']'; + private static readonly SAVE_BUTTON_CSS: string = 'button[name=\'save-button\']'; + private static readonly ENABLED_SAVE_BUTTON_CSS: string = 'button[name=\'save-button\'][aria-disabled=\'false\']'; + private static readonly WORKSPACE_DETAILS_LOADER_CSS: string = 'workspace-details-overview md-progress-linear'; - constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper, - @inject(TYPES.WorkspaceUtil) private readonly testWorkspaceUtil: ITestWorkspaceUtil, - @inject(CLASSES.ProjectAndFileTests) private readonly testProjectAndFileCheCode: ProjectAndFileTests) { } + constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper, + @inject(TYPES.WorkspaceUtil) private readonly testWorkspaceUtil: ITestWorkspaceUtil, + @inject(CLASSES.ProjectAndFileTests) private readonly testProjectAndFileCheCode: ProjectAndFileTests) { } - async waitLoaderDisappearance(attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { - Logger.debug(); + async waitLoaderDisappearance(attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { + Logger.debug(); - await this.driverHelper.waitDisappearance(By.css(WorkspaceDetails.WORKSPACE_DETAILS_LOADER_CSS), attempts, polling); - } + await this.driverHelper.waitDisappearance(By.css(WorkspaceDetails.WORKSPACE_DETAILS_LOADER_CSS), attempts, polling); + } - async saveChanges(): Promise { - Logger.debug(); + async saveChanges(): Promise { + Logger.debug(); - await this.waitSaveButton(); - await this.clickOnSaveButton(); - await this.waitSaveButtonDisappearance(); - } + await this.waitSaveButton(); + await this.clickOnSaveButton(); + await this.waitSaveButtonDisappearance(); + } - async waitPage(workspaceName: string, timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { - Logger.debug(`workspace: "${workspaceName}"`); + async waitPage(workspaceName: string, timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { + Logger.debug(`workspace: "${workspaceName}"`); - await this.waitWorkspaceTitle(workspaceName, timeout); - await this.waitOpenButton(timeout); - await this.waitRunButton(timeout); - await this.waitTabsPresence(timeout); - await this.waitLoaderDisappearance(timeout); - } + await this.waitWorkspaceTitle(workspaceName, timeout); + await this.waitOpenButton(timeout); + await this.waitRunButton(timeout); + await this.waitTabsPresence(timeout); + await this.waitLoaderDisappearance(timeout); + } - async waitWorkspaceTitle(workspaceName: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(`title: "${workspaceName}"`); + async waitWorkspaceTitle(workspaceName: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(`title: "${workspaceName}"`); - const workspaceTitleLocator: By = By.css(this.getWorkspaceTitleCssLocator(workspaceName)); + const workspaceTitleLocator: By = By.css(this.getWorkspaceTitleCssLocator(workspaceName)); - await this.driverHelper.waitVisibility(workspaceTitleLocator, timeout); - } + await this.driverHelper.waitVisibility(workspaceTitleLocator, timeout); + } - async waitRunButton(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(); + async waitRunButton(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitVisibility(By.css(WorkspaceDetails.RUN_BUTTON_CSS), timeout); - } + await this.driverHelper.waitVisibility(By.css(WorkspaceDetails.RUN_BUTTON_CSS), timeout); + } - async clickOnRunButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - Logger.debug(); + async clickOnRunButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(By.css(WorkspaceDetails.RUN_BUTTON_CSS), timeout); - } + await this.driverHelper.waitAndClick(By.css(WorkspaceDetails.RUN_BUTTON_CSS), timeout); + } - async waitOpenButton(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(); + async waitOpenButton(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(); - await this.driverHelper.waitVisibility(By.css(WorkspaceDetails.OPEN_BUTTON_CSS), timeout); - } + await this.driverHelper.waitVisibility(By.css(WorkspaceDetails.OPEN_BUTTON_CSS), timeout); + } - async openWorkspace(namespace: string, workspaceName: string, timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { - Logger.debug(`"${namespace}/${workspaceName}"`); + async openWorkspace(namespace: string, workspaceName: string, timeout: number = TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT): Promise { + Logger.debug(`"${namespace}/${workspaceName}"`); - await this.clickOnOpenButton(timeout); - await this.testProjectAndFileCheCode.waitWorkspaceReadinessForCheCodeEditor(); - await this.testWorkspaceUtil.waitWorkspaceStatus(namespace, workspaceName, WorkspaceStatus.STARTING); - } + await this.clickOnOpenButton(timeout); + await this.testProjectAndFileCheCode.waitWorkspaceReadinessForCheCodeEditor(); + await this.testWorkspaceUtil.waitWorkspaceStatus(namespace, workspaceName, WorkspaceStatus.STARTING); + } - async waitTabsPresence(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug('WorkspaceDetails.waitTabsPresence'); + async waitTabsPresence(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug('WorkspaceDetails.waitTabsPresence'); - const workspaceDetailsTabs: Array = ['Overview', 'Projects', 'Containers', 'Servers', - 'Env Variables', 'Volumes', 'Config', 'SSH', 'Plugins', 'Editors']; + const workspaceDetailsTabs: Array = ['Overview', 'Projects', 'Containers', 'Servers', + 'Env Variables', 'Volumes', 'Config', 'SSH', 'Plugins', 'Editors']; - for (const tabTitle of workspaceDetailsTabs) { - const workspaceDetailsTabLocator: By = By.xpath(this.getTabXpathLocator(tabTitle)); + for (const tabTitle of workspaceDetailsTabs) { + const workspaceDetailsTabLocator: By = By.xpath(this.getTabXpathLocator(tabTitle)); - await this.driverHelper.waitVisibility(workspaceDetailsTabLocator, timeout); - } + await this.driverHelper.waitVisibility(workspaceDetailsTabLocator, timeout); } + } - async selectTab(tabTitle: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - Logger.debug(`WorkspaceDetails.selectTab ${tabTitle}`); + async selectTab(tabTitle: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + Logger.debug(`WorkspaceDetails.selectTab ${tabTitle}`); - await this.clickOnTab(tabTitle, timeout); - await this.waitTabSelected(tabTitle, timeout); - } + await this.clickOnTab(tabTitle, timeout); + await this.waitTabSelected(tabTitle, timeout); + } - private getWorkspaceTitleCssLocator(workspaceName: string): string { - return `che-row-toolbar[che-title='${workspaceName}']`; - } + private getWorkspaceTitleCssLocator(workspaceName: string): string { + return `che-row-toolbar[che-title='${workspaceName}']`; + } - private getTabXpathLocator(tabTitle: string): string { - return `//md-tabs-canvas//md-tab-item//span[text()='${tabTitle}']`; - } + private getTabXpathLocator(tabTitle: string): string { + return `//md-tabs-canvas//md-tab-item//span[text()='${tabTitle}']`; + } - private getSelectedTabXpathLocator(tabTitle: string): string { - return `//md-tabs-canvas[@role='tablist']//md-tab-item[@aria-selected='true']//span[text()='${tabTitle}']`; - } + private getSelectedTabXpathLocator(tabTitle: string): string { + return `//md-tabs-canvas[@role='tablist']//md-tab-item[@aria-selected='true']//span[text()='${tabTitle}']`; + } - private async waitSaveButton(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - await this.driverHelper.waitVisibility(By.css(WorkspaceDetails.ENABLED_SAVE_BUTTON_CSS), timeout); - } + private async waitSaveButton(timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + await this.driverHelper.waitVisibility(By.css(WorkspaceDetails.ENABLED_SAVE_BUTTON_CSS), timeout); + } - private async waitSaveButtonDisappearance(attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { - await this.driverHelper.waitDisappearance(By.css(WorkspaceDetails.SAVE_BUTTON_CSS), attempts, polling); - } + private async waitSaveButtonDisappearance(attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { + await this.driverHelper.waitDisappearance(By.css(WorkspaceDetails.SAVE_BUTTON_CSS), attempts, polling); + } - private async clickOnSaveButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - await this.driverHelper.waitAndClick(By.css(WorkspaceDetails.ENABLED_SAVE_BUTTON_CSS), timeout); - } + private async clickOnSaveButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + await this.driverHelper.waitAndClick(By.css(WorkspaceDetails.ENABLED_SAVE_BUTTON_CSS), timeout); + } - private async clickOnOpenButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - await this.driverHelper.waitAndClick(By.css(WorkspaceDetails.OPEN_BUTTON_CSS), timeout); - } - - private async clickOnTab(tabTitle: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { - const workspaceDetailsTabLocator: By = By.xpath(this.getTabXpathLocator(tabTitle)); + private async clickOnOpenButton(timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + await this.driverHelper.waitAndClick(By.css(WorkspaceDetails.OPEN_BUTTON_CSS), timeout); + } + private async clickOnTab(tabTitle: string, timeout: number = TimeoutConstants.TS_CLICK_DASHBOARD_ITEM_TIMEOUT): Promise { + const workspaceDetailsTabLocator: By = By.xpath(this.getTabXpathLocator(tabTitle)); - await this.driverHelper.waitAndClick(workspaceDetailsTabLocator, timeout); - } + await this.driverHelper.waitAndClick(workspaceDetailsTabLocator, timeout); + } - private async waitTabSelected(tabTitle: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { - const selectedTabLocator: By = By.xpath(this.getSelectedTabXpathLocator(tabTitle)); + private async waitTabSelected(tabTitle: string, timeout: number = TimeoutConstants.TS_COMMON_DASHBOARD_WAIT_TIMEOUT): Promise { + const selectedTabLocator: By = By.xpath(this.getSelectedTabXpathLocator(tabTitle)); - await this.driverHelper.waitVisibility(selectedTabLocator, timeout); - } + await this.driverHelper.waitVisibility(selectedTabLocator, timeout); + } } diff --git a/tests/e2e/pageobjects/git-providers/OauthPage.ts b/tests/e2e/pageobjects/git-providers/OauthPage.ts index 881449eea75..c7641f65dc9 100644 --- a/tests/e2e/pageobjects/git-providers/OauthPage.ts +++ b/tests/e2e/pageobjects/git-providers/OauthPage.ts @@ -18,165 +18,165 @@ import { OAuthConstants } from '../../constants/OAuthConstants'; @injectable() export class OauthPage { - private static LOGIN_FORM: By; - private static PASSWORD_FORM: By; - private static SUBMIT_BUTTON: By; - private static APPROVE_BUTTON: By; - private static DENY_ACCESS_BUTTON: By; - private static DENY_SAVE_CREDENTIALS_BUTTON: By; - - constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { - switch (FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER) { - case GitProviderType.BITBUCKET : { - OauthPage.LOGIN_FORM = By.id('j_username'); - OauthPage.PASSWORD_FORM = By.id('j_password'); - OauthPage.APPROVE_BUTTON = By.id('approve'); - OauthPage.SUBMIT_BUTTON = By.id('submit'); - OauthPage.DENY_ACCESS_BUTTON = By.id('deny'); - } - break; - case GitProviderType.GITLAB: { - OauthPage.LOGIN_FORM = By.id('user_login'); - OauthPage.PASSWORD_FORM = By.id('user_password'); - OauthPage.SUBMIT_BUTTON = By.xpath('//button[@data-qa-selector="sign_in_button"]'); - OauthPage.APPROVE_BUTTON = By.xpath('//*[@value="Authorize"]'); - OauthPage.DENY_ACCESS_BUTTON = By.xpath('//input[@value="Deny"]'); - } - break; - case GitProviderType.GITHUB: { - OauthPage.LOGIN_FORM = By.id('login_field'); - OauthPage.PASSWORD_FORM = By.id('password'); - OauthPage.APPROVE_BUTTON = By.xpath('//*[@id="js-oauth-authorize-btn"]'); - OauthPage.SUBMIT_BUTTON = By.xpath('//*[@value="Sign in"]'); - OauthPage.DENY_ACCESS_BUTTON = By.xpath('//button[contains(., "Cancel")]'); - } - break; - case GitProviderType.AZURE_DEVOPS: { - OauthPage.LOGIN_FORM = By.xpath('//input[@type="email"]'); - OauthPage.PASSWORD_FORM = By.xpath('//input[@type="password"]'); - OauthPage.APPROVE_BUTTON = By.id('accept-button'); - OauthPage.SUBMIT_BUTTON = By.xpath('//input[@type="submit"]'); - OauthPage.DENY_SAVE_CREDENTIALS_BUTTON = By.xpath('//input[@type="button"]'); - OauthPage.DENY_ACCESS_BUTTON = By.id('deny-button'); - } - break; - default: { - throw new Error(`Invalid git provider. The value should be ${GitProviderType.GITHUB}, ${GitProviderType.GITLAB}, ${GitProviderType.AZURE_DEVOPS} or ${GitProviderType.BITBUCKET}`); - } - } + private static LOGIN_FORM: By; + private static PASSWORD_FORM: By; + private static SUBMIT_BUTTON: By; + private static APPROVE_BUTTON: By; + private static DENY_ACCESS_BUTTON: By; + private static DENY_SAVE_CREDENTIALS_BUTTON: By; + + constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { + switch (FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER) { + case GitProviderType.BITBUCKET : { + OauthPage.LOGIN_FORM = By.id('j_username'); + OauthPage.PASSWORD_FORM = By.id('j_password'); + OauthPage.APPROVE_BUTTON = By.id('approve'); + OauthPage.SUBMIT_BUTTON = By.id('submit'); + OauthPage.DENY_ACCESS_BUTTON = By.id('deny'); + } + break; + case GitProviderType.GITLAB: { + OauthPage.LOGIN_FORM = By.id('user_login'); + OauthPage.PASSWORD_FORM = By.id('user_password'); + OauthPage.SUBMIT_BUTTON = By.xpath('//button[@data-qa-selector="sign_in_button"]'); + OauthPage.APPROVE_BUTTON = By.xpath('//*[@value="Authorize"]'); + OauthPage.DENY_ACCESS_BUTTON = By.xpath('//input[@value="Deny"]'); + } + break; + case GitProviderType.GITHUB: { + OauthPage.LOGIN_FORM = By.id('login_field'); + OauthPage.PASSWORD_FORM = By.id('password'); + OauthPage.APPROVE_BUTTON = By.xpath('//*[@id="js-oauth-authorize-btn"]'); + OauthPage.SUBMIT_BUTTON = By.xpath('//*[@value="Sign in"]'); + OauthPage.DENY_ACCESS_BUTTON = By.xpath('//button[contains(., "Cancel")]'); + } + break; + case GitProviderType.AZURE_DEVOPS: { + OauthPage.LOGIN_FORM = By.xpath('//input[@type="email"]'); + OauthPage.PASSWORD_FORM = By.xpath('//input[@type="password"]'); + OauthPage.APPROVE_BUTTON = By.id('accept-button'); + OauthPage.SUBMIT_BUTTON = By.xpath('//input[@type="submit"]'); + OauthPage.DENY_SAVE_CREDENTIALS_BUTTON = By.xpath('//input[@type="button"]'); + OauthPage.DENY_ACCESS_BUTTON = By.id('deny-button'); + } + break; + default: { + throw new Error(`Invalid git provider. The value should be ${GitProviderType.GITHUB}, ${GitProviderType.GITLAB}, ${GitProviderType.AZURE_DEVOPS} or ${GitProviderType.BITBUCKET}`); + } } + } - async waitLoginPage(): Promise { - Logger.debug('OauthPage.waitLoginPage'); + async waitLoginPage(): Promise { + Logger.debug(); - await this.driverHelper.waitVisibility(OauthPage.LOGIN_FORM, TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM * 3); - } + await this.driverHelper.waitVisibility(OauthPage.LOGIN_FORM, TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM * 3); + } - async enterUserName(userName: string): Promise { - Logger.debug(`this.enterUserName "${userName}"`); + async enterUserName(userName: string): Promise { + Logger.debug(`"${userName}"`); - await this.driverHelper.enterValue(OauthPage.LOGIN_FORM, userName); - } + await this.driverHelper.enterValue(OauthPage.LOGIN_FORM, userName); + } - async enterPassword(password: string): Promise { - Logger.debug(`OauthPage.enterPassword`); + async enterPassword(password: string): Promise { + Logger.debug(); - await this.driverHelper.enterValue(OauthPage.PASSWORD_FORM, password); - } + await this.driverHelper.enterValue(OauthPage.PASSWORD_FORM, password); + } - async clickOnSubmitButton(): Promise { - Logger.debug('OauthPage.clickOnLoginButton'); + async clickOnSubmitButton(): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(OauthPage.SUBMIT_BUTTON); - } + await this.driverHelper.waitAndClick(OauthPage.SUBMIT_BUTTON); + } - async clickOnNotRememberCredentialsButton(): Promise { - Logger.debug('OauthPage.clickOnNotRememberCredentialsButton'); + async clickOnNotRememberCredentialsButton(): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(OauthPage.DENY_SAVE_CREDENTIALS_BUTTON); - } + await this.driverHelper.waitAndClick(OauthPage.DENY_SAVE_CREDENTIALS_BUTTON); + } - async waitClosingLoginPage(): Promise { - Logger.debug('OauthPage.waitClosingLoginPage'); + async waitClosingLoginPage(): Promise { + Logger.debug(); - await this.driverHelper.waitDisappearance(OauthPage.PASSWORD_FORM); - } + await this.driverHelper.waitDisappearance(OauthPage.PASSWORD_FORM); + } - async waitOauthPage(): Promise { - Logger.debug('OauthPage.waitOauthPage'); + async waitOauthPage(): Promise { + Logger.debug(); - await this.driverHelper.waitVisibility(OauthPage.APPROVE_BUTTON); - } + await this.driverHelper.waitVisibility(OauthPage.APPROVE_BUTTON); + } - async clickOnApproveButton(): Promise { - Logger.debug('OauthPage.clickOnApproveButton'); + async clickOnApproveButton(): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(OauthPage.APPROVE_BUTTON); - } + await this.driverHelper.waitAndClick(OauthPage.APPROVE_BUTTON); + } - async clickOnDenyAccessButton(): Promise { - Logger.debug('OauthPage.clickOnDenyAccessButton'); + async clickOnDenyAccessButton(): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(OauthPage.DENY_ACCESS_BUTTON); - } + await this.driverHelper.waitAndClick(OauthPage.DENY_ACCESS_BUTTON); + } - async waitDisappearanceOauthPage(): Promise { - Logger.debug('OauthPage.waitDisappearanceOauthPage'); + async waitDisappearanceOauthPage(): Promise { + Logger.debug(); - await this.driverHelper.waitDisappearance(OauthPage.APPROVE_BUTTON); - } + await this.driverHelper.waitDisappearance(OauthPage.APPROVE_BUTTON); + } - async login(): Promise { - Logger.debug('OauthPage.login'); - - await this.waitLoginPage(); - await this.enterUserName(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_USERNAME); - if (FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER === GitProviderType.AZURE_DEVOPS) { - await this.clickOnSubmitButton(); - } - await this.enterPassword(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_PASSWORD); - await this.clickOnSubmitButton(); - if (FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER === GitProviderType.AZURE_DEVOPS) { - await this.clickOnNotRememberCredentialsButton(); - } - await this.waitClosingLoginPage(); - } + async login(): Promise { + Logger.debug(); - async confirmAccess(): Promise { - Logger.debug('OauthPage.confirmAccess'); - - try { - await this.clickOnApproveButton(); - await this.waitDisappearanceOauthPage(); - } catch (e) { - Logger.debug('OauthPage.confirmAccess - access was not confirmed, retrying to click confirmation button'); - // workaround for github, AZURE_DEVOPS oauth confirmation page (bot security) - await this.driverHelper.getAction() - .move({ - origin: await this.driverHelper.waitPresence(OauthPage.APPROVE_BUTTON) - }) - .click() - .perform(); - await this.waitDisappearanceOauthPage(); - } + await this.waitLoginPage(); + await this.enterUserName(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_USERNAME); + if (FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER === GitProviderType.AZURE_DEVOPS) { + await this.clickOnSubmitButton(); } - - async denyAccess(): Promise { - Logger.debug('OauthPage.denyAccess'); - - try { - await this.clickOnDenyAccessButton(); - await this.waitDisappearanceOauthPage(); - } catch (e) { - Logger.debug('OauthPage.denyAccess - deny access was not confirmed, retrying to click confirmation button'); - // workaround for github, AZURE_DEVOPS oauth confirmation page (bot security) - await this.driverHelper.getAction() - .move({ - origin: await this.driverHelper.waitPresence(OauthPage.DENY_ACCESS_BUTTON) - }) - .click() - .perform(); - await this.waitDisappearanceOauthPage(); - } + await this.enterPassword(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_PASSWORD); + await this.clickOnSubmitButton(); + if (FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER === GitProviderType.AZURE_DEVOPS) { + await this.clickOnNotRememberCredentialsButton(); + } + await this.waitClosingLoginPage(); + } + + async confirmAccess(): Promise { + Logger.debug(); + + try { + await this.clickOnApproveButton(); + await this.waitDisappearanceOauthPage(); + } catch (e) { + Logger.debug('access was not confirmed, retrying to click confirmation button'); + // workaround for GITHUB, AZURE_DEVOPS oauth confirmation page (bot security) + await this.driverHelper.getAction() + .move({ + origin: await this.driverHelper.waitPresence(OauthPage.APPROVE_BUTTON) + }) + .click() + .perform(); + await this.waitDisappearanceOauthPage(); + } + } + + async denyAccess(): Promise { + Logger.debug(); + + try { + await this.clickOnDenyAccessButton(); + await this.waitDisappearanceOauthPage(); + } catch (e) { + Logger.debug('deny access was not confirmed, retrying to click confirmation button'); + // workaround for GITHUB, AZURE_DEVOPS oauth confirmation page (bot security) + await this.driverHelper.getAction() + .move({ + origin: await this.driverHelper.waitPresence(OauthPage.DENY_ACCESS_BUTTON) + }) + .click() + .perform(); + await this.waitDisappearanceOauthPage(); } + } } diff --git a/tests/e2e/pageobjects/ide/CheCodeLocatorLoader.ts b/tests/e2e/pageobjects/ide/CheCodeLocatorLoader.ts index 02601dc8951..2e7d4371c26 100644 --- a/tests/e2e/pageobjects/ide/CheCodeLocatorLoader.ts +++ b/tests/e2e/pageobjects/ide/CheCodeLocatorLoader.ts @@ -21,54 +21,54 @@ import { MonacoConstants } from '../../constants/MonacoConstants'; */ export class CheCodeLocatorLoader extends LocatorLoader { - readonly webCheCodeLocators: Locators; + readonly webCheCodeLocators: Locators; - constructor() { - super(MonacoConstants.TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION, MonacoConstants.TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION, getLocatorsPath()); - this.webCheCodeLocators = this.mergeLocators() as Locators; - } + constructor() { + super(MonacoConstants.TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION, MonacoConstants.TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION, getLocatorsPath()); + this.webCheCodeLocators = this.mergeLocators() as Locators; + } - private webLocatorDiff(): LocatorDiff { - return { - locators: { - WelcomeContent: { - text: By.xpath('//*[@class="dialog-message-text" and contains(text(), "trust")]'), - button: By.xpath('//a[contains(., "trust")]') - }, - }, - extras: { - ExtensionsViewSection: { - requireReloadButton: By.xpath('//a[text()=\'Reload Required\']') - } - } - }; - } + private webLocatorDiff(): LocatorDiff { + return { + locators: { + WelcomeContent: { + text: By.xpath('//*[@class="dialog-message-text" and contains(text(), "trust")]'), + button: By.xpath('//a[contains(., "trust")]') + } + }, + extras: { + ExtensionsViewSection: { + requireReloadButton: By.xpath('//a[text()=\'Reload Required\']') + } + } + }; + } - private merge(target: any, obj: any): object { - for (const key in obj) { - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - continue; - } + private merge(target: any, obj: any): object { + for (const key in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + continue; + } - let oldVal: any = obj[key]; - let newVal: any = target[key]; + let oldVal: any = obj[key]; + let newVal: any = target[key]; - if (typeof (newVal) === 'object' && typeof (oldVal) === 'object') { - target[key] = this.merge(newVal, oldVal); - } else { - target[key] = clone(oldVal); - } - } - return target; + if (typeof (newVal) === 'object' && typeof (oldVal) === 'object') { + target[key] = this.merge(newVal, oldVal); + } else { + target[key] = clone(oldVal); + } } + return target; + } - private mergeLocators(): Locators { - const target: Locators = super.loadLocators(); + private mergeLocators(): Locators { + const target: Locators = super.loadLocators(); - this.merge(target, this.webLocatorDiff().locators as Locators); - this.merge(target, this.webLocatorDiff().extras as Locators); + this.merge(target, this.webLocatorDiff().locators as Locators); + this.merge(target, this.webLocatorDiff().extras as Locators); - return target; - } + return target; + } } diff --git a/tests/e2e/pageobjects/login/interfaces/ICheLoginPage.ts b/tests/e2e/pageobjects/login/interfaces/ICheLoginPage.ts index 0bb798caf31..24d388f073e 100644 --- a/tests/e2e/pageobjects/login/interfaces/ICheLoginPage.ts +++ b/tests/e2e/pageobjects/login/interfaces/ICheLoginPage.ts @@ -9,5 +9,5 @@ **********************************************************************/ export interface ICheLoginPage { - login(): void; + login(): void; } diff --git a/tests/e2e/pageobjects/login/interfaces/IOcpLoginPage.ts b/tests/e2e/pageobjects/login/interfaces/IOcpLoginPage.ts index 44c54a4c86b..1c227104516 100644 --- a/tests/e2e/pageobjects/login/interfaces/IOcpLoginPage.ts +++ b/tests/e2e/pageobjects/login/interfaces/IOcpLoginPage.ts @@ -9,5 +9,5 @@ **********************************************************************/ export interface IOcpLoginPage { - login(): void; + login(): void; } diff --git a/tests/e2e/pageobjects/login/kubernetes/DexLoginPage.ts b/tests/e2e/pageobjects/login/kubernetes/DexLoginPage.ts index c91affb2f65..c53b793a31e 100644 --- a/tests/e2e/pageobjects/login/kubernetes/DexLoginPage.ts +++ b/tests/e2e/pageobjects/login/kubernetes/DexLoginPage.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ import 'reflect-metadata'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { CLASSES } from '../../../configs/inversify.types'; import { Logger } from '../../../utils/Logger'; import { By } from 'selenium-webdriver'; @@ -18,41 +18,41 @@ import { DriverHelper } from '../../../utils/DriverHelper'; @injectable() export class DexLoginPage { - private static readonly dexPageContentContainer: By = By.className('dex-container'); - private static readonly loginInput: By = By.id('login'); - private static readonly passwordInput: By = By.id('password'); - private static readonly submitButton: By = By.id('submit-login'); + private static readonly dexPageContentContainer: By = By.className('dex-container'); + private static readonly loginInput: By = By.id('login'); + private static readonly passwordInput: By = By.id('password'); + private static readonly submitButton: By = By.id('submit-login'); - constructor( - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + constructor( + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - async waitDexLoginPage(): Promise { - Logger.debug(); + async waitDexLoginPage(): Promise { + Logger.debug(); - await this.driverHelper.waitVisibility(DexLoginPage.dexPageContentContainer, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - } + await this.driverHelper.waitVisibility(DexLoginPage.dexPageContentContainer, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + } - async clickOnLoginButton(): Promise { - Logger.debug(); + async clickOnLoginButton(): Promise { + Logger.debug(); - await this.driverHelper.waitAndClick(DexLoginPage.submitButton); - } + await this.driverHelper.waitAndClick(DexLoginPage.submitButton); + } - async enterUserNameKubernetes(userName: string): Promise { - Logger.debug(); + async enterUserNameKubernetes(userName: string): Promise { + Logger.debug(); - await this.driverHelper.enterValue(DexLoginPage.loginInput, userName); - } + await this.driverHelper.enterValue(DexLoginPage.loginInput, userName); + } - async enterPasswordKubernetes(password: string): Promise { - Logger.debug(); + async enterPasswordKubernetes(password: string): Promise { + Logger.debug(); - await this.driverHelper.enterValue(DexLoginPage.passwordInput, password); - } + await this.driverHelper.enterValue(DexLoginPage.passwordInput, password); + } - async waitDexLoginPageDisappearance(): Promise { - Logger.debug(); + async waitDexLoginPageDisappearance(): Promise { + Logger.debug(); - await this.driverHelper.waitDisappearance(DexLoginPage.dexPageContentContainer, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - } + await this.driverHelper.waitDisappearance(DexLoginPage.dexPageContentContainer, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + } } diff --git a/tests/e2e/pageobjects/login/kubernetes/KubernetesLoginPage.ts b/tests/e2e/pageobjects/login/kubernetes/KubernetesLoginPage.ts index 5b4d3847003..2188d4c5723 100644 --- a/tests/e2e/pageobjects/login/kubernetes/KubernetesLoginPage.ts +++ b/tests/e2e/pageobjects/login/kubernetes/KubernetesLoginPage.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ import 'reflect-metadata'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { CLASSES } from '../../../configs/inversify.types'; import { Logger } from '../../../utils/Logger'; import { ICheLoginPage } from '../interfaces/ICheLoginPage'; @@ -18,16 +18,16 @@ import { OAuthConstants } from '../../../constants/OAuthConstants'; @injectable() export class KubernetesLoginPage implements ICheLoginPage { - constructor( - @inject(CLASSES.DexLoginPage) private readonly dexLoginPage: DexLoginPage) { } + constructor( + @inject(CLASSES.DexLoginPage) private readonly dexLoginPage: DexLoginPage) { } - async login(): Promise { - Logger.debug(); + async login(): Promise { + Logger.debug(); - await this.dexLoginPage.waitDexLoginPage(); - await this.dexLoginPage.enterUserNameKubernetes(OAuthConstants.TS_SELENIUM_K8S_USERNAME); - await this.dexLoginPage.enterPasswordKubernetes(OAuthConstants.TS_SELENIUM_K8S_PASSWORD); - await this.dexLoginPage.clickOnLoginButton(); - await this.dexLoginPage.waitDexLoginPageDisappearance(); - } + await this.dexLoginPage.waitDexLoginPage(); + await this.dexLoginPage.enterUserNameKubernetes(OAuthConstants.TS_SELENIUM_K8S_USERNAME); + await this.dexLoginPage.enterPasswordKubernetes(OAuthConstants.TS_SELENIUM_K8S_PASSWORD); + await this.dexLoginPage.clickOnLoginButton(); + await this.dexLoginPage.waitDexLoginPageDisappearance(); + } } diff --git a/tests/e2e/pageobjects/login/openshift/OcpLoginPage.ts b/tests/e2e/pageobjects/login/openshift/OcpLoginPage.ts index fc3835ca732..472e8473e82 100644 --- a/tests/e2e/pageobjects/login/openshift/OcpLoginPage.ts +++ b/tests/e2e/pageobjects/login/openshift/OcpLoginPage.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ import 'reflect-metadata'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { DriverHelper } from '../../../utils/DriverHelper'; import { CLASSES } from '../../../configs/inversify.types'; import { By } from 'selenium-webdriver'; @@ -19,74 +19,74 @@ import { OAuthConstants } from '../../../constants/OAuthConstants'; @injectable() export class OcpLoginPage { - private static readonly LOGIN_PAGE_OPENSHIFT_XPATH: string = '//*[contains(text(), \'Welcome\')]'; + private static readonly LOGIN_PAGE_OPENSHIFT_XPATH: string = '//*[contains(text(), \'Welcome\')]'; - constructor( - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + constructor( + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - async waitOpenShiftLoginWelcomePage(): Promise { - Logger.debug(); + async waitOpenShiftLoginWelcomePage(): Promise { + Logger.debug(); - await this.driverHelper.waitVisibility(By.xpath(OcpLoginPage.LOGIN_PAGE_OPENSHIFT_XPATH), TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - } + await this.driverHelper.waitVisibility(By.xpath(OcpLoginPage.LOGIN_PAGE_OPENSHIFT_XPATH), TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + } - async clickOnLoginProviderTitle(): Promise { - Logger.debug(); + async clickOnLoginProviderTitle(): Promise { + Logger.debug(); - const loginProviderTitleLocator: By = By.xpath(`//a[text()=\'${OAuthConstants.TS_OCP_LOGIN_PAGE_PROVIDER_TITLE}\']`); - await this.driverHelper.waitAndClick(loginProviderTitleLocator, TimeoutConstants.TS_SELENIUM_WAIT_FOR_URL); - } + const loginProviderTitleLocator: By = By.xpath(`//a[text()=\'${OAuthConstants.TS_OCP_LOGIN_PAGE_PROVIDER_TITLE}\']`); + await this.driverHelper.waitAndClick(loginProviderTitleLocator, TimeoutConstants.TS_SELENIUM_WAIT_FOR_URL); + } - async isIdentityProviderLinkVisible(): Promise { - Logger.debug(); + async isIdentityProviderLinkVisible(): Promise { + Logger.debug(); - const loginWithHtpaswdLocator: By = By.xpath(`//a[text()=\'${OAuthConstants.TS_OCP_LOGIN_PAGE_PROVIDER_TITLE}\']`); - return await this.driverHelper.waitVisibilityBoolean(loginWithHtpaswdLocator, 3, 5000); - } + const loginWithHtpaswdLocator: By = By.xpath(`//a[text()=\'${OAuthConstants.TS_OCP_LOGIN_PAGE_PROVIDER_TITLE}\']`); + return await this.driverHelper.waitVisibilityBoolean(loginWithHtpaswdLocator, 3, 5000); + } - async isAuthorizeOpenShiftIdentityProviderPageVisible(): Promise { - Logger.debug(); + async isAuthorizeOpenShiftIdentityProviderPageVisible(): Promise { + Logger.debug(); - const authorizeOpenshiftIdentityProviderPageLocator: By = By.xpath('//h1[text()=\'Authorize Access\']'); - return await this.driverHelper.isVisible(authorizeOpenshiftIdentityProviderPageLocator); - } + const authorizeOpenshiftIdentityProviderPageLocator: By = By.xpath('//h1[text()=\'Authorize Access\']'); + return await this.driverHelper.isVisible(authorizeOpenshiftIdentityProviderPageLocator); + } - async waitAuthorizeOpenShiftIdentityProviderPage(): Promise { - Logger.debug(); + async waitAuthorizeOpenShiftIdentityProviderPage(): Promise { + Logger.debug(); - const authorizeOpenshiftIdentityProviderPageLocator: By = By.xpath('//h1[text()=\'Authorize Access\']'); - await this.driverHelper.waitVisibility(authorizeOpenshiftIdentityProviderPageLocator, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - } + const authorizeOpenshiftIdentityProviderPageLocator: By = By.xpath('//h1[text()=\'Authorize Access\']'); + await this.driverHelper.waitVisibility(authorizeOpenshiftIdentityProviderPageLocator, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + } - async clickOnApproveAuthorizeAccessButton(): Promise { - Logger.debug(); + async clickOnApproveAuthorizeAccessButton(): Promise { + Logger.debug(); - const approveAuthorizeAccessOcpLocator: By = By.css('input[name=\'approve\']'); - await this.driverHelper.waitAndClick(approveAuthorizeAccessOcpLocator); - } + const approveAuthorizeAccessOcpLocator: By = By.css('input[name=\'approve\']'); + await this.driverHelper.waitAndClick(approveAuthorizeAccessOcpLocator); + } - async enterUserNameOpenShift(userName: string): Promise { - Logger.debug(`"${userName}"`); + async enterUserNameOpenShift(userName: string): Promise { + Logger.debug(`"${userName}"`); - await this.driverHelper.enterValue(By.id('inputUsername'), userName); - } + await this.driverHelper.enterValue(By.id('inputUsername'), userName); + } - async enterPasswordOpenShift(passw: string): Promise { - Logger.debug(); + async enterPasswordOpenShift(passw: string): Promise { + Logger.debug(); - await this.driverHelper.enterValue(By.id('inputPassword'), passw); - } + await this.driverHelper.enterValue(By.id('inputPassword'), passw); + } - async clickOnLoginButton(): Promise { - Logger.debug(); + async clickOnLoginButton(): Promise { + Logger.debug(); - const loginButtonLocator: By = By.css('button[type=submit]'); - await this.driverHelper.waitAndClick(loginButtonLocator); - } + const loginButtonLocator: By = By.css('button[type=submit]'); + await this.driverHelper.waitAndClick(loginButtonLocator); + } - async waitDisappearanceOpenShiftLoginWelcomePage(): Promise { - Logger.debug(); + async waitDisappearanceOpenShiftLoginWelcomePage(): Promise { + Logger.debug(); - await this.driverHelper.waitDisappearance(By.xpath(OcpLoginPage.LOGIN_PAGE_OPENSHIFT_XPATH)); - } + await this.driverHelper.waitDisappearance(By.xpath(OcpLoginPage.LOGIN_PAGE_OPENSHIFT_XPATH)); + } } diff --git a/tests/e2e/pageobjects/login/openshift/OcpRedHatLoginPage.ts b/tests/e2e/pageobjects/login/openshift/OcpRedHatLoginPage.ts index 20f3ec1b4bc..d0cdc3b314f 100644 --- a/tests/e2e/pageobjects/login/openshift/OcpRedHatLoginPage.ts +++ b/tests/e2e/pageobjects/login/openshift/OcpRedHatLoginPage.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ import 'reflect-metadata'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { RedHatLoginPage } from './RedHatLoginPage'; import { CLASSES } from '../../../configs/inversify.types'; import { By } from 'selenium-webdriver'; @@ -21,29 +21,29 @@ import { Logger } from '../../../utils/Logger'; @injectable() export class OcpRedHatLoginPage implements ICheLoginPage { - private readonly OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR: string = `//div[@class='panel-login']`; - private readonly OPEN_SHIFT_LOGIN_LANDING_PAGE_BUTTON_LOCATOR: string = `${this.OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR}/div[contains(@class, 'panel-content')]/form/button`; + private readonly OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR: string = `//div[@class='panel-login']`; + private readonly OPEN_SHIFT_LOGIN_LANDING_PAGE_BUTTON_LOCATOR: string = `${this.OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR}/div[contains(@class, 'panel-content')]/form/button`; - constructor( - @inject(CLASSES.OcpLoginPage) private readonly ocpLogin: OcpLoginPage, - @inject(CLASSES.RedHatLoginPage) private readonly redHatLogin: RedHatLoginPage, - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + constructor( + @inject(CLASSES.OcpLoginPage) private readonly ocpLogin: OcpLoginPage, + @inject(CLASSES.RedHatLoginPage) private readonly redHatLogin: RedHatLoginPage, + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - async login(): Promise { - Logger.debug(); + async login(): Promise { + Logger.debug(); - Logger.debug('wait for LogInWithOpenShift page and click button'); - await this.driverHelper.waitPresence(By.xpath(this.OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR), TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - await this.driverHelper.waitAndClick(By.xpath(this.OPEN_SHIFT_LOGIN_LANDING_PAGE_BUTTON_LOCATOR)); + Logger.debug('wait for LogInWithOpenShift page and click button'); + await this.driverHelper.waitPresence(By.xpath(this.OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR), TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + await this.driverHelper.waitAndClick(By.xpath(this.OPEN_SHIFT_LOGIN_LANDING_PAGE_BUTTON_LOCATOR)); - await this.ocpLogin.isIdentityProviderLinkVisible(); - await this.ocpLogin.clickOnLoginProviderTitle(); + await this.ocpLogin.isIdentityProviderLinkVisible(); + await this.ocpLogin.clickOnLoginProviderTitle(); - await this.redHatLogin.waitRedHatLoginWelcomePage(); - await this.redHatLogin.enterUserNameRedHat(); - await this.redHatLogin.clickNextButton(); - await this.redHatLogin.enterPasswordRedHat(); - await this.redHatLogin.clickOnLoginButton(); - await this.redHatLogin.waitDisappearanceRedHatLoginWelcomePage(); - } + await this.redHatLogin.waitRedHatLoginWelcomePage(); + await this.redHatLogin.enterUserNameRedHat(); + await this.redHatLogin.clickNextButton(); + await this.redHatLogin.enterPasswordRedHat(); + await this.redHatLogin.clickOnLoginButton(); + await this.redHatLogin.waitDisappearanceRedHatLoginWelcomePage(); + } } diff --git a/tests/e2e/pageobjects/login/openshift/OcpUserLoginPage.ts b/tests/e2e/pageobjects/login/openshift/OcpUserLoginPage.ts index f4a3ef807a5..c82c639ece9 100644 --- a/tests/e2e/pageobjects/login/openshift/OcpUserLoginPage.ts +++ b/tests/e2e/pageobjects/login/openshift/OcpUserLoginPage.ts @@ -9,7 +9,7 @@ **********************************************************************/ import 'reflect-metadata'; import { IOcpLoginPage } from '../interfaces/IOcpLoginPage'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { OcpLoginPage } from './OcpLoginPage'; import { CLASSES } from '../../../configs/inversify.types'; import { Logger } from '../../../utils/Logger'; @@ -18,21 +18,21 @@ import { OAuthConstants } from '../../../constants/OAuthConstants'; @injectable() export class OcpUserLoginPage implements IOcpLoginPage { - constructor( - @inject(CLASSES.OcpLoginPage) private readonly ocpLogin: OcpLoginPage) { } + constructor( + @inject(CLASSES.OcpLoginPage) private readonly ocpLogin: OcpLoginPage) { } - async login(): Promise { - Logger.debug(); + async login(): Promise { + Logger.debug(); - if (OAuthConstants.TS_OCP_LOGIN_PAGE_PROVIDER_TITLE !== '') { - await this.ocpLogin.clickOnLoginProviderTitle(); - } - - await this.ocpLogin.waitOpenShiftLoginWelcomePage(); - await this.ocpLogin.enterUserNameOpenShift(OAuthConstants.TS_SELENIUM_OCP_USERNAME); - await this.ocpLogin.enterPasswordOpenShift(OAuthConstants.TS_SELENIUM_OCP_PASSWORD); - await this.ocpLogin.clickOnLoginButton(); - await this.ocpLogin.waitDisappearanceOpenShiftLoginWelcomePage(); + if (OAuthConstants.TS_OCP_LOGIN_PAGE_PROVIDER_TITLE !== '') { + await this.ocpLogin.clickOnLoginProviderTitle(); } + await this.ocpLogin.waitOpenShiftLoginWelcomePage(); + await this.ocpLogin.enterUserNameOpenShift(OAuthConstants.TS_SELENIUM_OCP_USERNAME); + await this.ocpLogin.enterPasswordOpenShift(OAuthConstants.TS_SELENIUM_OCP_PASSWORD); + await this.ocpLogin.clickOnLoginButton(); + await this.ocpLogin.waitDisappearanceOpenShiftLoginWelcomePage(); + } + } diff --git a/tests/e2e/pageobjects/login/openshift/RedHatLoginPage.ts b/tests/e2e/pageobjects/login/openshift/RedHatLoginPage.ts index 9be1dcdb502..775dfaf0f17 100644 --- a/tests/e2e/pageobjects/login/openshift/RedHatLoginPage.ts +++ b/tests/e2e/pageobjects/login/openshift/RedHatLoginPage.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ import 'reflect-metadata'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { By } from 'selenium-webdriver'; import { CLASSES } from '../../../configs/inversify.types'; import { DriverHelper } from '../../../utils/DriverHelper'; @@ -17,44 +17,47 @@ import { OAuthConstants } from '../../../constants/OAuthConstants'; @injectable() export class RedHatLoginPage { - private readonly USERNAME_INPUT_ID: string = 'username-verification'; - private readonly PASSWORD_INPUT_ID: string = 'password'; - private readonly NEXT_BUTTON_ID: string = 'login-show-step2'; - private readonly LOGIN_BUTTON_ID: string = 'rh-password-verification-submit-button'; - - constructor( - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - - async waitRedHatLoginWelcomePage(): Promise { - Logger.debug(); - await this.driverHelper.waitVisibility(By.id(this.USERNAME_INPUT_ID)); - } - - async enterPasswordRedHat(): Promise { - Logger.debug(); - const passwordFieldLocator: By = By.id(this.PASSWORD_INPUT_ID); - await this.driverHelper.waitVisibility(passwordFieldLocator, 3000); - await this.driverHelper.enterValue(passwordFieldLocator, OAuthConstants.TS_SELENIUM_OCP_PASSWORD); - } - async clickOnLoginButton(): Promise { - Logger.debug(); - const loginButtonLocator: By = By.id(this.LOGIN_BUTTON_ID); - await this.driverHelper.waitAndClick(loginButtonLocator); - } - async waitDisappearanceRedHatLoginWelcomePage(): Promise { - Logger.debug(); - await this.driverHelper.waitDisappearance(By.id(this.LOGIN_BUTTON_ID)); - } - async enterUserNameRedHat(): Promise { - Logger.debug(); - const usernameFieldLocator: By = By.id(this.USERNAME_INPUT_ID); - await this.driverHelper.waitVisibility(usernameFieldLocator, 20000); - await this.driverHelper.enterValue(usernameFieldLocator, OAuthConstants.TS_SELENIUM_OCP_USERNAME); - } - - async clickNextButton(): Promise { - Logger.debug(); - const nextButtonLocator: By = By.id(this.NEXT_BUTTON_ID); - await this.driverHelper.waitAndClick(nextButtonLocator); - } + private readonly USERNAME_INPUT_ID: string = 'username-verification'; + private readonly PASSWORD_INPUT_ID: string = 'password'; + private readonly NEXT_BUTTON_ID: string = 'login-show-step2'; + private readonly LOGIN_BUTTON_ID: string = 'rh-password-verification-submit-button'; + + constructor( + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + + async waitRedHatLoginWelcomePage(): Promise { + Logger.debug(); + await this.driverHelper.waitVisibility(By.id(this.USERNAME_INPUT_ID)); + } + + async enterPasswordRedHat(): Promise { + Logger.debug(); + const passwordFieldLocator: By = By.id(this.PASSWORD_INPUT_ID); + await this.driverHelper.waitVisibility(passwordFieldLocator, 3000); + await this.driverHelper.enterValue(passwordFieldLocator, OAuthConstants.TS_SELENIUM_OCP_PASSWORD); + } + + async clickOnLoginButton(): Promise { + Logger.debug(); + const loginButtonLocator: By = By.id(this.LOGIN_BUTTON_ID); + await this.driverHelper.waitAndClick(loginButtonLocator); + } + + async waitDisappearanceRedHatLoginWelcomePage(): Promise { + Logger.debug(); + await this.driverHelper.waitDisappearance(By.id(this.LOGIN_BUTTON_ID)); + } + + async enterUserNameRedHat(): Promise { + Logger.debug(); + const usernameFieldLocator: By = By.id(this.USERNAME_INPUT_ID); + await this.driverHelper.waitVisibility(usernameFieldLocator, 20000); + await this.driverHelper.enterValue(usernameFieldLocator, OAuthConstants.TS_SELENIUM_OCP_USERNAME); + } + + async clickNextButton(): Promise { + Logger.debug(); + const nextButtonLocator: By = By.id(this.NEXT_BUTTON_ID); + await this.driverHelper.waitAndClick(nextButtonLocator); + } } diff --git a/tests/e2e/pageobjects/login/openshift/RegularUserOcpCheLoginPage.ts b/tests/e2e/pageobjects/login/openshift/RegularUserOcpCheLoginPage.ts index ef1a0d91d29..1931561c442 100644 --- a/tests/e2e/pageobjects/login/openshift/RegularUserOcpCheLoginPage.ts +++ b/tests/e2e/pageobjects/login/openshift/RegularUserOcpCheLoginPage.ts @@ -10,7 +10,7 @@ import 'reflect-metadata'; import { ICheLoginPage } from '../interfaces/ICheLoginPage'; import { OcpLoginPage } from './OcpLoginPage'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { CLASSES } from '../../../configs/inversify.types'; import { Logger } from '../../../utils/Logger'; import { TimeoutConstants } from '../../../constants/TimeoutConstants'; @@ -21,33 +21,33 @@ import { OAuthConstants } from '../../../constants/OAuthConstants'; @injectable() export class RegularUserOcpCheLoginPage implements ICheLoginPage { - private readonly OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR: string = `//div[@class='panel-login']`; - private readonly OPEN_SHIFT_LOGIN_LANDING_PAGE_BUTTON_LOCATOR: string = `${this.OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR}/div[contains(@class, 'panel-content')]/form/button`; + private readonly OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR: string = `//div[@class='panel-login']`; + private readonly OPEN_SHIFT_LOGIN_LANDING_PAGE_BUTTON_LOCATOR: string = `${this.OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR}/div[contains(@class, 'panel-content')]/form/button`; - constructor( - @inject(CLASSES.OcpLoginPage) private readonly ocpLogin: OcpLoginPage, - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + constructor( + @inject(CLASSES.OcpLoginPage) private readonly ocpLogin: OcpLoginPage, + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - async login(): Promise { - Logger.debug(); + async login(): Promise { + Logger.debug(); - Logger.debug('wait for LogInWithOpenShift page and click button'); - await this.driverHelper.waitPresence(By.xpath(this.OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR), TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - await this.driverHelper.waitAndClick(By.xpath(this.OPEN_SHIFT_LOGIN_LANDING_PAGE_BUTTON_LOCATOR)); + Logger.debug('wait for LogInWithOpenShift page and click button'); + await this.driverHelper.waitPresence(By.xpath(this.OPEN_SHIFT_LOGIN_LANDING_PAGE_LOCATOR), TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + await this.driverHelper.waitAndClick(By.xpath(this.OPEN_SHIFT_LOGIN_LANDING_PAGE_BUTTON_LOCATOR)); - if (await this.ocpLogin.isIdentityProviderLinkVisible()) { - await this.ocpLogin.clickOnLoginProviderTitle(); - } + if (await this.ocpLogin.isIdentityProviderLinkVisible()) { + await this.ocpLogin.clickOnLoginProviderTitle(); + } - await this.ocpLogin.waitOpenShiftLoginWelcomePage(); - await this.ocpLogin.enterUserNameOpenShift(OAuthConstants.TS_SELENIUM_OCP_USERNAME); - await this.ocpLogin.enterPasswordOpenShift(OAuthConstants.TS_SELENIUM_OCP_PASSWORD); - await this.ocpLogin.clickOnLoginButton(); - await this.ocpLogin.waitDisappearanceOpenShiftLoginWelcomePage(); + await this.ocpLogin.waitOpenShiftLoginWelcomePage(); + await this.ocpLogin.enterUserNameOpenShift(OAuthConstants.TS_SELENIUM_OCP_USERNAME); + await this.ocpLogin.enterPasswordOpenShift(OAuthConstants.TS_SELENIUM_OCP_PASSWORD); + await this.ocpLogin.clickOnLoginButton(); + await this.ocpLogin.waitDisappearanceOpenShiftLoginWelcomePage(); - if (await this.ocpLogin.isAuthorizeOpenShiftIdentityProviderPageVisible()) { - await this.ocpLogin.waitAuthorizeOpenShiftIdentityProviderPage(); - await this.ocpLogin.clickOnApproveAuthorizeAccessButton(); - } + if (await this.ocpLogin.isAuthorizeOpenShiftIdentityProviderPageVisible()) { + await this.ocpLogin.waitAuthorizeOpenShiftIdentityProviderPage(); + await this.ocpLogin.clickOnApproveAuthorizeAccessButton(); } + } } diff --git a/tests/e2e/pageobjects/openshift/OcpApplicationPage.ts b/tests/e2e/pageobjects/openshift/OcpApplicationPage.ts index 7dc38517415..7eca320785a 100644 --- a/tests/e2e/pageobjects/openshift/OcpApplicationPage.ts +++ b/tests/e2e/pageobjects/openshift/OcpApplicationPage.ts @@ -19,24 +19,24 @@ import { BrowserTabsUtil } from '../../utils/BrowserTabsUtil'; @injectable() export class OcpApplicationPage { - private static readonly APPLICATION_ICON_LOCATOR: By = By.xpath('//*[@data-test-id="base-node-handler"]'); - private static readonly EDIT_SOURCE_CODE_ICON_LOCATOR: By = By.xpath('//*[@aria-label="Edit source code"]'); + private static readonly APPLICATION_ICON_LOCATOR: By = By.xpath('//*[@data-test-id="base-node-handler"]'); + private static readonly EDIT_SOURCE_CODE_ICON_LOCATOR: By = By.xpath('//*[@aria-label="Edit source code"]'); - constructor( - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper, - @inject(CLASSES.BrowserTabsUtil) private readonly browserTabsUtil: BrowserTabsUtil) { - } + constructor( + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper, + @inject(CLASSES.BrowserTabsUtil) private readonly browserTabsUtil: BrowserTabsUtil) { + } - async waitApplicationIcon(): Promise { - Logger.debug(); + async waitApplicationIcon(): Promise { + Logger.debug(); - await this.driverHelper.waitPresence(OcpApplicationPage.APPLICATION_ICON_LOCATOR, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - } + await this.driverHelper.waitPresence(OcpApplicationPage.APPLICATION_ICON_LOCATOR, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + } - async waitAndOpenEditSourceCodeIcon(): Promise { - Logger.debug(); - const parentGUID: string = await this.browserTabsUtil.getCurrentWindowHandle(); - await this.driverHelper.waitAndClick(OcpApplicationPage.EDIT_SOURCE_CODE_ICON_LOCATOR); - await this.browserTabsUtil.waitAndSwitchToAnotherWindow(parentGUID, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - } + async waitAndOpenEditSourceCodeIcon(): Promise { + Logger.debug(); + const parentGUID: string = await this.browserTabsUtil.getCurrentWindowHandle(); + await this.driverHelper.waitAndClick(OcpApplicationPage.EDIT_SOURCE_CODE_ICON_LOCATOR); + await this.browserTabsUtil.waitAndSwitchToAnotherWindow(parentGUID, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + } } diff --git a/tests/e2e/pageobjects/openshift/OcpImportFromGitPage.ts b/tests/e2e/pageobjects/openshift/OcpImportFromGitPage.ts index c3da74713ab..ca893317d42 100644 --- a/tests/e2e/pageobjects/openshift/OcpImportFromGitPage.ts +++ b/tests/e2e/pageobjects/openshift/OcpImportFromGitPage.ts @@ -19,69 +19,69 @@ import { e2eContainer } from '../../configs/inversify.config'; @injectable() export class OcpImportFromGitPage { - private static readonly GIT_URL_INPUT_LOCATOR: By = By.id('form-input-git-url-field'); - private static readonly SHOW_ADVANCED_GIT_OPTIONS_LINK_LOCATOR: By = By.xpath('//*[text()="Show advanced Git options"]//ancestor::button'); - private static readonly HIDE_ADVANCED_GIT_OPTIONS_LOCATOR: By = By.xpath('//*[text()="Hide advanced Git options"]'); - private static readonly GIT_REFERENCE_INPUT_LOCATOR: By = By.id('form-input-git-ref-field'); - private static readonly EDIT_IMPORT_STRATEGY_LINK_LOCATOR: By = By.xpath('//*[text()="Edit Import Strategy"]//ancestor::button'); - private static readonly BUILDER_IMAGE_STRATEGY_ITEM_LOCATOR: By = By.xpath('//*[text()="Builder Image"]//parent::div//parent::div'); - private static readonly ADD_LABEL_LINK_LOCATOR: By = By.xpath('//button[text()="Labels"]'); - private static readonly ADD_LABEL_INPUT_LOCATOR: By = By.id('form-selector-labels-field'); - private static readonly SUBMIT_BUTTON_LOCATOR: By = By.xpath('//*[@data-test-id="submit-button"]'); - - constructor( - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { - } - - async enterGitRepoUrl(gitRepoUrl: string): Promise { - Logger.debug(); - - await this.driverHelper.enterValue(OcpImportFromGitPage.GIT_URL_INPUT_LOCATOR, gitRepoUrl); + private static readonly GIT_URL_INPUT_LOCATOR: By = By.id('form-input-git-url-field'); + private static readonly SHOW_ADVANCED_GIT_OPTIONS_LINK_LOCATOR: By = By.xpath('//*[text()="Show advanced Git options"]//ancestor::button'); + private static readonly HIDE_ADVANCED_GIT_OPTIONS_LOCATOR: By = By.xpath('//*[text()="Hide advanced Git options"]'); + private static readonly GIT_REFERENCE_INPUT_LOCATOR: By = By.id('form-input-git-ref-field'); + private static readonly EDIT_IMPORT_STRATEGY_LINK_LOCATOR: By = By.xpath('//*[text()="Edit Import Strategy"]//ancestor::button'); + private static readonly BUILDER_IMAGE_STRATEGY_ITEM_LOCATOR: By = By.xpath('//*[text()="Builder Image"]//parent::div//parent::div'); + private static readonly ADD_LABEL_LINK_LOCATOR: By = By.xpath('//button[text()="Labels"]'); + private static readonly ADD_LABEL_INPUT_LOCATOR: By = By.id('form-selector-labels-field'); + private static readonly SUBMIT_BUTTON_LOCATOR: By = By.xpath('//*[@data-test-id="submit-button"]'); + + constructor( + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { + } + + async enterGitRepoUrl(gitRepoUrl: string): Promise { + Logger.debug(); + + await this.driverHelper.enterValue(OcpImportFromGitPage.GIT_URL_INPUT_LOCATOR, gitRepoUrl); + } + + async clickOnAdvancedOptionsButton(): Promise { + Logger.debug(); + + if (!(await this.driverHelper.isVisible(OcpImportFromGitPage.HIDE_ADVANCED_GIT_OPTIONS_LOCATOR))) { + await this.driverHelper.waitAndClick(OcpImportFromGitPage.SHOW_ADVANCED_GIT_OPTIONS_LINK_LOCATOR); } + } - async clickOnAdvancedOptionsButton(): Promise { - Logger.debug(); + async enterGitReference(gitReference: string): Promise { + Logger.debug(`"${gitReference}"`); - if (!(await this.driverHelper.isVisible(OcpImportFromGitPage.HIDE_ADVANCED_GIT_OPTIONS_LOCATOR))) { - await this.driverHelper.waitAndClick(OcpImportFromGitPage.SHOW_ADVANCED_GIT_OPTIONS_LINK_LOCATOR); - } - } - - async enterGitReference(gitReference: string): Promise { - Logger.debug(`"${gitReference}"`); - - await this.driverHelper.enterValue(OcpImportFromGitPage.GIT_REFERENCE_INPUT_LOCATOR, gitReference); - } + await this.driverHelper.enterValue(OcpImportFromGitPage.GIT_REFERENCE_INPUT_LOCATOR, gitReference); + } - async selectBuilderImageImportStrategy(): Promise { - Logger.debug(); + async selectBuilderImageImportStrategy(): Promise { + Logger.debug(); - await this.driverHelper.scrollToAndClick(OcpImportFromGitPage.EDIT_IMPORT_STRATEGY_LINK_LOCATOR); - await this.driverHelper.scrollToAndClick(OcpImportFromGitPage.BUILDER_IMAGE_STRATEGY_ITEM_LOCATOR); - } + await this.driverHelper.scrollToAndClick(OcpImportFromGitPage.EDIT_IMPORT_STRATEGY_LINK_LOCATOR); + await this.driverHelper.scrollToAndClick(OcpImportFromGitPage.BUILDER_IMAGE_STRATEGY_ITEM_LOCATOR); + } - async addLabel(label: string): Promise { - Logger.debug(`"${label}"`); + async addLabel(label: string): Promise { + Logger.debug(`"${label}"`); - await this.driverHelper.scrollToAndClick(OcpImportFromGitPage.ADD_LABEL_LINK_LOCATOR); - await this.driverHelper.scrollToAndEnterValue(OcpImportFromGitPage.ADD_LABEL_INPUT_LOCATOR, label); - } + await this.driverHelper.scrollToAndClick(OcpImportFromGitPage.ADD_LABEL_LINK_LOCATOR); + await this.driverHelper.scrollToAndEnterValue(OcpImportFromGitPage.ADD_LABEL_INPUT_LOCATOR, label); + } - async submitConfiguration(): Promise { - Logger.debug(`${this.constructor.name}.${this.submitConfiguration.name}`); + async submitConfiguration(): Promise { + Logger.debug(`${this.constructor.name}.${this.submitConfiguration.name}`); - await this.driverHelper.waitAndClick(OcpImportFromGitPage.SUBMIT_BUTTON_LOCATOR); - return e2eContainer.get(CLASSES.OcpApplicationPage); - } + await this.driverHelper.waitAndClick(OcpImportFromGitPage.SUBMIT_BUTTON_LOCATOR); + return e2eContainer.get(CLASSES.OcpApplicationPage); + } - async fitAndSubmitConfiguration(gitRepoUrl: string, gitReference: string, label: string): Promise { - Logger.debug(`${this.constructor.name}.${this.fitAndSubmitConfiguration.name}`); + async fitAndSubmitConfiguration(gitRepoUrl: string, gitReference: string, label: string): Promise { + Logger.debug(`${this.constructor.name}.${this.fitAndSubmitConfiguration.name}`); - await this.enterGitRepoUrl(gitRepoUrl); - await this.clickOnAdvancedOptionsButton(); - await this.enterGitReference(gitReference); - await this.selectBuilderImageImportStrategy(); - await this.addLabel(label); - return await this.submitConfiguration(); - } + await this.enterGitRepoUrl(gitRepoUrl); + await this.clickOnAdvancedOptionsButton(); + await this.enterGitReference(gitReference); + await this.selectBuilderImageImportStrategy(); + await this.addLabel(label); + return await this.submitConfiguration(); + } } diff --git a/tests/e2e/pageobjects/openshift/OcpMainPage.ts b/tests/e2e/pageobjects/openshift/OcpMainPage.ts index 958b76d031a..ff30bbe0af2 100644 --- a/tests/e2e/pageobjects/openshift/OcpMainPage.ts +++ b/tests/e2e/pageobjects/openshift/OcpMainPage.ts @@ -20,90 +20,90 @@ import { e2eContainer } from '../../configs/inversify.config'; @injectable() export class OcpMainPage { - private static readonly MAIN_PAGE_HEADER_LOCATOR: By = By.id('page-main-header'); - private static readonly SELECT_ROLE_BUTTON_LOCATOR: By = By.xpath('//*[@data-test-id="perspective-switcher-toggle"]'); - private static readonly ADD_BUTTON_LOCATOR: By = By.xpath('//*[@data-test-id="+Add-header"]'); - private static readonly IMPORT_FROM_GIT_ITEM_LOCATOR: By = By.xpath('//*[@data-test="item import-from-git"]'); - private static readonly SELECT_PROJECT_DROPDOWN_LOCATOR: By = By.xpath('//div[@class="co-namespace-dropdown"]//button'); - private static readonly PROJECT_FILTER_INPUT_LOCATOR: By = By.xpath('//*[@data-test="dropdown-text-filter"]'); - private static readonly SKIP_TOUR_BUTTON_LOCATOR: By = By.xpath('//*[text()="Skip tour"]'); - - private static getRoleLocator(role: string): By { - return By.xpath(`//a//*[text()="${role}"]`); - } + private static readonly MAIN_PAGE_HEADER_LOCATOR: By = By.id('page-main-header'); + private static readonly SELECT_ROLE_BUTTON_LOCATOR: By = By.xpath('//*[@data-test-id="perspective-switcher-toggle"]'); + private static readonly ADD_BUTTON_LOCATOR: By = By.xpath('//*[@data-test-id="+Add-header"]'); + private static readonly IMPORT_FROM_GIT_ITEM_LOCATOR: By = By.xpath('//*[@data-test="item import-from-git"]'); + private static readonly SELECT_PROJECT_DROPDOWN_LOCATOR: By = By.xpath('//div[@class="co-namespace-dropdown"]//button'); + private static readonly PROJECT_FILTER_INPUT_LOCATOR: By = By.xpath('//*[@data-test="dropdown-text-filter"]'); + private static readonly SKIP_TOUR_BUTTON_LOCATOR: By = By.xpath('//*[text()="Skip tour"]'); - private static getProjectDropdownItemLocator(projectName: string): By { - return By.xpath(`//button//*[text()="${projectName}"]`); - } + private static getRoleLocator(role: string): By { + return By.xpath(`//a//*[text()="${role}"]`); + } - constructor( - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + private static getProjectDropdownItemLocator(projectName: string): By { + return By.xpath(`//button//*[text()="${projectName}"]`); + } - async waitOpenMainPage(): Promise { - Logger.debug(); + constructor( + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - await this.driverHelper.waitVisibility(OcpMainPage.MAIN_PAGE_HEADER_LOCATOR, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); - } + async waitOpenMainPage(): Promise { + Logger.debug(); - async clickOnSelectRoleButton(): Promise { - Logger.debug(); + await this.driverHelper.waitVisibility(OcpMainPage.MAIN_PAGE_HEADER_LOCATOR, TimeoutConstants.TS_SELENIUM_LOAD_PAGE_TIMEOUT); + } - await this.driverHelper.waitAndClick(OcpMainPage.SELECT_ROLE_BUTTON_LOCATOR); - } + async clickOnSelectRoleButton(): Promise { + Logger.debug(); - async clickAddToProjectButton(): Promise { - Logger.debug(); + await this.driverHelper.waitAndClick(OcpMainPage.SELECT_ROLE_BUTTON_LOCATOR); + } - await this.driverHelper.waitAndClick(OcpMainPage.ADD_BUTTON_LOCATOR); - } + async clickAddToProjectButton(): Promise { + Logger.debug(); - async selectDeveloperRole(): Promise { - Logger.debug(); + await this.driverHelper.waitAndClick(OcpMainPage.ADD_BUTTON_LOCATOR); + } - await this.waitOpenMainPage(); - await this.tryToSkipWebTour(); - await this.clickOnSelectRoleButton(); - await this.selectRole('Developer'); - await this.tryToSkipWebTour(); - } + async selectDeveloperRole(): Promise { + Logger.debug(); - async selectImportFromGitMethod(): Promise { - Logger.debug(); + await this.waitOpenMainPage(); + await this.tryToSkipWebTour(); + await this.clickOnSelectRoleButton(); + await this.selectRole('Developer'); + await this.tryToSkipWebTour(); + } - await this.driverHelper.waitAndClick(OcpMainPage.IMPORT_FROM_GIT_ITEM_LOCATOR); - return e2eContainer.get(CLASSES.OcpImportFromGitPage); - } + async selectImportFromGitMethod(): Promise { + Logger.debug(); - async openImportFromGitPage(): Promise { - Logger.debug(); + await this.driverHelper.waitAndClick(OcpMainPage.IMPORT_FROM_GIT_ITEM_LOCATOR); + return e2eContainer.get(CLASSES.OcpImportFromGitPage); + } - await this.clickAddToProjectButton(); - return await this.selectImportFromGitMethod(); - } + async openImportFromGitPage(): Promise { + Logger.debug(); - async selectProject(projectName: string): Promise { - Logger.debug(); + await this.clickAddToProjectButton(); + return await this.selectImportFromGitMethod(); + } - await this.driverHelper.waitAndClick(OcpMainPage.SELECT_PROJECT_DROPDOWN_LOCATOR); - await this.driverHelper.enterValue(OcpMainPage.PROJECT_FILTER_INPUT_LOCATOR, projectName); - await this.driverHelper.waitAndClick(OcpMainPage.getProjectDropdownItemLocator(projectName)); - } + async selectProject(projectName: string): Promise { + Logger.debug(); - private async selectRole(role: string): Promise { - Logger.debug(`selecting role ${role}`); + await this.driverHelper.waitAndClick(OcpMainPage.SELECT_PROJECT_DROPDOWN_LOCATOR); + await this.driverHelper.enterValue(OcpMainPage.PROJECT_FILTER_INPUT_LOCATOR, projectName); + await this.driverHelper.waitAndClick(OcpMainPage.getProjectDropdownItemLocator(projectName)); + } - await this.driverHelper.waitAndClick(OcpMainPage.getRoleLocator(role)); - } + private async selectRole(role: string): Promise { + Logger.debug(`selecting role ${role}`); + + await this.driverHelper.waitAndClick(OcpMainPage.getRoleLocator(role)); + } - private async tryToSkipWebTour(): Promise { - Logger.debug(); + private async tryToSkipWebTour(): Promise { + Logger.debug(); - if (await this.driverHelper.isVisible(OcpMainPage.SKIP_TOUR_BUTTON_LOCATOR)) { - await this.driverHelper.waitAndClick(OcpMainPage.SKIP_TOUR_BUTTON_LOCATOR); + if (await this.driverHelper.isVisible(OcpMainPage.SKIP_TOUR_BUTTON_LOCATOR)) { + await this.driverHelper.waitAndClick(OcpMainPage.SKIP_TOUR_BUTTON_LOCATOR); - Logger.debug(`welcome tour modal dialog was located and skipped`); - } else { - Logger.debug(`welcome tour modal dialog was not located`); - } + Logger.debug(`welcome tour modal dialog was located and skipped`); + } else { + Logger.debug(`welcome tour modal dialog was not located`); } + } } diff --git a/tests/e2e/specs/MochaHooks.ts b/tests/e2e/specs/MochaHooks.ts index 58d5aea54b4..bbfa31359cb 100644 --- a/tests/e2e/specs/MochaHooks.ts +++ b/tests/e2e/specs/MochaHooks.ts @@ -28,51 +28,51 @@ const testWorkspaceUtil: ITestWorkspaceUtil = e2eContainer.get(TYPES.WorkspaceUt let latestWorkspace: string = ''; export function registerRunningWorkspace(workspaceName: string): void { - Logger.debug(`with workspaceName:${workspaceName}`); - latestWorkspace = workspaceName; + Logger.debug(`with workspaceName:${workspaceName}`); + latestWorkspace = workspaceName; } exports.mochaHooks = { - beforeAll: [ - async function enableRequestInterceptor(): Promise { - if (BaseTestConstants.TS_SELENIUM_REQUEST_INTERCEPTOR) { - CheApiRequestHandler.enableRequestInterceptor(); - } - }, - async function enableResponseInterceptor(): Promise { - if (BaseTestConstants.TS_SELENIUM_RESPONSE_INTERCEPTOR) { - CheApiRequestHandler.enableResponseInterceptor(); - } - }, - async function initMonacoPageObjects(): Promise { - // init vscode-extension-tester monaco-page-objects - monacoPageObjects.initPageObjects(MonacoConstants.TS_SELENIUM_MONACO_PAGE_OBJECTS_USE_VERSION, MonacoConstants.TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION, vscodeExtensionTesterLocators.getLocatorsPath(), driverHelper.getDriver(), 'google-chrome'); - }, - async function prolongTimeoutConstantsInDebugMode(): Promise { - if (BaseTestConstants.TS_DEBUG_MODE) { - for (let [timeout, seconds] of Object.entries(TimeoutConstants)) { - Object.defineProperty(TimeoutConstants, timeout, { value: seconds as number * 100 }); - } - } - }, - ], - afterEach: [ - // stop and remove running workspace - async function (this: Mocha.Context): Promise { - if (this.currentTest?.state === 'failed') { - if (BaseTestConstants.DELETE_WORKSPACE_ON_FAILED_TEST) { - Logger.info('Property DELETE_WORKSPACE_ON_FAILED_TEST is true - trying to stop and delete running workspace with API.'); - await testWorkspaceUtil.stopAndDeleteWorkspaceByName(latestWorkspace); - } - } - }, - ], - afterAll: [ - async function stopTheDriver(): Promise { - if (!BaseTestConstants.TS_DEBUG_MODE && ChromeDriverConstants.TS_USE_WEB_DRIVER_FOR_TEST) { - await driverHelper.getDriver().quit(); - Logger.info('Chrome driver session stopped.'); - } - }, - ] + beforeAll: [ + async function enableRequestInterceptor(): Promise { + if (BaseTestConstants.TS_SELENIUM_REQUEST_INTERCEPTOR) { + CheApiRequestHandler.enableRequestInterceptor(); + } + }, + async function enableResponseInterceptor(): Promise { + if (BaseTestConstants.TS_SELENIUM_RESPONSE_INTERCEPTOR) { + CheApiRequestHandler.enableResponseInterceptor(); + } + }, + async function initMonacoPageObjects(): Promise { + // init vscode-extension-tester monaco-page-objects + monacoPageObjects.initPageObjects(MonacoConstants.TS_SELENIUM_MONACO_PAGE_OBJECTS_USE_VERSION, MonacoConstants.TS_SELENIUM_MONACO_PAGE_OBJECTS_BASE_VERSION, vscodeExtensionTesterLocators.getLocatorsPath(), driverHelper.getDriver(), 'google-chrome'); + }, + async function prolongTimeoutConstantsInDebugMode(): Promise { + if (BaseTestConstants.TS_DEBUG_MODE) { + for (let [timeout, seconds] of Object.entries(TimeoutConstants)) { + Object.defineProperty(TimeoutConstants, timeout, { value: seconds as number * 100 }); + } + } + }, + ], + afterEach: [ + // stop and remove running workspace + async function(this: Mocha.Context): Promise { + if (this.currentTest?.state === 'failed') { + if (BaseTestConstants.DELETE_WORKSPACE_ON_FAILED_TEST) { + Logger.info('Property DELETE_WORKSPACE_ON_FAILED_TEST is true - trying to stop and delete running workspace with API.'); + await testWorkspaceUtil.stopAndDeleteWorkspaceByName(latestWorkspace); + } + } + }, + ], + afterAll: [ + async function stopTheDriver(): Promise { + if (!BaseTestConstants.TS_DEBUG_MODE && ChromeDriverConstants.TS_USE_WEB_DRIVER_FOR_TEST) { + await driverHelper.getDriver().quit(); + Logger.info('Chrome driver session stopped.'); + } + }, + ] }; diff --git a/tests/e2e/specs/SmokeTest.spec.ts b/tests/e2e/specs/SmokeTest.spec.ts index 5d80a80a196..734e67bfe86 100644 --- a/tests/e2e/specs/SmokeTest.spec.ts +++ b/tests/e2e/specs/SmokeTest.spec.ts @@ -26,40 +26,40 @@ const workspaceHandlingTests: WorkspaceHandlingTests = e2eContainer.get(CLASSES. const loginTests: LoginTests = e2eContainer.get(CLASSES.LoginTests); const browserTabsUtil: BrowserTabsUtil = e2eContainer.get(CLASSES.BrowserTabsUtil); -suite(`The SmokeTest userstory`, async function (): Promise { - const factoryUrl: string = FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_URL || 'https://github.com/che-incubator/quarkus-api-example.git'; - let projectSection: ViewSection; - suite(`Create workspace from factory:${factoryUrl}`, async function (): Promise { - loginTests.loginIntoChe(); - test(`Create and open new workspace from factory:${factoryUrl}`, async function (): Promise { - await workspaceHandlingTests.createAndOpenWorkspaceFromGitRepository(factoryUrl); - }); - test('Obtain workspace name from workspace loader page', async function (): Promise { - await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); +suite(`The SmokeTest userstory`, async function(): Promise { + const factoryUrl: string = FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_URL || 'https://github.com/che-incubator/quarkus-api-example.git'; + let projectSection: ViewSection; + suite(`Create workspace from factory:${factoryUrl}`, async function(): Promise { + loginTests.loginIntoChe(); + test(`Create and open new workspace from factory:${factoryUrl}`, async function(): Promise { + await workspaceHandlingTests.createAndOpenWorkspaceFromGitRepository(factoryUrl); }); - test('Register running workspace', async function (): Promise { - registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); - test('Wait workspace readiness', async function (): Promise { - await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); - }); - test('Check a project folder has been created', async function (): Promise { - const projectName: string = FactoryTestConstants.TS_SELENIUM_PROJECT_NAME || StringUtil.getProjectNameFromGitUrl(factoryUrl); - projectSection = await new SideBarView().getContent().getSection(projectName); - Logger.debug(`new SideBarView().getContent().getSection: get ${projectName}`); - }); - test('Check the project files was imported', async function (): Promise { - Logger.debug(`projectSection.findItem: find ${BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME}`); - const isFileImported: ViewItem | undefined = await projectSection.findItem(BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME); - expect(isFileImported).not.eqls(undefined); - }); - test('Stop the workspace', async function (): Promise { - await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - await browserTabsUtil.closeAllTabsExceptCurrent(); - }); - test('Delete the workspace', async function (): Promise { - await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); - loginTests.logoutFromChe(); + test('Obtain workspace name from workspace loader page', async function(): Promise { + await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); }); + test('Register running workspace', async function(): Promise { + registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); + test('Wait workspace readiness', async function(): Promise { + await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + }); + test('Check a project folder has been created', async function(): Promise { + const projectName: string = FactoryTestConstants.TS_SELENIUM_PROJECT_NAME || StringUtil.getProjectNameFromGitUrl(factoryUrl); + projectSection = await new SideBarView().getContent().getSection(projectName); + Logger.debug(`new SideBarView().getContent().getSection: get ${projectName}`); + }); + test('Check the project files was imported', async function(): Promise { + Logger.debug(`projectSection.findItem: find ${BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME}`); + const isFileImported: ViewItem | undefined = await projectSection.findItem(BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME); + expect(isFileImported).not.eqls(undefined); + }); + test('Stop the workspace', async function(): Promise { + await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + await browserTabsUtil.closeAllTabsExceptCurrent(); + }); + test('Delete the workspace', async function(): Promise { + await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); + loginTests.logoutFromChe(); + }); }); diff --git a/tests/e2e/specs/api/ContainerOverridesAPI.spec.ts b/tests/e2e/specs/api/ContainerOverridesAPI.spec.ts index cb420326e62..92af847cfcf 100644 --- a/tests/e2e/specs/api/ContainerOverridesAPI.spec.ts +++ b/tests/e2e/specs/api/ContainerOverridesAPI.spec.ts @@ -5,34 +5,34 @@ import YAML from 'yaml'; import { expect } from 'chai'; import { ShellExecutor } from '../../utils/ShellExecutor'; -suite(`Test defining container overrides via attribute.`, async function (): Promise { - const pathToSampleFile: string = path.resolve('resources/container-overrides.yaml'); - const workspaceName: string = YAML.parse(fs.readFileSync(pathToSampleFile, 'utf8')).metadata.name; - const kubernetesCommandLineToolsExecutor: KubernetesCommandLineToolsExecutor = new KubernetesCommandLineToolsExecutor(workspaceName); +suite(`Test defining container overrides via attribute.`, async function(): Promise { + const pathToSampleFile: string = path.resolve('resources/container-overrides.yaml'); + const workspaceName: string = YAML.parse(fs.readFileSync(pathToSampleFile, 'utf8')).metadata.name; + const kubernetesCommandLineToolsExecutor: KubernetesCommandLineToolsExecutor = new KubernetesCommandLineToolsExecutor(workspaceName); - suiteSetup('Login into OC client', function (): void { - kubernetesCommandLineToolsExecutor.loginToOcp(); - }); + suiteSetup('Login into OC client', function(): void { + kubernetesCommandLineToolsExecutor.loginToOcp(); + }); - suiteTeardown('Delete DevWorkspace', function (): void { - kubernetesCommandLineToolsExecutor.deleteDevWorkspace(); - }); + suiteTeardown('Delete DevWorkspace', function(): void { + kubernetesCommandLineToolsExecutor.deleteDevWorkspace(); + }); - test('Apply container-overrides sample as DevWorkspace with OC client', function (): void { - kubernetesCommandLineToolsExecutor.applyYamlConfigurationAsFile(pathToSampleFile); - ShellExecutor.wait(5); - }); + test('Apply container-overrides sample as DevWorkspace with OC client', function(): void { + kubernetesCommandLineToolsExecutor.applyYamlConfigurationAsFile(pathToSampleFile); + ShellExecutor.wait(5); + }); - test('Check that fields are overridden in the Deployment for DevWorkspace', function (): void { - const devWorkspaceFullYamlOutput: any = YAML.parse(kubernetesCommandLineToolsExecutor.getDevWorkspaceYamlConfiguration()); - expect(devWorkspaceFullYamlOutput.spec.template.components[0].attributes['container-overrides']).eqls({ - resources: { - limits: { - 'nvidia.com/gpu': '1' - } - } - }); + test('Check that fields are overridden in the Deployment for DevWorkspace', function(): void { + const devWorkspaceFullYamlOutput: any = YAML.parse(kubernetesCommandLineToolsExecutor.getDevWorkspaceYamlConfiguration()); + expect(devWorkspaceFullYamlOutput.spec.template.components[0].attributes['container-overrides']).eqls({ + resources: { + limits: { + 'nvidia.com/gpu': '1' + } + } }); + }); }); diff --git a/tests/e2e/specs/api/EmptyWorkspaceAPI.spec.ts b/tests/e2e/specs/api/EmptyWorkspaceAPI.spec.ts index 92ee904d8c6..43da6543321 100644 --- a/tests/e2e/specs/api/EmptyWorkspaceAPI.spec.ts +++ b/tests/e2e/specs/api/EmptyWorkspaceAPI.spec.ts @@ -7,68 +7,68 @@ import { DevfileContext } from '@eclipse-che/che-devworkspace-generator/lib/api/ import { APITestConstants } from '../../constants/APITestConstants'; import { BaseTestConstants } from '../../constants/BaseTestConstants'; -suite(`Empty workspace API test`, async function (): Promise { - // works only for root user - const namespace: string = APITestConstants.TS_API_TEST_NAMESPACE; - let clonedProjectName: string; - let containerWorkDir: string; - let devWorkspaceConfigurationHelper: DevWorkspaceConfigurationHelper; - let kubernetesCommandLineToolsExecutor: KubernetesCommandLineToolsExecutor; - let devfileContext: DevfileContext; - let devWorkspaceName: string | undefined; - let containerTerminal: KubernetesCommandLineToolsExecutor.ContainerTerminal; +suite(`Empty workspace API test`, async function(): Promise { + // works only for root user + const namespace: string = APITestConstants.TS_API_TEST_NAMESPACE; + let clonedProjectName: string; + let containerWorkDir: string; + let devWorkspaceConfigurationHelper: DevWorkspaceConfigurationHelper; + let kubernetesCommandLineToolsExecutor: KubernetesCommandLineToolsExecutor; + let devfileContext: DevfileContext; + let devWorkspaceName: string | undefined; + let containerTerminal: KubernetesCommandLineToolsExecutor.ContainerTerminal; - const gitRepository: string = 'https://github.com/crw-qe/web-nodejs-sample'; + const gitRepository: string = 'https://github.com/crw-qe/web-nodejs-sample'; - suiteSetup('Create empty workspace with OC client', async function (): Promise { - const workspaceName: string = 'empty-' + Math.floor(Math.random() * 1000); - const devfileContent: string = - 'schemaVersion: 2.2.0\n' + - 'metadata:\n' + - ` name: ${workspaceName}\n`; + suiteSetup('Create empty workspace with OC client', async function(): Promise { + const workspaceName: string = 'empty-' + Math.floor(Math.random() * 1000); + const devfileContent: string = + 'schemaVersion: 2.2.0\n' + + 'metadata:\n' + + ` name: ${workspaceName}\n`; - devWorkspaceConfigurationHelper = new DevWorkspaceConfigurationHelper({ - devfileContent, - }); - devfileContext = await devWorkspaceConfigurationHelper.generateDevfileContext(); - devWorkspaceName = devfileContext?.devWorkspace?.metadata?.name; - kubernetesCommandLineToolsExecutor = new KubernetesCommandLineToolsExecutor(devWorkspaceName, namespace); - containerTerminal = new KubernetesCommandLineToolsExecutor.ContainerTerminal(kubernetesCommandLineToolsExecutor); + devWorkspaceConfigurationHelper = new DevWorkspaceConfigurationHelper({ + devfileContent }); + devfileContext = await devWorkspaceConfigurationHelper.generateDevfileContext(); + devWorkspaceName = devfileContext?.devWorkspace?.metadata?.name; + kubernetesCommandLineToolsExecutor = new KubernetesCommandLineToolsExecutor(devWorkspaceName, namespace); + containerTerminal = new KubernetesCommandLineToolsExecutor.ContainerTerminal(kubernetesCommandLineToolsExecutor); + }); - test('Create empty workspace', async function (): Promise { - kubernetesCommandLineToolsExecutor.loginToOcp(); - const devWorkspaceConfigurationYamlString: string = await devWorkspaceConfigurationHelper.getDevWorkspaceConfigurationYamlAsString(devfileContext); - const output: ShellString = kubernetesCommandLineToolsExecutor.applyAndWaitDevWorkspace(devWorkspaceConfigurationYamlString); - expect(output.stdout).contains('condition met'); - }); - - suite('Clone public repo without previous setup', function (): void { + test('Create empty workspace', async function(): Promise { + kubernetesCommandLineToolsExecutor.loginToOcp(); + const devWorkspaceConfigurationYamlString: string = await devWorkspaceConfigurationHelper.getDevWorkspaceConfigurationYamlAsString(devfileContext); + const output: ShellString = kubernetesCommandLineToolsExecutor.applyAndWaitDevWorkspace(devWorkspaceConfigurationYamlString); + expect(output.stdout).contains('condition met'); + }); - test('Check if public repo can be cloned', function (): void { - containerWorkDir = containerTerminal.pwd().stdout.replace('\n', ''); - const cloneOutput: ShellString = containerTerminal.gitClone(gitRepository); - expect(cloneOutput.stdout + cloneOutput.stderr).includes('Cloning'); - }); + suite('Clone public repo without previous setup', function(): void { - test('Check if project was created', function (): void { - clonedProjectName = StringUtil.getProjectNameFromGitUrl(gitRepository); - expect(containerTerminal.ls().stdout).includes(clonedProjectName); - }); + test('Check if public repo can be cloned', function(): void { + containerWorkDir = containerTerminal.pwd().stdout.replace('\n', ''); + const cloneOutput: ShellString = containerTerminal.gitClone(gitRepository); + expect(cloneOutput.stdout + cloneOutput.stderr).includes('Cloning'); + }); - test('Check if project files are imported', function (): void { - expect(containerTerminal.ls(`${containerWorkDir}/${clonedProjectName}`).stdout) - .includes(BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME); - }); + test('Check if project was created', function(): void { + clonedProjectName = StringUtil.getProjectNameFromGitUrl(gitRepository); + expect(containerTerminal.ls().stdout).includes(clonedProjectName); + }); - suiteTeardown('Delete cloned project', function (): void { - containerTerminal.removeFolder(`${clonedProjectName}`); - }); + test('Check if project files are imported', function(): void { + expect(containerTerminal.ls(`${containerWorkDir}/${clonedProjectName}`).stdout) + .includes(BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME); }); - suiteTeardown('Delete workspace', function (): void { - kubernetesCommandLineToolsExecutor.deleteDevWorkspace(); + suiteTeardown('Delete cloned project', function(): void { + containerTerminal.removeFolder(`${clonedProjectName}`); }); + }); + + suiteTeardown('Delete workspace', function(): void { + kubernetesCommandLineToolsExecutor.deleteDevWorkspace(); + }); }); diff --git a/tests/e2e/specs/api/PodOverridesAPI.spec.ts b/tests/e2e/specs/api/PodOverridesAPI.spec.ts index 10cdcb529d3..a57e307ba50 100644 --- a/tests/e2e/specs/api/PodOverridesAPI.spec.ts +++ b/tests/e2e/specs/api/PodOverridesAPI.spec.ts @@ -5,40 +5,40 @@ import YAML from 'yaml'; import { expect } from 'chai'; import { ShellExecutor } from '../../utils/ShellExecutor'; -suite(`Test defining pod overrides via attribute.`, async function (): Promise { - const pathToSampleFile: string = path.resolve('resources/pod-overrides.yaml'); - const workspaceName: string = YAML.parse(fs.readFileSync(pathToSampleFile, 'utf8')).metadata.name; - const kubernetesCommandLineToolsExecutor: KubernetesCommandLineToolsExecutor = new KubernetesCommandLineToolsExecutor(workspaceName); +suite(`Test defining pod overrides via attribute.`, async function(): Promise { + const pathToSampleFile: string = path.resolve('resources/pod-overrides.yaml'); + const workspaceName: string = YAML.parse(fs.readFileSync(pathToSampleFile, 'utf8')).metadata.name; + const kubernetesCommandLineToolsExecutor: KubernetesCommandLineToolsExecutor = new KubernetesCommandLineToolsExecutor(workspaceName); - suiteSetup('Login into OC client', function (): void { - kubernetesCommandLineToolsExecutor.loginToOcp(); - }); + suiteSetup('Login into OC client', function(): void { + kubernetesCommandLineToolsExecutor.loginToOcp(); + }); - suiteTeardown('Delete DevWorkspace', function (): void { - kubernetesCommandLineToolsExecutor.deleteDevWorkspace(); - }); + suiteTeardown('Delete DevWorkspace', function(): void { + kubernetesCommandLineToolsExecutor.deleteDevWorkspace(); + }); - test('Apply pod-overrides sample as DevWorkspace with OC client', function (): void { - kubernetesCommandLineToolsExecutor.applyYamlConfigurationAsFile(pathToSampleFile); - ShellExecutor.wait(5); - }); + test('Apply pod-overrides sample as DevWorkspace with OC client', function(): void { + kubernetesCommandLineToolsExecutor.applyYamlConfigurationAsFile(pathToSampleFile); + ShellExecutor.wait(5); + }); - test('Check that fields are overridden in the Deployment for DevWorkspace', function (): void { - const devWorkspaceFullYamlOutput: any = YAML.parse(kubernetesCommandLineToolsExecutor.getDevWorkspaceYamlConfiguration()); - expect(devWorkspaceFullYamlOutput.spec.template.attributes['pod-overrides']).eqls({ - metadata: { - annotations: { - 'io.kubernetes.cri-o.userns-mode': 'auto:size=65536;map-to-root=true', - 'io.openshift.userns': 'true', - 'openshift.io/scc': 'container-build' - } - }, - spec: { - runtimeClassName: 'kata', - schedulerName: 'stork' - } - }); + test('Check that fields are overridden in the Deployment for DevWorkspace', function(): void { + const devWorkspaceFullYamlOutput: any = YAML.parse(kubernetesCommandLineToolsExecutor.getDevWorkspaceYamlConfiguration()); + expect(devWorkspaceFullYamlOutput.spec.template.attributes['pod-overrides']).eqls({ + metadata: { + annotations: { + 'io.kubernetes.cri-o.userns-mode': 'auto:size=65536;map-to-root=true', + 'io.openshift.userns': 'true', + 'openshift.io/scc': 'container-build' + } + }, + spec: { + runtimeClassName: 'kata', + schedulerName: 'stork' + } }); + }); }); diff --git a/tests/e2e/specs/dashboard-samples/Quarkus.spec.ts b/tests/e2e/specs/dashboard-samples/Quarkus.spec.ts index af8a61a909d..67abbe0b6c7 100644 --- a/tests/e2e/specs/dashboard-samples/Quarkus.spec.ts +++ b/tests/e2e/specs/dashboard-samples/Quarkus.spec.ts @@ -27,44 +27,44 @@ const browserTabsUtil: BrowserTabsUtil = e2eContainer.get(CLASSES.BrowserTabsUti const stackName: string = 'Java 11 with Quarkus'; const projectName: string = 'quarkus-quickstarts'; -suite(`The ${stackName} userstory`, async function (): Promise { - let projectSection: ViewSection; +suite(`The ${stackName} userstory`, async function(): Promise { + let projectSection: ViewSection; - loginTests.loginIntoChe(); + loginTests.loginIntoChe(); - test(`Create and open new workspace, stack:${stackName}`, async function (): Promise { - await workspaceHandlingTests.createAndOpenWorkspace(stackName); - }); + test(`Create and open new workspace, stack:${stackName}`, async function(): Promise { + await workspaceHandlingTests.createAndOpenWorkspace(stackName); + }); - test('Obtain workspace name from workspace loader page', async function (): Promise { - await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); - }); + test('Obtain workspace name from workspace loader page', async function(): Promise { + await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); + }); - test('Register running workspace', async function (): Promise { - registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); + test('Register running workspace', async function(): Promise { + registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); - test('Wait workspace readiness', async function (): Promise { - await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); - }); + test('Wait workspace readiness', async function(): Promise { + await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + }); - test('Check a project folder has been created', async function (): Promise { - projectSection = await new SideBarView().getContent().getSection(projectName); - Logger.debug(`new SideBarView().getContent().getSection: get ${projectName}`); - }); + test('Check a project folder has been created', async function(): Promise { + projectSection = await new SideBarView().getContent().getSection(projectName); + Logger.debug(`new SideBarView().getContent().getSection: get ${projectName}`); + }); - test('Check the project files was imported', async function (): Promise { - await projectSection.findItem(BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME); - Logger.debug(`projectSection.findItem: find ${BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME}`); - }); + test('Check the project files was imported', async function(): Promise { + await projectSection.findItem(BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME); + Logger.debug(`projectSection.findItem: find ${BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME}`); + }); - test('Stop the workspace', async function (): Promise { - await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - await browserTabsUtil.closeAllTabsExceptCurrent(); - }); + test('Stop the workspace', async function(): Promise { + await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + await browserTabsUtil.closeAllTabsExceptCurrent(); + }); - test('Delete the workspace', async function (): Promise { - await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); - loginTests.logoutFromChe(); + test('Delete the workspace', async function(): Promise { + await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); + loginTests.logoutFromChe(); }); diff --git a/tests/e2e/specs/dashboard-samples/RecommendedExtensions.spec.ts b/tests/e2e/specs/dashboard-samples/RecommendedExtensions.spec.ts index 796d6795deb..c7b3375addb 100644 --- a/tests/e2e/specs/dashboard-samples/RecommendedExtensions.spec.ts +++ b/tests/e2e/specs/dashboard-samples/RecommendedExtensions.spec.ts @@ -46,160 +46,160 @@ const webCheCodeLocators: Locators = new CheCodeLocatorLoader().webCheCodeLocato const samples: string[] = PluginsTestConstants.TS_SAMPLE_LIST.split(','); const browserTabsUtil: BrowserTabsUtil = e2eContainer.get(CLASSES.BrowserTabsUtil); -suite(`Check if recommended extensions installed for ${samples}`, async function (): Promise { - let projectSection: ViewSection; - let extensionsView: SideBarView | undefined; - let extensionSection: ExtensionsViewSection; +suite(`Check if recommended extensions installed for ${samples}`, async function(): Promise { + let projectSection: ViewSection; + let extensionsView: SideBarView | undefined; + let extensionSection: ExtensionsViewSection; - const extensionsListFileName: string = 'extensions.json'; - let recommendedExtensions: any = { - recommendations: [] - }; + const extensionsListFileName: string = 'extensions.json'; + let recommendedExtensions: any = { + recommendations: [] + }; - loginTests.loginIntoChe(); + loginTests.loginIntoChe(); - for (const sample of samples) { - test(`Create and open new workspace, stack:${sample}`, async function (): Promise { - await workspaceHandlingTests.createAndOpenWorkspace(sample); + for (const sample of samples) { + test(`Create and open new workspace, stack:${sample}`, async function(): Promise { + await workspaceHandlingTests.createAndOpenWorkspace(sample); }); - test('Obtain workspace name from workspace loader page', async function (): Promise { - await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); + test('Obtain workspace name from workspace loader page', async function(): Promise { + await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); }); - test('Registering the running workspace', async function (): Promise { - registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); - - test('Wait workspace readiness', async function (): Promise { - await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); - }); - - test('Wait until the project will be imported and accept it as trusted one', async function (): Promise { - [projectSection] = await new SideBarView().getContent().getSections(); - const label: string = BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME; - Logger.debug(`projectSection.findItem: find ${label}`); - const isFileImported: ViewItem | undefined = await projectSection.findItem(label); - expect(isFileImported).not.eqls(undefined); - try { - const buttonYesITrustTheAuthors: string = `Yes, I trust the authors`; - await driverHelper.waitVisibility(webCheCodeLocators.WelcomeContent.button, TimeoutConstants.TS_DIALOG_WINDOW_DEFAULT_TIMEOUT); - const trustedProjectDialog: ModalDialog = new ModalDialog(); - Logger.debug(`trustedProjectDialog.pushButton: "${buttonYesITrustTheAuthors}"`); - await trustedProjectDialog.pushButton(buttonYesITrustTheAuthors); - } catch (e) { - Logger.debug(`Welcome modal dialog was not shown: ${e}`); - } - }); - - test(`Get recommended extensions list from ${extensionsListFileName}`, async function (): Promise { - Logger.debug(`projectSection.findItem(item))?.select(): expand .vscode folder and open extensions.json.`); - await (await projectSection.findItem('.vscode'))?.select(); - // time to expand project tree - await driverHelper.wait(TimeoutConstants.TS_EXPAND_PROJECT_TREE_ITEM_TIMEOUT); - await (await projectSection.findItem(extensionsListFileName))?.select(); - Logger.debug(`EditorView().openEditor(${extensionsListFileName})`); - const editor: TextEditor = await new EditorView().openEditor(extensionsListFileName) as TextEditor; - await driverHelper.waitVisibility(webCheCodeLocators.Editor.inputArea); - Logger.debug(`editor.getText(): get recommended extensions as text from editor, delete comments and parse to object.`); - recommendedExtensions = JSON.parse((await editor.getText()).replace(/\/\*[\s\S]*?\*\/|(?<=[^:])\/\/.*|^\/\/.*/g, '').trim()); - Logger.debug(`recommendedExtensions.recommendations: Get recommendations clear names using map().`); - recommendedExtensions.recommendations = recommendedExtensions.recommendations.map((r: { split: (arg: string) => [any, any]; }) => { - const [publisher, name] = r.split('.'); - return {publisher, name}; - }); - Logger.info(`Recommended extension for this workspace:\n${JSON.stringify(recommendedExtensions.recommendations)}.`); - }); - - test(`Open "Extensions" view section`, async function (): Promise { - Logger.debug(`ActivityBar().getViewControl('Extensions'))?.openView(): open Extensions view.`); - extensionsView = await (await new ActivityBar().getViewControl('Extensions'))?.openView(); - }); - - test(`Let extensions complete installation`, async function (): Promise { - Logger.info(`Time for extensions installation TimeoutConstants.TS_COMMON_PLUGIN_TEST_TIMEOUT=${TimeoutConstants.TS_COMMON_PLUGIN_TEST_TIMEOUT}`); - await driverHelper.wait(TimeoutConstants.TS_COMMON_PLUGIN_TEST_TIMEOUT); - }); - - test(`Check if extensions are installed and enabled`, async function (): Promise { - this.retries(10); - Logger.debug(`ActivityBar().getViewControl('Extensions'))?.openView(): open Extensions view.`); - extensionsView = await (await new ActivityBar().getViewControl('Extensions'))?.openView(); - - Logger.debug(`extensionsView?.getContent().getSections(): get current section.`); - [extensionSection] = await extensionsView?.getContent().getSections() as ExtensionsViewSection[]; - await driverHelper.waitAllPresence(webCheCodeLocators.ExtensionsViewSection.itemTitle, TimeoutConstants.TS_EDITOR_TAB_INTERACTION_TIMEOUT); - - for (const extension of recommendedExtensions.recommendations) { - Logger.info(`Check if ${JSON.stringify(extension)} are installed.`); - - Logger.debug(`extensionSection.findItem(${extension.name}).`); - await extensionSection.findItem(extension.name); - - // check if extension require reload the page - if (await driverHelper.isVisible((webCheCodeLocators.ExtensionsViewSection as any).requireReloadButton)) { - Logger.debug(`Extension require reload the editor. Refreshing the page..`); - await browserTabsUtil.refreshPage(); - await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); - Logger.debug(`ActivityBar().getViewControl('Extensions'))?.openView(): open Extensions view.`); - extensionsView = await (await new ActivityBar().getViewControl('Extensions'))?.openView(); - Logger.debug(`extensionsView?.getContent().getSections(): get current section.`); - [extensionSection] = await extensionsView?.getContent().getSections() as ExtensionsViewSection[]; - await driverHelper.waitAllPresence(webCheCodeLocators.ExtensionsViewSection.itemTitle, TimeoutConstants.TS_EDITOR_TAB_INTERACTION_TIMEOUT); - Logger.debug(`extensionSection.findItem(${extension.name}).`); - await extensionSection.findItem(extension.name); - } - - Logger.debug(`extensionsView?.getContent().getSections(): switch to marketplace section.`); - const [marketplaceSection]: ExtensionsViewSection[] = await extensionsView?.getContent().getSections() as ExtensionsViewSection[]; - await driverHelper.waitVisibility(webCheCodeLocators.ExtensionsViewSection.items, TimeoutConstants.TS_EDITOR_TAB_INTERACTION_TIMEOUT); - - Logger.debug(`marketplaceSection.getVisibleItems(): get all found items.`); - const allFinedItems: ExtensionsViewItem[] = await marketplaceSection.getVisibleItems(); - - let itemWithRightNameAndPublisher: ExtensionsViewItem | undefined; - for (const item of allFinedItems) { - Logger.debug(`Try to find extension published by ${extension.publisher}.`); - if (await item.getAuthor() === extension.publisher) { - itemWithRightNameAndPublisher = item; - Logger.debug(`Extension was found: ${await itemWithRightNameAndPublisher?.getTitle()}`); - break; - } - if (itemWithRightNameAndPublisher === undefined) { - Logger.error(`Extension with publisher as ${extension.publisher} was not found.`); - } - } - - Logger.debug(`itemWithRightNameAndPublisher?.isInstalled()`); - const isInstalled: boolean = await itemWithRightNameAndPublisher?.isInstalled() as boolean; - - Logger.debug(`itemWithRightNameAndPublisher?.isInstalled(): ${isInstalled}.`); - expect(isInstalled).eqls(true); - - Logger.debug(`itemWithRightNameAndPublisher.manage(): get context menu.`); - const extensionManageMenu: ContextMenu = await (itemWithRightNameAndPublisher as ExtensionsViewItem).manage(); - - Logger.debug(`extensionManageMenu.getItems(): get menu items.`); - const extensionMenuItems: ContextMenuItem[] = await extensionManageMenu.getItems(); - let extensionMenuItemLabels: string = ''; - for (const item of extensionMenuItems) { - Logger.trace(`extensionMenuItems -> item.getLabel(): get menu items names.`); - extensionMenuItemLabels += (await item.getLabel()) + ' '; - } - - Logger.debug(`extensionMenuItemLabels: ${extensionMenuItemLabels}.`); - expect(extensionMenuItemLabels).contains('Disable').and.not.contains('Enable'); - } - }); - - test('Stop the workspace', async function (): Promise { - await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - await browserTabsUtil.closeAllTabsExceptCurrent(); - }); - - test('Delete the workspace', async function (): Promise { - await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); - } - - loginTests.logoutFromChe(); + test('Registering the running workspace', async function(): Promise { + registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); + + test('Wait workspace readiness', async function(): Promise { + await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + }); + + test('Wait until the project will be imported and accept it as trusted one', async function(): Promise { + [projectSection] = await new SideBarView().getContent().getSections(); + const label: string = BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME; + Logger.debug(`projectSection.findItem: find ${label}`); + const isFileImported: ViewItem | undefined = await projectSection.findItem(label); + expect(isFileImported).not.eqls(undefined); + try { + const buttonYesITrustTheAuthors: string = `Yes, I trust the authors`; + await driverHelper.waitVisibility(webCheCodeLocators.WelcomeContent.button, TimeoutConstants.TS_DIALOG_WINDOW_DEFAULT_TIMEOUT); + const trustedProjectDialog: ModalDialog = new ModalDialog(); + Logger.debug(`trustedProjectDialog.pushButton: "${buttonYesITrustTheAuthors}"`); + await trustedProjectDialog.pushButton(buttonYesITrustTheAuthors); + } catch (e) { + Logger.debug(`Welcome modal dialog was not shown: ${e}`); + } + }); + + test(`Get recommended extensions list from ${extensionsListFileName}`, async function(): Promise { + Logger.debug(`projectSection.findItem(item))?.select(): expand .vscode folder and open extensions.json.`); + await (await projectSection.findItem('.vscode'))?.select(); + // time to expand project tree + await driverHelper.wait(TimeoutConstants.TS_EXPAND_PROJECT_TREE_ITEM_TIMEOUT); + await (await projectSection.findItem(extensionsListFileName))?.select(); + Logger.debug(`EditorView().openEditor(${extensionsListFileName})`); + const editor: TextEditor = await new EditorView().openEditor(extensionsListFileName) as TextEditor; + await driverHelper.waitVisibility(webCheCodeLocators.Editor.inputArea); + Logger.debug(`editor.getText(): get recommended extensions as text from editor, delete comments and parse to object.`); + recommendedExtensions = JSON.parse((await editor.getText()).replace(/\/\*[\s\S]*?\*\/|(?<=[^:])\/\/.*|^\/\/.*/g, '').trim()); + Logger.debug(`recommendedExtensions.recommendations: Get recommendations clear names using map().`); + recommendedExtensions.recommendations = recommendedExtensions.recommendations.map((r: { split: (arg: string) => [any, any]; }) => { + const [publisher, name] = r.split('.'); + return { publisher, name }; + }); + Logger.info(`Recommended extension for this workspace:\n${JSON.stringify(recommendedExtensions.recommendations)}.`); + }); + + test(`Open "Extensions" view section`, async function(): Promise { + Logger.debug(`ActivityBar().getViewControl('Extensions'))?.openView(): open Extensions view.`); + extensionsView = await (await new ActivityBar().getViewControl('Extensions'))?.openView(); + }); + + test(`Let extensions complete installation`, async function(): Promise { + Logger.info(`Time for extensions installation TimeoutConstants.TS_COMMON_PLUGIN_TEST_TIMEOUT=${TimeoutConstants.TS_COMMON_PLUGIN_TEST_TIMEOUT}`); + await driverHelper.wait(TimeoutConstants.TS_COMMON_PLUGIN_TEST_TIMEOUT); + }); + + test(`Check if extensions are installed and enabled`, async function(): Promise { + this.retries(10); + Logger.debug(`ActivityBar().getViewControl('Extensions'))?.openView(): open Extensions view.`); + extensionsView = await (await new ActivityBar().getViewControl('Extensions'))?.openView(); + + Logger.debug(`extensionsView?.getContent().getSections(): get current section.`); + [extensionSection] = await extensionsView?.getContent().getSections() as ExtensionsViewSection[]; + await driverHelper.waitAllPresence(webCheCodeLocators.ExtensionsViewSection.itemTitle, TimeoutConstants.TS_EDITOR_TAB_INTERACTION_TIMEOUT); + + for (const extension of recommendedExtensions.recommendations) { + Logger.info(`Check if ${JSON.stringify(extension)} are installed.`); + + Logger.debug(`extensionSection.findItem(${extension.name}).`); + await extensionSection.findItem(extension.name); + + // check if extension require reload the page + if (await driverHelper.isVisible((webCheCodeLocators.ExtensionsViewSection as any).requireReloadButton)) { + Logger.debug(`Extension require reload the editor. Refreshing the page..`); + await browserTabsUtil.refreshPage(); + await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + Logger.debug(`ActivityBar().getViewControl('Extensions'))?.openView(): open Extensions view.`); + extensionsView = await (await new ActivityBar().getViewControl('Extensions'))?.openView(); + Logger.debug(`extensionsView?.getContent().getSections(): get current section.`); + [extensionSection] = await extensionsView?.getContent().getSections() as ExtensionsViewSection[]; + await driverHelper.waitAllPresence(webCheCodeLocators.ExtensionsViewSection.itemTitle, TimeoutConstants.TS_EDITOR_TAB_INTERACTION_TIMEOUT); + Logger.debug(`extensionSection.findItem(${extension.name}).`); + await extensionSection.findItem(extension.name); + } + + Logger.debug(`extensionsView?.getContent().getSections(): switch to marketplace section.`); + const [marketplaceSection]: ExtensionsViewSection[] = await extensionsView?.getContent().getSections() as ExtensionsViewSection[]; + await driverHelper.waitVisibility(webCheCodeLocators.ExtensionsViewSection.items, TimeoutConstants.TS_EDITOR_TAB_INTERACTION_TIMEOUT); + + Logger.debug(`marketplaceSection.getVisibleItems(): get all found items.`); + const allFinedItems: ExtensionsViewItem[] = await marketplaceSection.getVisibleItems(); + + let itemWithRightNameAndPublisher: ExtensionsViewItem | undefined; + for (const item of allFinedItems) { + Logger.debug(`Try to find extension published by ${extension.publisher}.`); + if (await item.getAuthor() === extension.publisher) { + itemWithRightNameAndPublisher = item; + Logger.debug(`Extension was found: ${await itemWithRightNameAndPublisher?.getTitle()}`); + break; + } + if (itemWithRightNameAndPublisher === undefined) { + Logger.error(`Extension with publisher as ${extension.publisher} was not found.`); + } + } + + Logger.debug(`itemWithRightNameAndPublisher?.isInstalled()`); + const isInstalled: boolean = await itemWithRightNameAndPublisher?.isInstalled() as boolean; + + Logger.debug(`itemWithRightNameAndPublisher?.isInstalled(): ${isInstalled}.`); + expect(isInstalled).eqls(true); + + Logger.debug(`itemWithRightNameAndPublisher.manage(): get context menu.`); + const extensionManageMenu: ContextMenu = await (itemWithRightNameAndPublisher as ExtensionsViewItem).manage(); + + Logger.debug(`extensionManageMenu.getItems(): get menu items.`); + const extensionMenuItems: ContextMenuItem[] = await extensionManageMenu.getItems(); + let extensionMenuItemLabels: string = ''; + for (const item of extensionMenuItems) { + Logger.trace(`extensionMenuItems -> item.getLabel(): get menu items names.`); + extensionMenuItemLabels += (await item.getLabel()) + ' '; + } + + Logger.debug(`extensionMenuItemLabels: ${extensionMenuItemLabels}.`); + expect(extensionMenuItemLabels).contains('Disable').and.not.contains('Enable'); + } + }); + + test('Stop the workspace', async function(): Promise { + await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + await browserTabsUtil.closeAllTabsExceptCurrent(); + }); + + test('Delete the workspace', async function(): Promise { + await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); + } + + loginTests.logoutFromChe(); }); diff --git a/tests/e2e/specs/devconsole-intergration/DevConsoleIntegration.spec.ts b/tests/e2e/specs/devconsole-intergration/DevConsoleIntegration.spec.ts index 628e3c68fac..a6a4910aba0 100644 --- a/tests/e2e/specs/devconsole-intergration/DevConsoleIntegration.spec.ts +++ b/tests/e2e/specs/devconsole-intergration/DevConsoleIntegration.spec.ts @@ -8,11 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ -import { - SideBarView, - ViewItem, - ViewSection -} from 'monaco-page-objects'; +import { SideBarView, ViewItem, ViewSection } from 'monaco-page-objects'; import { registerRunningWorkspace } from '../MochaHooks'; import { LoginTests } from '../../tests-library/LoginTests'; import { e2eContainer } from '../../configs/inversify.config'; @@ -36,65 +32,65 @@ let ocpApplicationPage: OcpApplicationPage; const kubernetesCommandLineToolsExecutor: KubernetesCommandLineToolsExecutor = new KubernetesCommandLineToolsExecutor(); // works only with no-admin user -suite(`DevConsole Integration`, async function (): Promise { - // test specific data - const gitImportRepo: string = 'https://github.com/crw-qe/summit-lab-spring-music.git'; - const gitImportReference: string = 'pipeline'; - const projectLabel: string = 'app.openshift.io/runtime=spring'; - const projectName: string = 'devconsole-integration-test'; - - suiteSetup('Create new empty project using ocp', async function (): Promise { - kubernetesCommandLineToolsExecutor.loginToOcp(); - kubernetesCommandLineToolsExecutor.createProject(projectName); - }); - - loginTests.loginIntoOcpConsole(); - - test('Select test project and Developer role on DevConsole', async function (): Promise { - await ocpMainPage.selectDeveloperRole(); - await ocpMainPage.selectProject(projectName); - }); - - test('Open import from git project page', async function (): Promise { - ocpImportPage = await ocpMainPage.openImportFromGitPage(); - }); - - test('Fill and submit import data', async function (): Promise { - ocpApplicationPage = await ocpImportPage.fitAndSubmitConfiguration(gitImportRepo, gitImportReference, projectLabel); - }); - - test('Wait until application creates', async function (): Promise { - await ocpApplicationPage.waitApplicationIcon(); - }); - - test('Check if application has worked link "Open Source Code"', async function (): Promise { - await ocpApplicationPage.waitAndOpenEditSourceCodeIcon(); - }); - - loginTests.loginIntoChe(); - - test('Obtain workspace name from workspace loader page', async function (): Promise { - await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); - }); - - test('Registering the running workspace', async function (): Promise { - registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); - - test('Check if application source code opens in workspace', async function (): Promise { - await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); - }); - - test('Check if project and files imported', async function (): Promise { - const applicationSourceProjectName: string = StringUtil.getProjectNameFromGitUrl(gitImportRepo); - const projectSection: ViewSection = await new SideBarView().getContent().getSection(applicationSourceProjectName); - const isFileImported: ViewItem | undefined = await projectSection.findItem(BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME); - expect(isFileImported).not.eqls(undefined); - }); - - loginTests.logoutFromChe(); - - suiteTeardown('Delete project using ocp', async function (): Promise { - kubernetesCommandLineToolsExecutor.deleteProject(projectName); - }); +suite(`DevConsole Integration`, async function(): Promise { + // test specific data + const gitImportRepo: string = 'https://github.com/crw-qe/summit-lab-spring-music.git'; + const gitImportReference: string = 'pipeline'; + const projectLabel: string = 'app.openshift.io/runtime=spring'; + const projectName: string = 'devconsole-integration-test'; + + suiteSetup('Create new empty project using ocp', async function(): Promise { + kubernetesCommandLineToolsExecutor.loginToOcp(); + kubernetesCommandLineToolsExecutor.createProject(projectName); + }); + + loginTests.loginIntoOcpConsole(); + + test('Select test project and Developer role on DevConsole', async function(): Promise { + await ocpMainPage.selectDeveloperRole(); + await ocpMainPage.selectProject(projectName); + }); + + test('Open import from git project page', async function(): Promise { + ocpImportPage = await ocpMainPage.openImportFromGitPage(); + }); + + test('Fill and submit import data', async function(): Promise { + ocpApplicationPage = await ocpImportPage.fitAndSubmitConfiguration(gitImportRepo, gitImportReference, projectLabel); + }); + + test('Wait until application creates', async function(): Promise { + await ocpApplicationPage.waitApplicationIcon(); + }); + + test('Check if application has worked link "Open Source Code"', async function(): Promise { + await ocpApplicationPage.waitAndOpenEditSourceCodeIcon(); + }); + + loginTests.loginIntoChe(); + + test('Obtain workspace name from workspace loader page', async function(): Promise { + await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); + }); + + test('Registering the running workspace', async function(): Promise { + registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); + + test('Check if application source code opens in workspace', async function(): Promise { + await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + }); + + test('Check if project and files imported', async function(): Promise { + const applicationSourceProjectName: string = StringUtil.getProjectNameFromGitUrl(gitImportRepo); + const projectSection: ViewSection = await new SideBarView().getContent().getSection(applicationSourceProjectName); + const isFileImported: ViewItem | undefined = await projectSection.findItem(BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME); + expect(isFileImported).not.eqls(undefined); + }); + + loginTests.logoutFromChe(); + + suiteTeardown('Delete project using ocp', async function(): Promise { + kubernetesCommandLineToolsExecutor.deleteProject(projectName); + }); }); diff --git a/tests/e2e/specs/factory/Factory.spec.ts b/tests/e2e/specs/factory/Factory.spec.ts index 8237666a75d..f58dd35a3b4 100644 --- a/tests/e2e/specs/factory/Factory.spec.ts +++ b/tests/e2e/specs/factory/Factory.spec.ts @@ -49,154 +49,154 @@ const loginTests: LoginTests = e2eContainer.get(CLASSES.LoginTests); const webCheCodeLocators: Locators = new CheCodeLocatorLoader().webCheCodeLocators; -suite(`Create a workspace via launching a factory from the ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} repository`, async function (): Promise { - const oauthPage: OauthPage = new OauthPage(driverHelper); - - let projectSection: ViewSection; - let scmProvider: SingleScmProvider; - let rest: SingleScmProvider[]; - let scmContextMenu: ContextMenu; - - // test specific data - const timeToRefresh: number = 1500; - const changesToCommit: string = (new Date()).getTime().toString(); - const fileToChange: string = 'Date.txt'; - const commitChangesButtonLabel: string = `Commit Changes on "${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}"`; - const refreshButtonLabel: string = 'Refresh'; - const pushItemLabel: string = 'Push'; - let testRepoProjectName: string; - - loginTests.loginIntoChe(); - test(`Navigate to the factory URL`, async function (): Promise { - await browserTabsUtil.navigateTo(FactoryTestConstants.TS_SELENIUM_FACTORY_URL()); - }); - - if (OAuthConstants.TS_SELENIUM_GIT_PROVIDER_OAUTH) { - test(`Authorize with a ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} OAuth`, async function (): Promise { - await oauthPage.login(); - await oauthPage.waitOauthPage(); - await oauthPage.confirmAccess(); - }); - } - - test('Obtain workspace name from workspace loader page', async function (): Promise { - await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); - }); - - test('Registering the running workspace', async function (): Promise { - registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); - - test('Wait the workspace readiness', async function (): Promise { - await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); - }); - - test('Check if a project folder has been created', async function (): Promise { - testRepoProjectName = StringUtil.getProjectNameFromGitUrl(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_URL); - Logger.debug(`new SideBarView().getContent().getSection: get ${testRepoProjectName}`); - projectSection = await new SideBarView().getContent().getSection(testRepoProjectName); - }); - - test('Check if the project files were imported', async function (): Promise { - const label: string = BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME; - Logger.debug(`projectSection.findItem: find ${label}`); - const isFileImported: ViewItem | undefined = await projectSection.findItem(label); - expect(isFileImported).not.eqls(undefined); - }); - - test('Accept the project as a trusted one', async function (): Promise { - const buttonYesITrustTheAuthors: string = `Yes, I trust the authors`; - const trustedProjectDialog: ModalDialog = new ModalDialog(); - await driverHelper.waitVisibility(webCheCodeLocators.WelcomeContent.button); - Logger.debug(`trustedProjectDialog.pushButton: "${buttonYesITrustTheAuthors}"`); - await trustedProjectDialog.pushButton(buttonYesITrustTheAuthors); - }); - - test('Make changes to the file', async function (): Promise { - Logger.debug(`projectSection.openItem: "${fileToChange}"`); - await projectSection.openItem(fileToChange); - const editor: TextEditor = await new EditorView().openEditor(fileToChange) as TextEditor; - await driverHelper.waitVisibility(webCheCodeLocators.Editor.inputArea); - Logger.debug(`editor.clearText`); - await editor.clearText(); - Logger.debug(`editor.typeTextAt: "${changesToCommit}"`); - await editor.typeTextAt(1, 1, changesToCommit); - }); - - test('Open a source control manager', async function (): Promise { - const viewSourceControl: string = `Source Control`; - const sourceControl: ViewControl = await new ActivityBar().getViewControl(viewSourceControl) as ViewControl; - Logger.debug(`sourceControl.openView: "${viewSourceControl}"`); - await sourceControl.openView(); - const scmView: NewScmView = new NewScmView(); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); - [scmProvider, ...rest] = await scmView.getProviders(); - Logger.debug(`scmView.getProviders: "${scmProvider}, ${scmProvider}"`); - }); - - test('Check if the changes are displayed in the source control manager', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - await driverHelper.wait(timeToRefresh); - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - // wait while changes counter will be refreshed - await driverHelper.wait(timeToRefresh); - const changes: number = await scmProvider.getChangeCount(); - Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); - expect(changes).eql(1); - }); - - test('Stage the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - Logger.debug(`scmProvider.openMoreActions`); - scmContextMenu = await scmProvider.openMoreActions(); - await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.contextView); - Logger.debug(`scmContextMenu.select: "Changes" -> "Stage All Changes"`); - await scmContextMenu.select('Changes', 'Stage All Changes'); - }); - - test('Commit the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); - Logger.debug(`scmProvider.commitChanges: commit name "Commit ${changesToCommit}"`); - await scmProvider.commitChanges('Commit ' + changesToCommit); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - await driverHelper.wait(timeToRefresh); - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - // wait while changes counter will be refreshed - await driverHelper.wait(timeToRefresh); - const changes: number = await scmProvider.getChangeCount(); - Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); - expect(changes).eql(0); - }); - - test('Push the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(`Push 1 commits to origin/${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}`)); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - Logger.debug(`scmProvider.openMoreActions`); - scmContextMenu = await scmProvider.openMoreActions(); - await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.itemConstructor(pushItemLabel)); - Logger.debug(`scmContextMenu.select: "${pushItemLabel}"`); - await scmContextMenu.select(pushItemLabel); - }); - - test('Check if the changes were pushed', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - await driverHelper.wait(timeToRefresh); - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - const isCommitButtonDisabled: string = await driverHelper.waitAndGetElementAttribute(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel), 'aria-disabled'); - expect(isCommitButtonDisabled).eql('true'); - }); - - test('Stop the workspace', async function (): Promise { - await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - await browserTabsUtil.closeAllTabsExceptCurrent(); - }); - - test('Delete the workspace', async function (): Promise { - await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); - - loginTests.logoutFromChe(); +suite(`Create a workspace via launching a factory from the ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} repository`, async function(): Promise { + const oauthPage: OauthPage = new OauthPage(driverHelper); + + let projectSection: ViewSection; + let scmProvider: SingleScmProvider; + let rest: SingleScmProvider[]; + let scmContextMenu: ContextMenu; + + // test specific data + const timeToRefresh: number = 1500; + const changesToCommit: string = (new Date()).getTime().toString(); + const fileToChange: string = 'Date.txt'; + const commitChangesButtonLabel: string = `Commit Changes on "${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}"`; + const refreshButtonLabel: string = 'Refresh'; + const pushItemLabel: string = 'Push'; + let testRepoProjectName: string; + + loginTests.loginIntoChe(); + test(`Navigate to the factory URL`, async function(): Promise { + await browserTabsUtil.navigateTo(FactoryTestConstants.TS_SELENIUM_FACTORY_URL()); + }); + + if (OAuthConstants.TS_SELENIUM_GIT_PROVIDER_OAUTH) { + test(`Authorize with a ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} OAuth`, async function(): Promise { + await oauthPage.login(); + await oauthPage.waitOauthPage(); + await oauthPage.confirmAccess(); + }); + } + + test('Obtain workspace name from workspace loader page', async function(): Promise { + await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); + }); + + test('Registering the running workspace', async function(): Promise { + registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); + + test('Wait the workspace readiness', async function(): Promise { + await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + }); + + test('Check if a project folder has been created', async function(): Promise { + testRepoProjectName = StringUtil.getProjectNameFromGitUrl(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_URL); + Logger.debug(`new SideBarView().getContent().getSection: get ${testRepoProjectName}`); + projectSection = await new SideBarView().getContent().getSection(testRepoProjectName); + }); + + test('Check if the project files were imported', async function(): Promise { + const label: string = BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME; + Logger.debug(`projectSection.findItem: find ${label}`); + const isFileImported: ViewItem | undefined = await projectSection.findItem(label); + expect(isFileImported).not.eqls(undefined); + }); + + test('Accept the project as a trusted one', async function(): Promise { + const buttonYesITrustTheAuthors: string = `Yes, I trust the authors`; + const trustedProjectDialog: ModalDialog = new ModalDialog(); + await driverHelper.waitVisibility(webCheCodeLocators.WelcomeContent.button); + Logger.debug(`trustedProjectDialog.pushButton: "${buttonYesITrustTheAuthors}"`); + await trustedProjectDialog.pushButton(buttonYesITrustTheAuthors); + }); + + test('Make changes to the file', async function(): Promise { + Logger.debug(`projectSection.openItem: "${fileToChange}"`); + await projectSection.openItem(fileToChange); + const editor: TextEditor = await new EditorView().openEditor(fileToChange) as TextEditor; + await driverHelper.waitVisibility(webCheCodeLocators.Editor.inputArea); + Logger.debug(`editor.clearText`); + await editor.clearText(); + Logger.debug(`editor.typeTextAt: "${changesToCommit}"`); + await editor.typeTextAt(1, 1, changesToCommit); + }); + + test('Open a source control manager', async function(): Promise { + const viewSourceControl: string = `Source Control`; + const sourceControl: ViewControl = await new ActivityBar().getViewControl(viewSourceControl) as ViewControl; + Logger.debug(`sourceControl.openView: "${viewSourceControl}"`); + await sourceControl.openView(); + const scmView: NewScmView = new NewScmView(); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); + [scmProvider, ...rest] = await scmView.getProviders(); + Logger.debug(`scmView.getProviders: "${scmProvider}, ${scmProvider}"`); + }); + + test('Check if the changes are displayed in the source control manager', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + await driverHelper.wait(timeToRefresh); + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + // wait while changes counter will be refreshed + await driverHelper.wait(timeToRefresh); + const changes: number = await scmProvider.getChangeCount(); + Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); + expect(changes).eql(1); + }); + + test('Stage the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + Logger.debug(`scmProvider.openMoreActions`); + scmContextMenu = await scmProvider.openMoreActions(); + await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.contextView); + Logger.debug(`scmContextMenu.select: "Changes" -> "Stage All Changes"`); + await scmContextMenu.select('Changes', 'Stage All Changes'); + }); + + test('Commit the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); + Logger.debug(`scmProvider.commitChanges: commit name "Commit ${changesToCommit}"`); + await scmProvider.commitChanges('Commit ' + changesToCommit); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + await driverHelper.wait(timeToRefresh); + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + // wait while changes counter will be refreshed + await driverHelper.wait(timeToRefresh); + const changes: number = await scmProvider.getChangeCount(); + Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); + expect(changes).eql(0); + }); + + test('Push the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(`Push 1 commits to origin/${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}`)); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + Logger.debug(`scmProvider.openMoreActions`); + scmContextMenu = await scmProvider.openMoreActions(); + await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.itemConstructor(pushItemLabel)); + Logger.debug(`scmContextMenu.select: "${pushItemLabel}"`); + await scmContextMenu.select(pushItemLabel); + }); + + test('Check if the changes were pushed', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + await driverHelper.wait(timeToRefresh); + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + const isCommitButtonDisabled: string = await driverHelper.waitAndGetElementAttribute(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel), 'aria-disabled'); + expect(isCommitButtonDisabled).eql('true'); + }); + + test('Stop the workspace', async function(): Promise { + await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + await browserTabsUtil.closeAllTabsExceptCurrent(); + }); + + test('Delete the workspace', async function(): Promise { + await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); + + loginTests.logoutFromChe(); }); diff --git a/tests/e2e/specs/factory/NoSetupRepoFactory.spec.ts b/tests/e2e/specs/factory/NoSetupRepoFactory.spec.ts index 005066230be..b4b71cd2243 100644 --- a/tests/e2e/specs/factory/NoSetupRepoFactory.spec.ts +++ b/tests/e2e/specs/factory/NoSetupRepoFactory.spec.ts @@ -29,7 +29,6 @@ import { import { expect } from 'chai'; import { StringUtil } from '../../utils/StringUtil'; import { CheCodeLocatorLoader } from '../../pageobjects/ide/CheCodeLocatorLoader'; -import WebDriverError = error.WebDriverError; import { registerRunningWorkspace } from '../MochaHooks'; import { BrowserTabsUtil } from '../../utils/BrowserTabsUtil'; import { CLASSES } from '../../configs/inversify.types'; @@ -44,6 +43,7 @@ import { LoginTests } from '../../tests-library/LoginTests'; import { FactoryTestConstants, GitProviderType } from '../../constants/FactoryTestConstants'; import { OAuthConstants } from '../../constants/OAuthConstants'; import { BaseTestConstants } from '../../constants/BaseTestConstants'; +import WebDriverError = error.WebDriverError; const browserTabsUtil: BrowserTabsUtil = e2eContainer.get(CLASSES.BrowserTabsUtil); const workspaceHandlingTests: WorkspaceHandlingTests = e2eContainer.get(CLASSES.WorkspaceHandlingTests); @@ -54,219 +54,219 @@ const dashboard: Dashboard = e2eContainer.get(CLASSES.Dashboard); const workspaces: Workspaces = e2eContainer.get(CLASSES.Workspaces); const loginTests: LoginTests = e2eContainer.get(CLASSES.LoginTests); -suite(`Create a workspace via launching a factory from the ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} repository without OAuth setup`, async function (): Promise { +suite(`Create a workspace via launching a factory from the ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} repository without OAuth setup`, async function(): Promise { - let projectSection: ViewSection; - let scmProvider: SingleScmProvider; - let rest: SingleScmProvider[]; - let scmContextMenu: ContextMenu; + let projectSection: ViewSection; + let scmProvider: SingleScmProvider; + let rest: SingleScmProvider[]; + let scmContextMenu: ContextMenu; - // test specific data - let numberOfCreatedWorkspaces: number = 0; - const timeToRefresh: number = 1500; - const changesToCommit: string = (new Date()).getTime().toString(); - const fileToChange: string = 'Date.txt'; - const pushItemLabel: string = 'Push'; - const commitChangesButtonLabel: string = `Commit Changes on "${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}"`; - const refreshButtonLabel: string = 'Refresh'; - const label: string = BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME; - let testRepoProjectName: string; - const isPrivateRepo: string = FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO ? 'private' : 'public'; + // test specific data + let numberOfCreatedWorkspaces: number = 0; + const timeToRefresh: number = 1500; + const changesToCommit: string = (new Date()).getTime().toString(); + const fileToChange: string = 'Date.txt'; + const pushItemLabel: string = 'Push'; + const commitChangesButtonLabel: string = `Commit Changes on "${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}"`; + const refreshButtonLabel: string = 'Refresh'; + const label: string = BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME; + let testRepoProjectName: string; + const isPrivateRepo: string = FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO ? 'private' : 'public'; - loginTests.loginIntoChe(); + loginTests.loginIntoChe(); - test('Get number of previously created workspaces', async function (): Promise { - await dashboard.clickWorkspacesButton(); - await workspaces.waitPage(); - numberOfCreatedWorkspaces = (await workspaces.getAllCreatedWorkspacesNames()).length; - }); + test('Get number of previously created workspaces', async function(): Promise { + await dashboard.clickWorkspacesButton(); + await workspaces.waitPage(); + numberOfCreatedWorkspaces = (await workspaces.getAllCreatedWorkspacesNames()).length; + }); - test(`Navigate to the ${isPrivateRepo} repository factory URL`, async function (): Promise { - await browserTabsUtil.navigateTo(FactoryTestConstants.TS_SELENIUM_FACTORY_URL()); - }); + test(`Navigate to the ${isPrivateRepo} repository factory URL`, async function(): Promise { + await browserTabsUtil.navigateTo(FactoryTestConstants.TS_SELENIUM_FACTORY_URL()); + }); - if (FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO) { + if (FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO) { - test(`Check that workspace cannot be created without OAuth for ${isPrivateRepo} repo`, async function (): Promise { - await dashboard.waitLoader(); - const loaderAlert: string = await dashboard.getLoaderAlert(); - expect(loaderAlert).contains.oneOf(['Cause: Unsupported OAuth provider', 'Cause: No PersonalAccessTokenFetcher configured']); - }); + test(`Check that workspace cannot be created without OAuth for ${isPrivateRepo} repo`, async function(): Promise { + await dashboard.waitLoader(); + const loaderAlert: string = await dashboard.getLoaderAlert(); + expect(loaderAlert).contains.oneOf(['Cause: Unsupported OAuth provider', 'Cause: No PersonalAccessTokenFetcher configured']); + }); - test(`Check that workspace was not created`, async function (): Promise { - await dashboard.openDashboard(); - await dashboard.clickWorkspacesButton(); - await workspaces.waitPage(); - const allCreatedWorkspacesNames: string[] = await workspaces.getAllCreatedWorkspacesNames(); - expect(allCreatedWorkspacesNames).has.length(numberOfCreatedWorkspaces); - }); + test(`Check that workspace was not created`, async function(): Promise { + await dashboard.openDashboard(); + await dashboard.clickWorkspacesButton(); + await workspaces.waitPage(); + const allCreatedWorkspacesNames: string[] = await workspaces.getAllCreatedWorkspacesNames(); + expect(allCreatedWorkspacesNames).has.length(numberOfCreatedWorkspaces); + }); - loginTests.logoutFromChe(); + loginTests.logoutFromChe(); - } else { - test('Obtain workspace name from workspace loader page', async function (): Promise { - await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); + } else { + test('Obtain workspace name from workspace loader page', async function(): Promise { + await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); }); - test('Registering the running workspace', async function (): Promise { - registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); + test('Registering the running workspace', async function(): Promise { + registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); - test('Wait the workspace readiness', async function (): Promise { - await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); - }); + test('Wait the workspace readiness', async function(): Promise { + await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + }); - test('Check if a project folder has been created', async function (): Promise { - testRepoProjectName = StringUtil.getProjectNameFromGitUrl(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_URL); - Logger.debug(`new SideBarView().getContent().getSection: get ${testRepoProjectName}`); - projectSection = await new SideBarView().getContent().getSection(testRepoProjectName); - }); + test('Check if a project folder has been created', async function(): Promise { + testRepoProjectName = StringUtil.getProjectNameFromGitUrl(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_URL); + Logger.debug(`new SideBarView().getContent().getSection: get ${testRepoProjectName}`); + projectSection = await new SideBarView().getContent().getSection(testRepoProjectName); + }); - test('Accept the project as a trusted one', async function (): Promise { - // click somewhere to trigger "Welcome Content" dialog - try { - await driverHelper.waitAndClick(webCheCodeLocators.Workbench.notificationItem); - } catch (e) { - Logger.info(`Click on ${webCheCodeLocators.Workbench.notificationItem} to get "Welcome Content" dialog ${e as string}`); - } - // "Welcome Content" dialog can be shown before of after dialog with an error for private repo - try { - const buttonYesITrustTheAuthors: string = `Yes, I trust the authors`; - await driverHelper.waitVisibility(webCheCodeLocators.WelcomeContent.text, TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM); - const welcomeContentDialog: ModalDialog = new ModalDialog(); - Logger.debug(`trustedProjectDialog.pushButton: "${buttonYesITrustTheAuthors}"`); - await welcomeContentDialog.pushButton(buttonYesITrustTheAuthors); - await driverHelper.waitDisappearance(webCheCodeLocators.WelcomeContent.text); - } catch (e) { - Logger.info(`"Accept the project as a trusted one" dialog was not shown firstly for "${isPrivateRepo}"`); - if (!FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO) { - throw new WebDriverError(e as string); - } - } - }); + test('Accept the project as a trusted one', async function(): Promise { + // click somewhere to trigger "Welcome Content" dialog + try { + await driverHelper.waitAndClick(webCheCodeLocators.Workbench.notificationItem); + } catch (e) { + Logger.info(`Click on ${webCheCodeLocators.Workbench.notificationItem} to get "Welcome Content" dialog ${e as string}`); + } + // "Welcome Content" dialog can be shown before of after dialog with an error for private repo + try { + const buttonYesITrustTheAuthors: string = `Yes, I trust the authors`; + await driverHelper.waitVisibility(webCheCodeLocators.WelcomeContent.text, TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM); + const welcomeContentDialog: ModalDialog = new ModalDialog(); + Logger.debug(`trustedProjectDialog.pushButton: "${buttonYesITrustTheAuthors}"`); + await welcomeContentDialog.pushButton(buttonYesITrustTheAuthors); + await driverHelper.waitDisappearance(webCheCodeLocators.WelcomeContent.text); + } catch (e) { + Logger.info(`"Accept the project as a trusted one" dialog was not shown firstly for "${isPrivateRepo}"`); + if (!FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO) { + throw new WebDriverError(e as string); + } + } + }); - test('Check if the project files were imported', async function (): Promise { - Logger.debug(`projectSection.findItem: find ${label}`); - const isFileImported: ViewItem | undefined = await projectSection.findItem(label); - // projectSection.findItem(label) can return undefined but test will goes on - expect(isFileImported).not.eqls(undefined); - }); + test('Check if the project files were imported', async function(): Promise { + Logger.debug(`projectSection.findItem: find ${label}`); + const isFileImported: ViewItem | undefined = await projectSection.findItem(label); + // projectSection.findItem(label) can return undefined but test will goes on + expect(isFileImported).not.eqls(undefined); + }); - test('Make changes to the file', async function (): Promise { - Logger.debug(`projectSection.openItem: "${fileToChange}"`); - await projectSection.openItem(fileToChange); - const editor: TextEditor = await new EditorView().openEditor(fileToChange) as TextEditor; - await driverHelper.waitVisibility(webCheCodeLocators.Editor.inputArea); - Logger.debug(`editor.clearText`); - await editor.clearText(); - Logger.debug(`editor.typeTextAt: "${changesToCommit}"`); - await editor.typeTextAt(1, 1, changesToCommit); - }); + test('Make changes to the file', async function(): Promise { + Logger.debug(`projectSection.openItem: "${fileToChange}"`); + await projectSection.openItem(fileToChange); + const editor: TextEditor = await new EditorView().openEditor(fileToChange) as TextEditor; + await driverHelper.waitVisibility(webCheCodeLocators.Editor.inputArea); + Logger.debug(`editor.clearText`); + await editor.clearText(); + Logger.debug(`editor.typeTextAt: "${changesToCommit}"`); + await editor.typeTextAt(1, 1, changesToCommit); + }); - test('Open a source control manager', async function (): Promise { - const viewSourceControl: string = `Source Control`; - const sourceControl: ViewControl = await new ActivityBar().getViewControl(viewSourceControl) as ViewControl; - Logger.debug(`sourceControl.openView: "${viewSourceControl}"`); - await sourceControl.openView(); - const scmView: NewScmView = new NewScmView(); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); - [scmProvider, ...rest] = await scmView.getProviders(); - Logger.debug(`scmView.getProviders: "${scmProvider}, ${scmProvider}"`); - }); + test('Open a source control manager', async function(): Promise { + const viewSourceControl: string = `Source Control`; + const sourceControl: ViewControl = await new ActivityBar().getViewControl(viewSourceControl) as ViewControl; + Logger.debug(`sourceControl.openView: "${viewSourceControl}"`); + await sourceControl.openView(); + const scmView: NewScmView = new NewScmView(); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); + [scmProvider, ...rest] = await scmView.getProviders(); + Logger.debug(`scmView.getProviders: "${scmProvider}, ${scmProvider}"`); + }); - test('Check if the changes are displayed in the source control manager', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - await driverHelper.wait(timeToRefresh); - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - // wait while changes counter will be refreshed - await driverHelper.wait(timeToRefresh); - const changes: number = await scmProvider.getChangeCount(); - Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); - expect(changes).eql(1); - }); + test('Check if the changes are displayed in the source control manager', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + await driverHelper.wait(timeToRefresh); + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + // wait while changes counter will be refreshed + await driverHelper.wait(timeToRefresh); + const changes: number = await scmProvider.getChangeCount(); + Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); + expect(changes).eql(1); + }); - test('Stage the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - Logger.debug(`scmProvider.openMoreActions`); - scmContextMenu = await scmProvider.openMoreActions(); - await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.contextView); - Logger.debug(`scmContextMenu.select: "Changes" -> "Stage All Changes"`); - await scmContextMenu.select('Changes', 'Stage All Changes'); - }); + test('Stage the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + Logger.debug(`scmProvider.openMoreActions`); + scmContextMenu = await scmProvider.openMoreActions(); + await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.contextView); + Logger.debug(`scmContextMenu.select: "Changes" -> "Stage All Changes"`); + await scmContextMenu.select('Changes', 'Stage All Changes'); + }); - test('Commit the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); - Logger.debug(`scmProvider.commitChanges: commit name "Commit ${changesToCommit}"`); - await scmProvider.commitChanges('Commit ' + changesToCommit); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - await driverHelper.wait(timeToRefresh); - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - // wait while changes counter will be refreshed - await driverHelper.wait(timeToRefresh); - const changes: number = await scmProvider.getChangeCount(); - Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); - expect(changes).eql(0); - }); + test('Commit the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); + Logger.debug(`scmProvider.commitChanges: commit name "Commit ${changesToCommit}"`); + await scmProvider.commitChanges('Commit ' + changesToCommit); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + await driverHelper.wait(timeToRefresh); + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + // wait while changes counter will be refreshed + await driverHelper.wait(timeToRefresh); + const changes: number = await scmProvider.getChangeCount(); + Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); + expect(changes).eql(0); + }); - test('Push the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(`Push 1 commits to origin/${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}`)); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - Logger.debug(`scmProvider.openMoreActions`); - scmContextMenu = await scmProvider.openMoreActions(); - await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.itemConstructor(pushItemLabel)); - Logger.debug(`scmContextMenu.select: "${pushItemLabel}"`); - await scmContextMenu.select(pushItemLabel); - }); + test('Push the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(`Push 1 commits to origin/${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}`)); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + Logger.debug(`scmProvider.openMoreActions`); + scmContextMenu = await scmProvider.openMoreActions(); + await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.itemConstructor(pushItemLabel)); + Logger.debug(`scmContextMenu.select: "${pushItemLabel}"`); + await scmContextMenu.select(pushItemLabel); + }); - if (FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER === GitProviderType.GITHUB) { - test('Decline GitHub Extension', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.Dialog.details); - const gitHaExtensionDialog: ModalDialog = new ModalDialog(); - await gitHaExtensionDialog.pushButton('Cancel'); - }); - } + if (FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER === GitProviderType.GITHUB) { + test('Decline GitHub Extension', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.Dialog.details); + const gitHaExtensionDialog: ModalDialog = new ModalDialog(); + await gitHaExtensionDialog.pushButton('Cancel'); + }); + } - test('Insert git credentials which were asked after push', async function (): Promise { - try { - await driverHelper.waitVisibility(webCheCodeLocators.InputBox.message); - } catch (e) { - Logger.info(`Workspace did not ask credentials before push - ${e}; + test('Insert git credentials which were asked after push', async function(): Promise { + try { + await driverHelper.waitVisibility(webCheCodeLocators.InputBox.message); + } catch (e) { + Logger.info(`Workspace did not ask credentials before push - ${e}; Known issue for github.com - https://issues.redhat.com/browse/CRW-4066, please check if not other git provider. `); - expect(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER).eqls(GitProviderType.GITHUB); - } - const input: InputBox = new InputBox(); - await input.setText(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_USERNAME); - await input.confirm(); - await driverHelper.wait(timeToRefresh); - await input.setText(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_PASSWORD); - await input.confirm(); - await driverHelper.wait(timeToRefresh); - }); + expect(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER).eqls(GitProviderType.GITHUB); + } + const input: InputBox = new InputBox(); + await input.setText(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_USERNAME); + await input.confirm(); + await driverHelper.wait(timeToRefresh); + await input.setText(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_PASSWORD); + await input.confirm(); + await driverHelper.wait(timeToRefresh); + }); - test('Check if the changes were pushed', async function (): Promise { - try { - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - } catch (e) { - Logger.info('Check you use correct credentials.' + - 'For bitbucket.org ensure you use an app password: https://support.atlassian.com/bitbucket-cloud/docs/using-app-passwords/;' + - 'For github.com - personal access token instead of password.'); - } - const isCommitButtonDisabled: string = await driverHelper.waitAndGetElementAttribute(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel), 'aria-disabled'); - expect(isCommitButtonDisabled).eql('true'); - }); + test('Check if the changes were pushed', async function(): Promise { + try { + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + } catch (e) { + Logger.info('Check you use correct credentials.' + + 'For bitbucket.org ensure you use an app password: https://support.atlassian.com/bitbucket-cloud/docs/using-app-passwords/;' + + 'For github.com - personal access token instead of password.'); + } + const isCommitButtonDisabled: string = await driverHelper.waitAndGetElementAttribute(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel), 'aria-disabled'); + expect(isCommitButtonDisabled).eql('true'); + }); - test('Stop the workspace', async function (): Promise { - await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - await browserTabsUtil.closeAllTabsExceptCurrent(); - }); + test('Stop the workspace', async function(): Promise { + await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + await browserTabsUtil.closeAllTabsExceptCurrent(); + }); - test('Delete the workspace', async function (): Promise { - await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - }); + test('Delete the workspace', async function(): Promise { + await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); - loginTests.logoutFromChe(); - } + loginTests.logoutFromChe(); + } }); diff --git a/tests/e2e/specs/factory/RefusedOAuthFactory.spec.ts b/tests/e2e/specs/factory/RefusedOAuthFactory.spec.ts index d8d6babb3b9..43d66c238cc 100644 --- a/tests/e2e/specs/factory/RefusedOAuthFactory.spec.ts +++ b/tests/e2e/specs/factory/RefusedOAuthFactory.spec.ts @@ -27,7 +27,6 @@ import { ViewSection } from 'monaco-page-objects'; import { expect } from 'chai'; -import WebDriverError = error.WebDriverError; import { registerRunningWorkspace } from '../MochaHooks'; import { BrowserTabsUtil } from '../../utils/BrowserTabsUtil'; import { CLASSES } from '../../configs/inversify.types'; @@ -43,6 +42,7 @@ import { LoginTests } from '../../tests-library/LoginTests'; import { OAuthConstants } from '../../constants/OAuthConstants'; import { BaseTestConstants } from '../../constants/BaseTestConstants'; import { FactoryTestConstants, GitProviderType } from '../../constants/FactoryTestConstants'; +import WebDriverError = error.WebDriverError; const browserTabsUtil: BrowserTabsUtil = e2eContainer.get(CLASSES.BrowserTabsUtil); const workspaceHandlingTests: WorkspaceHandlingTests = e2eContainer.get(CLASSES.WorkspaceHandlingTests); @@ -51,212 +51,212 @@ const webCheCodeLocators: Locators = new CheCodeLocatorLoader().webCheCodeLocato const driverHelper: DriverHelper = e2eContainer.get(CLASSES.DriverHelper); const loginTests: LoginTests = e2eContainer.get(CLASSES.LoginTests); -suite(`Create a workspace via launching a factory from the ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} repository and deny the access`, async function (): Promise { - const oauthPage: OauthPage = new OauthPage(driverHelper); +suite(`Create a workspace via launching a factory from the ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} repository and deny the access`, async function(): Promise { + const oauthPage: OauthPage = new OauthPage(driverHelper); + + let projectSection: ViewSection; + let scmProvider: SingleScmProvider; + let rest: SingleScmProvider[]; + let scmContextMenu: ContextMenu; - let projectSection: ViewSection; - let scmProvider: SingleScmProvider; - let rest: SingleScmProvider[]; - let scmContextMenu: ContextMenu; + // test specific data + const timeToRefresh: number = 1500; + const changesToCommit: string = (new Date()).getTime().toString(); + const fileToChange: string = 'Date.txt'; + const commitChangesButtonLabel: string = `Commit Changes on "${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}"`; + const refreshButtonLabel: string = 'Refresh'; + const pushItemLabel: string = 'Push'; + const label: string = BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME; + let testRepoProjectName: string; + const isPrivateRepo: string = FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO ? 'private' : 'public'; - // test specific data - const timeToRefresh: number = 1500; - const changesToCommit: string = (new Date()).getTime().toString(); - const fileToChange: string = 'Date.txt'; - const commitChangesButtonLabel: string = `Commit Changes on "${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}"`; - const refreshButtonLabel: string = 'Refresh'; - const pushItemLabel: string = 'Push'; - const label: string = BaseTestConstants.TS_SELENIUM_PROJECT_ROOT_FILE_NAME; - let testRepoProjectName: string; - const isPrivateRepo: string = FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO ? 'private' : 'public'; + loginTests.loginIntoChe(); - loginTests.loginIntoChe(); + test(`Navigate to the ${isPrivateRepo} repository factory URL`, async function(): Promise { + await browserTabsUtil.navigateTo(FactoryTestConstants.TS_SELENIUM_FACTORY_URL()); + }); - test(`Navigate to the ${isPrivateRepo} repository factory URL`, async function (): Promise { - await browserTabsUtil.navigateTo(FactoryTestConstants.TS_SELENIUM_FACTORY_URL()); + if (OAuthConstants.TS_SELENIUM_GIT_PROVIDER_OAUTH) { + test(`Authorize with a ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} OAuth and deny access`, async function(): Promise { + await oauthPage.login(); + await oauthPage.waitOauthPage(); + await oauthPage.denyAccess(); }); + } + + test('Obtain workspace name from workspace loader page', async function(): Promise { + await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); + }); + + test('The workspace starts with access deny flag in the url', async function(): Promise { + expect(await driverHelper.getDriver().getCurrentUrl()).contains('&error_code=access_denied'); + }); + + test('Registering the running workspace', async function(): Promise { + registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); - if (OAuthConstants.TS_SELENIUM_GIT_PROVIDER_OAUTH) { - test(`Authorize with a ${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER} OAuth and deny access`, async function (): Promise { - await oauthPage.login(); - await oauthPage.waitOauthPage(); - await oauthPage.denyAccess(); - }); + test('Wait the workspace readiness', async function(): Promise { + await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + }); + + test('Check if a project folder has been created', async function(): Promise { + testRepoProjectName = StringUtil.getProjectNameFromGitUrl(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_URL); + Logger.debug(`new SideBarView().getContent().getSection: get ${testRepoProjectName}`); + projectSection = await new SideBarView().getContent().getSection(testRepoProjectName); + }); + + test('Accept the project as a trusted one', async function(): Promise { + // click somewhere to trigger "Welcome Content" dialog + try { + await driverHelper.waitAndClick(webCheCodeLocators.Workbench.notificationItem); + } catch (e) { + Logger.info(`Click on ${webCheCodeLocators.Workbench.notificationItem} to get "Welcome Content" dialog ${e as string}`); + } + // "Welcome Content" dialog can be shown before of after dialog with an error for private repo + try { + const buttonYesITrustTheAuthors: string = `Yes, I trust the authors`; + await driverHelper.waitVisibility(webCheCodeLocators.WelcomeContent.text, TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM); + const welcomeContentDialog: ModalDialog = new ModalDialog(); + Logger.debug(`trustedProjectDialog.pushButton: "${buttonYesITrustTheAuthors}"`); + await welcomeContentDialog.pushButton(buttonYesITrustTheAuthors); + await driverHelper.waitDisappearance(webCheCodeLocators.WelcomeContent.text); + } catch (e) { + Logger.info(`"Accept the project as a trusted one" dialog was not shown firstly for "${isPrivateRepo}"`); + if (!FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO) { + throw new WebDriverError(e as string); + } } + }); - test('Obtain workspace name from workspace loader page', async function (): Promise { - await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); + if (FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO) { + test('Check that project can not be cloned', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.Dialog.message); + const workspaceDoesNotExistDialog: ModalDialog = new ModalDialog(); + const message: string = await workspaceDoesNotExistDialog.getMessage(); + expect(message).contains('space does not exist'); }); - test('The workspace starts with access deny flag in the url', async function (): Promise { - expect(await driverHelper.getDriver().getCurrentUrl()).contains('&error_code=access_denied'); + test('Check that project files were not imported', async function(): Promise { + const isFileImported: ViewItem | undefined = await projectSection.findItem(label); + expect(isFileImported).eqls(undefined); }); - test('Registering the running workspace', async function (): Promise { - registerRunningWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + } else { + test('Check if the project files were imported', async function(): Promise { + Logger.debug(`projectSection.findItem: find ${label}`); + const isFileImported: ViewItem | undefined = await projectSection.findItem(label); + // projectSection.findItem(label) can return undefined but test will goes on + expect(isFileImported).not.eqls(undefined); }); - test('Wait the workspace readiness', async function (): Promise { - await projectAndFileTests.waitWorkspaceReadinessForCheCodeEditor(); + test('Make changes to the file', async function(): Promise { + Logger.debug(`projectSection.openItem: "${fileToChange}"`); + await projectSection.openItem(fileToChange); + const editor: TextEditor = await new EditorView().openEditor(fileToChange) as TextEditor; + await driverHelper.waitVisibility(webCheCodeLocators.Editor.inputArea); + Logger.debug(`editor.clearText`); + await editor.clearText(); + Logger.debug(`editor.typeTextAt: "${changesToCommit}"`); + await editor.typeTextAt(1, 1, changesToCommit); }); - test('Check if a project folder has been created', async function (): Promise { - testRepoProjectName = StringUtil.getProjectNameFromGitUrl(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_URL); - Logger.debug(`new SideBarView().getContent().getSection: get ${testRepoProjectName}`); - projectSection = await new SideBarView().getContent().getSection(testRepoProjectName); + test('Open a source control manager', async function(): Promise { + const viewSourceControl: string = `Source Control`; + const sourceControl: ViewControl = await new ActivityBar().getViewControl(viewSourceControl) as ViewControl; + Logger.debug(`sourceControl.openView: "${viewSourceControl}"`); + await sourceControl.openView(); + const scmView: NewScmView = new NewScmView(); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); + [scmProvider, ...rest] = await scmView.getProviders(); + Logger.debug(`scmView.getProviders: "${scmProvider}, ${scmProvider}"`); }); - test('Accept the project as a trusted one', async function (): Promise { - // click somewhere to trigger "Welcome Content" dialog - try { - await driverHelper.waitAndClick(webCheCodeLocators.Workbench.notificationItem); - } catch (e) { - Logger.info(`Click on ${webCheCodeLocators.Workbench.notificationItem} to get "Welcome Content" dialog ${e as string}`); - } - // "Welcome Content" dialog can be shown before of after dialog with an error for private repo - try { - const buttonYesITrustTheAuthors: string = `Yes, I trust the authors`; - await driverHelper.waitVisibility(webCheCodeLocators.WelcomeContent.text, TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM); - const welcomeContentDialog: ModalDialog = new ModalDialog(); - Logger.debug(`trustedProjectDialog.pushButton: "${buttonYesITrustTheAuthors}"`); - await welcomeContentDialog.pushButton(buttonYesITrustTheAuthors); - await driverHelper.waitDisappearance(webCheCodeLocators.WelcomeContent.text); - } catch (e) { - Logger.info(`"Accept the project as a trusted one" dialog was not shown firstly for "${isPrivateRepo}"`); - if (!FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO) { - throw new WebDriverError(e as string); - } - } + test('Check if the changes are displayed in the source control manager', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + await driverHelper.wait(timeToRefresh); + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + // wait while changes counter will be refreshed + await driverHelper.wait(timeToRefresh); + const changes: number = await scmProvider.getChangeCount(); + Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); + expect(changes).eql(1); }); - if (FactoryTestConstants.TS_SELENIUM_IS_PRIVATE_FACTORY_GIT_REPO) { - test('Check that project can not be cloned', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.Dialog.message); - const workspaceDoesNotExistDialog: ModalDialog = new ModalDialog(); - const message: string = await workspaceDoesNotExistDialog.getMessage(); - expect(message).contains('space does not exist'); - }); - - test('Check that project files were not imported', async function (): Promise { - const isFileImported: ViewItem | undefined = await projectSection.findItem(label); - expect(isFileImported).eqls(undefined); - }); - - } else { - test('Check if the project files were imported', async function (): Promise { - Logger.debug(`projectSection.findItem: find ${label}`); - const isFileImported: ViewItem | undefined = await projectSection.findItem(label); - // projectSection.findItem(label) can return undefined but test will goes on - expect(isFileImported).not.eqls(undefined); - }); - - test('Make changes to the file', async function (): Promise { - Logger.debug(`projectSection.openItem: "${fileToChange}"`); - await projectSection.openItem(fileToChange); - const editor: TextEditor = await new EditorView().openEditor(fileToChange) as TextEditor; - await driverHelper.waitVisibility(webCheCodeLocators.Editor.inputArea); - Logger.debug(`editor.clearText`); - await editor.clearText(); - Logger.debug(`editor.typeTextAt: "${changesToCommit}"`); - await editor.typeTextAt(1, 1, changesToCommit); - }); - - test('Open a source control manager', async function (): Promise { - const viewSourceControl: string = `Source Control`; - const sourceControl: ViewControl = await new ActivityBar().getViewControl(viewSourceControl) as ViewControl; - Logger.debug(`sourceControl.openView: "${viewSourceControl}"`); - await sourceControl.openView(); - const scmView: NewScmView = new NewScmView(); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); - [scmProvider, ...rest] = await scmView.getProviders(); - Logger.debug(`scmView.getProviders: "${scmProvider}, ${scmProvider}"`); - }); - - test('Check if the changes are displayed in the source control manager', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - await driverHelper.wait(timeToRefresh); - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - // wait while changes counter will be refreshed - await driverHelper.wait(timeToRefresh); - const changes: number = await scmProvider.getChangeCount(); - Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); - expect(changes).eql(1); - }); - - test('Stage the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - Logger.debug(`scmProvider.openMoreActions`); - scmContextMenu = await scmProvider.openMoreActions(); - await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.contextView); - Logger.debug(`scmContextMenu.select: "Changes" -> "Stage All Changes"`); - await scmContextMenu.select('Changes', 'Stage All Changes'); - }); + test('Stage the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + Logger.debug(`scmProvider.openMoreActions`); + scmContextMenu = await scmProvider.openMoreActions(); + await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.contextView); + Logger.debug(`scmContextMenu.select: "Changes" -> "Stage All Changes"`); + await scmContextMenu.select('Changes', 'Stage All Changes'); + }); - test('Commit the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); - Logger.debug(`scmProvider.commitChanges: commit name "Commit ${changesToCommit}"`); - await scmProvider.commitChanges('Commit ' + changesToCommit); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - await driverHelper.wait(timeToRefresh); - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - // wait while changes counter will be refreshed - await driverHelper.wait(timeToRefresh); - const changes: number = await scmProvider.getChangeCount(); - Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); - expect(changes).eql(0); - }); + test('Commit the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel)); + Logger.debug(`scmProvider.commitChanges: commit name "Commit ${changesToCommit}"`); + await scmProvider.commitChanges('Commit ' + changesToCommit); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + await driverHelper.wait(timeToRefresh); + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + // wait while changes counter will be refreshed + await driverHelper.wait(timeToRefresh); + const changes: number = await scmProvider.getChangeCount(); + Logger.debug(`scmProvider.getChangeCount: number of changes is "${changes}"`); + expect(changes).eql(0); + }); - test('Push the changes', async function (): Promise { - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(`Push 1 commits to origin/${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}`)); - await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); - Logger.debug(`scmProvider.openMoreActions`); - scmContextMenu = await scmProvider.openMoreActions(); - await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.itemConstructor(pushItemLabel)); - Logger.debug(`scmContextMenu.select: "${pushItemLabel}"`); - await scmContextMenu.select(pushItemLabel); - }); + test('Push the changes', async function(): Promise { + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.actionConstructor(`Push 1 commits to origin/${FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_REPO_BRANCH}`)); + await driverHelper.waitVisibility(webCheCodeLocators.ScmView.more); + Logger.debug(`scmProvider.openMoreActions`); + scmContextMenu = await scmProvider.openMoreActions(); + await driverHelper.waitVisibility(webCheCodeLocators.ContextMenu.itemConstructor(pushItemLabel)); + Logger.debug(`scmContextMenu.select: "${pushItemLabel}"`); + await scmContextMenu.select(pushItemLabel); + }); - test('Insert git credentials which were asked after push', async function (): Promise { - try { - await driverHelper.waitVisibility(webCheCodeLocators.InputBox.message); - } catch (e) { - Logger.info(`Workspace did not ask credentials before push - ${e}; + test('Insert git credentials which were asked after push', async function(): Promise { + try { + await driverHelper.waitVisibility(webCheCodeLocators.InputBox.message); + } catch (e) { + Logger.info(`Workspace did not ask credentials before push - ${e}; Known issue for github.com - https://issues.redhat.com/browse/CRW-4066, please check if not other git provider. `); - expect(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER).eqls(GitProviderType.GITHUB); - } - const input: InputBox = new InputBox(); - await input.setText(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_USERNAME); - await input.confirm(); - await driverHelper.wait(timeToRefresh); - await input.setText(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_PASSWORD); - await input.confirm(); - await driverHelper.wait(timeToRefresh); - }); - - test('Check if the changes were pushed', async function (): Promise { - try { - Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); - await scmProvider.takeAction(refreshButtonLabel); - } catch (e) { - Logger.info('Check you use correct credentials.' + - 'For bitbucket.org ensure you use an app password: https://support.atlassian.com/bitbucket-cloud/docs/using-app-passwords/;' + - 'For github.com - personal access token instead of password.'); - } - const isCommitButtonDisabled: string = await driverHelper.waitAndGetElementAttribute(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel), 'aria-disabled'); - expect(isCommitButtonDisabled).eql('true'); - }); - } - - test('Stop the workspace', async function (): Promise { - await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); - await browserTabsUtil.closeAllTabsExceptCurrent(); + expect(FactoryTestConstants.TS_SELENIUM_FACTORY_GIT_PROVIDER).eqls(GitProviderType.GITHUB); + } + const input: InputBox = new InputBox(); + await input.setText(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_USERNAME); + await input.confirm(); + await driverHelper.wait(timeToRefresh); + await input.setText(OAuthConstants.TS_SELENIUM_GIT_PROVIDER_PASSWORD); + await input.confirm(); + await driverHelper.wait(timeToRefresh); }); - test('Delete the workspace', async function (): Promise { - await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + test('Check if the changes were pushed', async function(): Promise { + try { + Logger.debug(`scmProvider.takeAction: "${refreshButtonLabel}"`); + await scmProvider.takeAction(refreshButtonLabel); + } catch (e) { + Logger.info('Check you use correct credentials.' + + 'For bitbucket.org ensure you use an app password: https://support.atlassian.com/bitbucket-cloud/docs/using-app-passwords/;' + + 'For github.com - personal access token instead of password.'); + } + const isCommitButtonDisabled: string = await driverHelper.waitAndGetElementAttribute(webCheCodeLocators.ScmView.actionConstructor(commitChangesButtonLabel), 'aria-disabled'); + expect(isCommitButtonDisabled).eql('true'); }); + } + + test('Stop the workspace', async function(): Promise { + await workspaceHandlingTests.stopWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + await browserTabsUtil.closeAllTabsExceptCurrent(); + }); + + test('Delete the workspace', async function(): Promise { + await workspaceHandlingTests.removeWorkspace(WorkspaceHandlingTests.getWorkspaceName()); + }); - loginTests.logoutFromChe(); + loginTests.logoutFromChe(); }); diff --git a/tests/e2e/specs/miscellaneous/PredefinedNamespace.spec.ts b/tests/e2e/specs/miscellaneous/PredefinedNamespace.spec.ts index 90d80b66462..74deb8ffe3c 100644 --- a/tests/e2e/specs/miscellaneous/PredefinedNamespace.spec.ts +++ b/tests/e2e/specs/miscellaneous/PredefinedNamespace.spec.ts @@ -13,66 +13,66 @@ const workspaceHandlingTests: WorkspaceHandlingTests = e2eContainer.get(CLASSES. const predefinedNamespaceName: string = 'predefined-ns'; async function runShellScript(shellCommandToExecution: string): Promise { - const {stdout, stderr} = await exec(shellCommandToExecution); - console.log(stdout); - console.error(stderr); - return stdout; + const { stdout, stderr } = await exec(shellCommandToExecution); + console.log(stdout); + console.error(stderr); + return stdout; } -suite(`Create predefined workspace and check it `, async function (): Promise { - let workspaceName: string = ''; +suite(`Create predefined workspace and check it `, async function(): Promise { + let workspaceName: string = ''; - const setEditRightsForUser: string = `oc adm policy add-role-to-user edit user -n ${predefinedNamespaceName}`; - const getDevWorkspaceFromPredefinedNameSpace: string = `oc get dw -n ${predefinedNamespaceName}`; - const deletePredefinedNamespace: string = `oc delete project ${predefinedNamespaceName}`; - const createPredefinedProjectCommand: string = 'cat < { - Logger.info('Test prerequisites:'); - Logger.info(' (1) there is OCP user with username and user password that have been set in the TS_SELENIUM_OCP_USERNAME and TS_SELENIUM_OCP_PASSWORD variables'); - Logger.info(' (2) \'oc\' client installed and logged into test OCP cluster with admin rights.'); + const setEditRightsForUser: string = `oc adm policy add-role-to-user edit user -n ${predefinedNamespaceName}`; + const getDevWorkspaceFromPredefinedNameSpace: string = `oc get dw -n ${predefinedNamespaceName}`; + const deletePredefinedNamespace: string = `oc delete project ${predefinedNamespaceName}`; + const createPredefinedProjectCommand: string = 'cat < { + Logger.info('Test prerequisites:'); + Logger.info(' (1) there is OCP user with username and user password that have been set in the TS_SELENIUM_OCP_USERNAME and TS_SELENIUM_OCP_PASSWORD variables'); + Logger.info(' (2) \'oc\' client installed and logged into test OCP cluster with admin rights.'); - await runShellScript(createPredefinedProjectCommand); - await runShellScript(setEditRightsForUser); - }); + await runShellScript(createPredefinedProjectCommand); + await runShellScript(setEditRightsForUser); + }); - suiteTeardown(async (): Promise => { - const workspaceName: string = WorkspaceHandlingTests.getWorkspaceName(); - try { - await runShellScript(deletePredefinedNamespace); - } catch (e) { - Logger.error(`Cannot remove the predefined project: ${workspaceName}, please fix it manually: ${e}`); - } - }); + suiteTeardown(async (): Promise => { + const workspaceName: string = WorkspaceHandlingTests.getWorkspaceName(); + try { + await runShellScript(deletePredefinedNamespace); + } catch (e) { + Logger.error(`Cannot remove the predefined project: ${workspaceName}, please fix it manually: ${e}`); + } + }); - loginTests.loginIntoChe(); - // create the Empty workspace using CHE Dashboard - test(`Create and open new workspace, stack:${'Empty Workspace'}`, async function (): Promise { - await workspaceHandlingTests.createAndOpenWorkspace('Empty Workspace'); - }); - test('Obtain workspace name from workspace loader page', async function (): Promise { - await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); - }); + loginTests.loginIntoChe(); + // create the Empty workspace using CHE Dashboard + test(`Create and open new workspace, stack:${'Empty Workspace'}`, async function(): Promise { + await workspaceHandlingTests.createAndOpenWorkspace('Empty Workspace'); + }); + test('Obtain workspace name from workspace loader page', async function(): Promise { + await workspaceHandlingTests.obtainWorkspaceNameFromStartingPage(); + }); - // verify that just created workspace with unique name is present in the predefined namespace - test('Validate the created workspace is present in predefined namespace', async function (): Promise { - workspaceName = WorkspaceHandlingTests.getWorkspaceName(); - registerRunningWorkspace(workspaceName); - const ocDevWorkspaceOutput: string = await runShellScript(getDevWorkspaceFromPredefinedNameSpace); - await assert.isTrue(ocDevWorkspaceOutput.includes(workspaceName)); - }); + // verify that just created workspace with unique name is present in the predefined namespace + test('Validate the created workspace is present in predefined namespace', async function(): Promise { + workspaceName = WorkspaceHandlingTests.getWorkspaceName(); + registerRunningWorkspace(workspaceName); + const ocDevWorkspaceOutput: string = await runShellScript(getDevWorkspaceFromPredefinedNameSpace); + await assert.isTrue(ocDevWorkspaceOutput.includes(workspaceName)); + }); - loginTests.logoutFromChe(); + loginTests.logoutFromChe(); }); diff --git a/tests/e2e/tests-library/LoginTests.ts b/tests/e2e/tests-library/LoginTests.ts index 2b6577657b6..984f3260cef 100644 --- a/tests/e2e/tests-library/LoginTests.ts +++ b/tests/e2e/tests-library/LoginTests.ts @@ -18,36 +18,36 @@ import { BaseTestConstants } from '../constants/BaseTestConstants'; @injectable() export class LoginTests { - constructor( - @inject(CLASSES.BrowserTabsUtil) private readonly browserTabsUtil: BrowserTabsUtil, - @inject(TYPES.CheLogin) private readonly productLoginPage: ICheLoginPage, - @inject(TYPES.OcpLogin) private readonly ocpLoginPage: IOcpLoginPage, - @inject(CLASSES.Dashboard) private readonly dashboard: Dashboard) { - } + constructor( + @inject(CLASSES.BrowserTabsUtil) private readonly browserTabsUtil: BrowserTabsUtil, + @inject(TYPES.CheLogin) private readonly productLoginPage: ICheLoginPage, + @inject(TYPES.OcpLogin) private readonly ocpLoginPage: IOcpLoginPage, + @inject(CLASSES.Dashboard) private readonly dashboard: Dashboard) { + } - loginIntoChe(): void { - test('Login', async () => { - if (!(await this.browserTabsUtil.getCurrentUrl()).includes(BaseTestConstants.TS_SELENIUM_BASE_URL)) { - await this.browserTabsUtil.navigateTo(BaseTestConstants.TS_SELENIUM_BASE_URL); - } - await this.productLoginPage.login(); - await this.browserTabsUtil.maximize(); - await this.dashboard.waitStartingPageLoaderDisappearance(); - }); - } + loginIntoChe(): void { + test('Login', async () => { + if (!(await this.browserTabsUtil.getCurrentUrl()).includes(BaseTestConstants.TS_SELENIUM_BASE_URL)) { + await this.browserTabsUtil.navigateTo(BaseTestConstants.TS_SELENIUM_BASE_URL); + } + await this.productLoginPage.login(); + await this.browserTabsUtil.maximize(); + await this.dashboard.waitStartingPageLoaderDisappearance(); + }); + } - loginIntoOcpConsole(): void { - test('Login into ocp console', async () => { - const openshiftConsoleUrl: string = BaseTestConstants.TS_SELENIUM_BASE_URL.replace('devspaces', 'console-openshift-console'); - await this.browserTabsUtil.navigateTo(openshiftConsoleUrl); - await this.ocpLoginPage.login(); - await this.browserTabsUtil.maximize(); - }); - } + loginIntoOcpConsole(): void { + test('Login into ocp console', async () => { + const openshiftConsoleUrl: string = BaseTestConstants.TS_SELENIUM_BASE_URL.replace('devspaces', 'console-openshift-console'); + await this.browserTabsUtil.navigateTo(openshiftConsoleUrl); + await this.ocpLoginPage.login(); + await this.browserTabsUtil.maximize(); + }); + } - logoutFromChe(): void { - test('Logout', async () => { - await this.dashboard.logout(); - }); - } + logoutFromChe(): void { + test('Logout', async () => { + await this.dashboard.logout(); + }); + } } diff --git a/tests/e2e/tests-library/ProjectAndFileTests.ts b/tests/e2e/tests-library/ProjectAndFileTests.ts index 4c35ed0e41b..40533db3f40 100644 --- a/tests/e2e/tests-library/ProjectAndFileTests.ts +++ b/tests/e2e/tests-library/ProjectAndFileTests.ts @@ -19,19 +19,19 @@ import { TimeoutConstants } from '../constants/TimeoutConstants'; @injectable() export class ProjectAndFileTests { - constructor( - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) {} + constructor( + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) {} - async waitWorkspaceReadinessForCheCodeEditor(): Promise { - Logger.debug(`waiting for editor.`); - try { - const start: number = new Date().getTime(); - await this.driverHelper.getDriver().wait(until.elementLocated(By.className('monaco-workbench')), TimeoutConstants.TS_SELENIUM_START_WORKSPACE_TIMEOUT); - const end: number = new Date().getTime(); - Logger.debug(`editor was opened in ${end - start} seconds.`); - } catch (err) { - Logger.error(`waiting for workspace readiness failed: ${err}`); - throw err; - } + async waitWorkspaceReadinessForCheCodeEditor(): Promise { + Logger.debug(`waiting for editor.`); + try { + const start: number = new Date().getTime(); + await this.driverHelper.getDriver().wait(until.elementLocated(By.className('monaco-workbench')), TimeoutConstants.TS_SELENIUM_START_WORKSPACE_TIMEOUT); + const end: number = new Date().getTime(); + Logger.debug(`editor was opened in ${end - start} seconds.`); + } catch (err) { + Logger.error(`waiting for workspace readiness failed: ${err}`); + throw err; } + } } diff --git a/tests/e2e/tests-library/WorkspaceHandlingTests.ts b/tests/e2e/tests-library/WorkspaceHandlingTests.ts index d3073a2f5de..b3b1f207dec 100644 --- a/tests/e2e/tests-library/WorkspaceHandlingTests.ts +++ b/tests/e2e/tests-library/WorkspaceHandlingTests.ts @@ -13,7 +13,6 @@ import { inject, injectable } from 'inversify'; import { CLASSES } from '../configs/inversify.types'; import { Dashboard } from '../pageobjects/dashboard/Dashboard'; import { CreateWorkspace } from '../pageobjects/dashboard/CreateWorkspace'; -import { Workspaces } from '../pageobjects/dashboard/Workspaces'; import { BrowserTabsUtil } from '../utils/BrowserTabsUtil'; import { Logger } from '../utils/Logger'; import { ApiUrlResolver } from '../utils/workspace/ApiUrlResolver'; @@ -24,101 +23,100 @@ import { By, error } from 'selenium-webdriver'; @injectable() export class WorkspaceHandlingTests { - static getWorkspaceName(): string { - return WorkspaceHandlingTests.workspaceName; - } + static getWorkspaceName(): string { + return WorkspaceHandlingTests.workspaceName; + } - private static WORKSPACE_NAME_LOCATOR: By = By.xpath(`//h1[contains(.,'Starting workspace ')]`); - private static workspaceName: string = 'undefined'; - private static parentGUID: string; + private static WORKSPACE_NAME_LOCATOR: By = By.xpath(`//h1[contains(.,'Starting workspace ')]`); + private static workspaceName: string = 'undefined'; + private static parentGUID: string; - constructor( - @inject(CLASSES.Dashboard) private readonly dashboard: Dashboard, - @inject(CLASSES.CreateWorkspace) private readonly createWorkspace: CreateWorkspace, - @inject(CLASSES.Workspaces) private readonly workspaces: Workspaces, - @inject(CLASSES.BrowserTabsUtil) private readonly browserTabsUtil: BrowserTabsUtil, - @inject(CLASSES.ApiUrlResolver) private readonly apiUrlResolver: ApiUrlResolver, - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) {} + constructor( + @inject(CLASSES.Dashboard) private readonly dashboard: Dashboard, + @inject(CLASSES.CreateWorkspace) private readonly createWorkspace: CreateWorkspace, + @inject(CLASSES.BrowserTabsUtil) private readonly browserTabsUtil: BrowserTabsUtil, + @inject(CLASSES.ApiUrlResolver) private readonly apiUrlResolver: ApiUrlResolver, + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) {} - setWindowHandle(guid: string): void { - WorkspaceHandlingTests.parentGUID = guid; - } + setWindowHandle(guid: string): void { + WorkspaceHandlingTests.parentGUID = guid; + } - getWindowHandle(): string { - return WorkspaceHandlingTests.parentGUID; - } + getWindowHandle(): string { + return WorkspaceHandlingTests.parentGUID; + } - async createAndOpenWorkspace(stack: string): Promise { - await this.dashboard.clickWorkspacesButton(); - await this.dashboard.waitPage(); - Logger.debug(`fetching user kubernetes namespace, storing auth token by getting workspaces API URL.`); - await this.apiUrlResolver.getWorkspacesApiUrl(); - await this.dashboard.clickCreateWorkspaceButton(); - await this.createWorkspace.waitPage(); - WorkspaceHandlingTests.parentGUID = await this.browserTabsUtil.getCurrentWindowHandle(); - await this.createWorkspace.clickOnSampleNoEditorSelection(stack); - await this.browserTabsUtil.waitAndSwitchToAnotherWindow(WorkspaceHandlingTests.parentGUID, TimeoutConstants.TS_IDE_LOAD_TIMEOUT); - } + async createAndOpenWorkspace(stack: string): Promise { + await this.dashboard.clickWorkspacesButton(); + await this.dashboard.waitPage(); + Logger.debug(`fetching user kubernetes namespace, storing auth token by getting workspaces API URL.`); + await this.apiUrlResolver.getWorkspacesApiUrl(); + await this.dashboard.clickCreateWorkspaceButton(); + await this.createWorkspace.waitPage(); + WorkspaceHandlingTests.parentGUID = await this.browserTabsUtil.getCurrentWindowHandle(); + await this.createWorkspace.clickOnSampleNoEditorSelection(stack); + await this.browserTabsUtil.waitAndSwitchToAnotherWindow(WorkspaceHandlingTests.parentGUID, TimeoutConstants.TS_IDE_LOAD_TIMEOUT); + } - async createAndOpenWorkspaceFromGitRepository(factoryUrl: string): Promise { - await this.dashboard.waitPage(); - Logger.debug(`fetching user kubernetes namespace, storing auth token by getting workspaces API URL.`); - await this.apiUrlResolver.getWorkspacesApiUrl(); - await this.dashboard.clickCreateWorkspaceButton(); - await this.createWorkspace.waitPage(); - WorkspaceHandlingTests.parentGUID = await this.browserTabsUtil.getCurrentWindowHandle(); - await this.createWorkspace.importFromGitUsingUI(factoryUrl); - await this.browserTabsUtil.waitAndSwitchToAnotherWindow(WorkspaceHandlingTests.parentGUID, TimeoutConstants.TS_IDE_LOAD_TIMEOUT); - } + async createAndOpenWorkspaceFromGitRepository(factoryUrl: string): Promise { + await this.dashboard.waitPage(); + Logger.debug(`fetching user kubernetes namespace, storing auth token by getting workspaces API URL.`); + await this.apiUrlResolver.getWorkspacesApiUrl(); + await this.dashboard.clickCreateWorkspaceButton(); + await this.createWorkspace.waitPage(); + WorkspaceHandlingTests.parentGUID = await this.browserTabsUtil.getCurrentWindowHandle(); + await this.createWorkspace.importFromGitUsingUI(factoryUrl); + await this.browserTabsUtil.waitAndSwitchToAnotherWindow(WorkspaceHandlingTests.parentGUID, TimeoutConstants.TS_IDE_LOAD_TIMEOUT); + } - async obtainWorkspaceNameFromStartingPage(): Promise { - const timeout: number = TimeoutConstants.TS_IDE_LOAD_TIMEOUT; - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); + async obtainWorkspaceNameFromStartingPage(): Promise { + const timeout: number = TimeoutConstants.TS_IDE_LOAD_TIMEOUT; + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); - for (let i: number = 0; i < attempts; i++) { - try { - let startingWorkspaceLineContent: string = await this.driverHelper.getDriver().findElement(WorkspaceHandlingTests.WORKSPACE_NAME_LOCATOR).getText(); - Logger.trace(`obtained starting workspace getText():${startingWorkspaceLineContent}`); - // cutting away leading text - WorkspaceHandlingTests.workspaceName = startingWorkspaceLineContent.substring('Starting workspace '.length).trim(); - Logger.trace(`trimmed workspace name from getText():${WorkspaceHandlingTests.workspaceName}`); - break; - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - Logger.trace(`failed to obtain name from workspace start page, element possibly detached from DOM. Retrying.`); - await this.driverHelper.wait(polling); - continue; - } - if (err instanceof error.NoSuchElementError) { - Logger.trace(`failed to obtain name from workspace start page, element not visible yet. Retrying.`); - await this.driverHelper.wait(polling); - continue; - } - Logger.error(`obtaining workspace name failed with an unexpected error:${err}`); - throw err; - } - } - if (WorkspaceHandlingTests.workspaceName !== '' && WorkspaceHandlingTests.workspaceName !== 'undefined') { - Logger.info(`obtained workspace name from workspace loader page: ${WorkspaceHandlingTests.workspaceName}`); - return; - } - Logger.error(`failed to obtain workspace name:${WorkspaceHandlingTests.workspaceName}`); - throw new error.InvalidArgumentError(`WorkspaceHandlingTests.obtainWorkspaceNameFromStartingPage failed to obtain workspace name:${WorkspaceHandlingTests.workspaceName}`); + for (let i: number = 0; i < attempts; i++) { + try { + let startingWorkspaceLineContent: string = await this.driverHelper.getDriver().findElement(WorkspaceHandlingTests.WORKSPACE_NAME_LOCATOR).getText(); + Logger.trace(`obtained starting workspace getText():${startingWorkspaceLineContent}`); + // cutting away leading text + WorkspaceHandlingTests.workspaceName = startingWorkspaceLineContent.substring('Starting workspace '.length).trim(); + Logger.trace(`trimmed workspace name from getText():${WorkspaceHandlingTests.workspaceName}`); + break; + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + Logger.trace(`failed to obtain name from workspace start page, element possibly detached from DOM. Retrying.`); + await this.driverHelper.wait(polling); + continue; + } + if (err instanceof error.NoSuchElementError) { + Logger.trace(`failed to obtain name from workspace start page, element not visible yet. Retrying.`); + await this.driverHelper.wait(polling); + continue; + } + Logger.error(`obtaining workspace name failed with an unexpected error:${err}`); + throw err; + } } - - async stopWorkspace(workspaceName: string): Promise { - await this.dashboard.openDashboard(); - await this.dashboard.stopWorkspaceByUI(workspaceName); + if (WorkspaceHandlingTests.workspaceName !== '' && WorkspaceHandlingTests.workspaceName !== 'undefined') { + Logger.info(`obtained workspace name from workspace loader page: ${WorkspaceHandlingTests.workspaceName}`); + return; } + Logger.error(`failed to obtain workspace name:${WorkspaceHandlingTests.workspaceName}`); + throw new error.InvalidArgumentError(`WorkspaceHandlingTests.obtainWorkspaceNameFromStartingPage failed to obtain workspace name:${WorkspaceHandlingTests.workspaceName}`); + } - async removeWorkspace(workspaceName: string): Promise { - await this.dashboard.openDashboard(); - await this.dashboard.deleteStoppedWorkspaceByUI(workspaceName); - } + async stopWorkspace(workspaceName: string): Promise { + await this.dashboard.openDashboard(); + await this.dashboard.stopWorkspaceByUI(workspaceName); + } - async stopAndRemoveWorkspace(workspaceName: string): Promise { - await this.dashboard.openDashboard(); - await this.dashboard.stopAndRemoveWorkspaceByUI(workspaceName); - } + async removeWorkspace(workspaceName: string): Promise { + await this.dashboard.openDashboard(); + await this.dashboard.deleteStoppedWorkspaceByUI(workspaceName); + } + + async stopAndRemoveWorkspace(workspaceName: string): Promise { + await this.dashboard.openDashboard(); + await this.dashboard.stopAndRemoveWorkspaceByUI(workspaceName); + } } diff --git a/tests/e2e/utils/BrowserTabsUtil.ts b/tests/e2e/utils/BrowserTabsUtil.ts index 9e2a7d07830..8051b1fb289 100644 --- a/tests/e2e/utils/BrowserTabsUtil.ts +++ b/tests/e2e/utils/BrowserTabsUtil.ts @@ -8,7 +8,7 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { CLASSES } from '../configs/inversify.types'; import { DriverHelper } from './DriverHelper'; import { Logger } from './Logger'; @@ -17,97 +17,97 @@ import { ChromeDriverConstants } from '../constants/ChromeDriverConstants'; @injectable() export class BrowserTabsUtil { - constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - async switchToWindow(windowHandle: string): Promise { - Logger.debug(); - await this.driverHelper.getDriver().switchTo().window(windowHandle); - } + async switchToWindow(windowHandle: string): Promise { + Logger.debug(); + await this.driverHelper.getDriver().switchTo().window(windowHandle); + } - async getAllWindowHandles(): Promise { - Logger.debug(); + async getAllWindowHandles(): Promise { + Logger.debug(); - return (await this.driverHelper.getDriver()).getAllWindowHandles(); - } + return (await this.driverHelper.getDriver()).getAllWindowHandles(); + } - async getCurrentWindowHandle(): Promise { - Logger.debug(); + async getCurrentWindowHandle(): Promise { + Logger.debug(); - return await this.driverHelper.getDriver().getWindowHandle(); - } + return await this.driverHelper.getDriver().getWindowHandle(); + } - async navigateTo(url: string): Promise { - Logger.debug(`${url}`); + async navigateTo(url: string): Promise { + Logger.debug(`${url}`); - await this.driverHelper.getDriver().navigate().to(url); - } + await this.driverHelper.getDriver().navigate().to(url); + } - async navigateAndWaitToUrl(url: string, timeout: number = TimeoutConstants.TS_SELENIUM_WAIT_FOR_URL): Promise { - Logger.trace(`${url}`); + async navigateAndWaitToUrl(url: string, timeout: number = TimeoutConstants.TS_SELENIUM_WAIT_FOR_URL): Promise { + Logger.trace(`${url}`); - await this.navigateTo(url); - await this.waitURL(url, timeout); - } + await this.navigateTo(url); + await this.waitURL(url, timeout); + } - async waitAndSwitchToAnotherWindow(currentWindowHandle: string, timeout: number): Promise { - Logger.debug(); + async waitAndSwitchToAnotherWindow(currentWindowHandle: string, timeout: number): Promise { + Logger.debug(); - await this.driverHelper.waitUntilTrue(async () => { - const windowHandles: string[] = await this.getAllWindowHandles(); + await this.driverHelper.waitUntilTrue(async () => { + const windowHandles: string[] = await this.getAllWindowHandles(); - return windowHandles.length > 1; - }, timeout); + return windowHandles.length > 1; + }, timeout); - const windowHandles: string[] = await this.getAllWindowHandles(); + const windowHandles: string[] = await this.getAllWindowHandles(); - for (const windowHandle of windowHandles) { - if (windowHandle !== currentWindowHandle) { - await this.switchToWindow(windowHandle); - } - } + for (const windowHandle of windowHandles) { + if (windowHandle !== currentWindowHandle) { + await this.switchToWindow(windowHandle); + } } + } - async refreshPage(): Promise { - Logger.debug(); + async refreshPage(): Promise { + Logger.debug(); - await (await this.driverHelper.getDriver()).navigate().refresh(); - } + await (await this.driverHelper.getDriver()).navigate().refresh(); + } - async getCurrentUrl(): Promise { - return await this.driverHelper.getDriver().getCurrentUrl(); - } + async getCurrentUrl(): Promise { + return await this.driverHelper.getDriver().getCurrentUrl(); + } - async waitURL(expectedUrl: string, timeout: number): Promise { - Logger.trace(`${expectedUrl}`); + async waitURL(expectedUrl: string, timeout: number): Promise { + Logger.trace(`${expectedUrl}`); - await this.driverHelper.getDriver().wait(async () => { - const currentUrl: string = await this.driverHelper.getDriver().getCurrentUrl(); - const urlEquals: boolean = currentUrl === expectedUrl; + await this.driverHelper.getDriver().wait(async () => { + const currentUrl: string = await this.driverHelper.getDriver().getCurrentUrl(); + const urlEquals: boolean = currentUrl === expectedUrl; - if (urlEquals) { - return true; - } - }, timeout); - } + if (urlEquals) { + return true; + } + }, timeout); + } - async maximize(): Promise { - Logger.trace(); - if (ChromeDriverConstants.TS_SELENIUM_LAUNCH_FULLSCREEN) { - Logger.debug(`TS_SELENIUM_LAUNCH_FULLSCREEN is set to true, maximizing window.`); - await this.driverHelper.getDriver().manage().window().maximize(); - } + async maximize(): Promise { + Logger.trace(); + if (ChromeDriverConstants.TS_SELENIUM_LAUNCH_FULLSCREEN) { + Logger.debug(`TS_SELENIUM_LAUNCH_FULLSCREEN is set to true, maximizing window.`); + await this.driverHelper.getDriver().manage().window().maximize(); } + } + + async closeAllTabsExceptCurrent(): Promise { + Logger.trace(); + const allTabsHandles: string[] = await this.getAllWindowHandles(); + const currentTabHandle: string = await this.getCurrentWindowHandle(); + allTabsHandles.splice(allTabsHandles.indexOf(currentTabHandle), 1); - async closeAllTabsExceptCurrent(): Promise { - Logger.trace(); - const allTabsHandles: string[] = await this.getAllWindowHandles(); - const currentTabHandle: string = await this.getCurrentWindowHandle(); - allTabsHandles.splice(allTabsHandles.indexOf(currentTabHandle), 1); - - for (const tabHandle of allTabsHandles) { - await this.switchToWindow(tabHandle); - await this.driverHelper.getDriver().close(); - } - await this.switchToWindow(currentTabHandle); + for (const tabHandle of allTabsHandles) { + await this.switchToWindow(tabHandle); + await this.driverHelper.getDriver().close(); } + await this.switchToWindow(currentTabHandle); + } } diff --git a/tests/e2e/utils/CheReporter.ts b/tests/e2e/utils/CheReporter.ts index fc97c2bedcb..fd297742e47 100644 --- a/tests/e2e/utils/CheReporter.ts +++ b/tests/e2e/utils/CheReporter.ts @@ -10,6 +10,7 @@ import * as mocha from 'mocha'; import { CLASSES } from '../configs/inversify.types'; import * as fs from 'fs'; +import { WriteStream } from 'fs'; import * as rm from 'rimraf'; import { logging } from 'selenium-webdriver'; import { DriverHelper } from './DriverHelper'; @@ -17,7 +18,6 @@ import { ScreenCatcher } from './ScreenCatcher'; import { TimeoutConstants } from '../constants/TimeoutConstants'; import { Logger } from './Logger'; import { e2eContainer } from '../configs/inversify.config'; -import { WriteStream } from 'fs'; import { StringUtil } from './StringUtil'; import { BaseTestConstants } from '../constants/BaseTestConstants'; import { ChromeDriverConstants } from '../constants/ChromeDriverConstants'; @@ -79,7 +79,7 @@ class CheReporter extends mocha.reporters.Spec { rm.sync(ReporterConstants.TS_SELENIUM_REPORT_FOLDER); }); - runner.on('test', async function (test: mocha.Test): Promise { + runner.on('test', async function(test: mocha.Test): Promise { if (!ReporterConstants.TS_SELENIUM_EXECUTION_SCREENCAST) { return; } @@ -108,8 +108,7 @@ class CheReporter extends mocha.reporters.Spec { } }); - - runner.on('end', async function (): Promise { + runner.on('end', async function(): Promise { // ensure that fired events done await driverHelper.wait(5000); @@ -122,7 +121,7 @@ class CheReporter extends mocha.reporters.Spec { } }); - runner.on('fail', async function (test: mocha.Test): Promise { + runner.on('fail', async function(test: mocha.Test): Promise { Logger.error(`CheReporter runner.on.fail: ${test.fullTitle()} failed after ${test.duration}ms`); // raise flag for keeping the screencast deleteScreencast = false; @@ -139,7 +138,6 @@ class CheReporter extends mocha.reporters.Spec { const pageSourceFileName: string = `${testReportDirPath}/pagesource-${testTitle}.html`; const browserLogsFileName: string = `${testReportDirPath}/browserlogs-${testTitle}.txt`; - // create reporter dir if not exist const reportDirExists: boolean = fs.existsSync(ReporterConstants.TS_SELENIUM_REPORT_FOLDER); diff --git a/tests/e2e/utils/DevWorkspaceConfigurationHelper.ts b/tests/e2e/utils/DevWorkspaceConfigurationHelper.ts index 7a54e294f0f..544b5326d37 100644 --- a/tests/e2e/utils/DevWorkspaceConfigurationHelper.ts +++ b/tests/e2e/utils/DevWorkspaceConfigurationHelper.ts @@ -13,71 +13,71 @@ import { APITestConstants } from '../constants/APITestConstants'; */ interface IContextParams { - devfilePath?: string | undefined; - devfileUrl?: string | undefined; - devfileContent?: string | undefined; - outputFile?: string | undefined; - editorPath?: string | undefined; - editorContent?: string | undefined; - editorEntry?: string | undefined; - pluginRegistryUrl?: string | undefined; - projects?: { - name: string; - location: string; - }[]; - injectDefaultComponent?: string | undefined; - defaultComponentImage?: string | undefined; + devfilePath?: string | undefined; + devfileUrl?: string | undefined; + devfileContent?: string | undefined; + outputFile?: string | undefined; + editorPath?: string | undefined; + editorContent?: string | undefined; + editorEntry?: string | undefined; + pluginRegistryUrl?: string | undefined; + projects?: { + name: string; + location: string; + }[]; + injectDefaultComponent?: string | undefined; + defaultComponentImage?: string | undefined; } export class DevWorkspaceConfigurationHelper { - private generator: Generator = new Generator(); - private readonly params: IContextParams; + private generator: Generator = new Generator(); + private readonly params: IContextParams; - constructor(params: IContextParams) { - // check if all undefined - if (!(params.editorPath || params.editorEntry || params.editorContent)) { - params.editorEntry = 'che-incubator/che-code/latest'; - } - // check if one or both has value - if (APITestConstants.TS_API_TEST_UDI_IMAGE || params.defaultComponentImage) { - params.injectDefaultComponent = 'true'; - // check if not explicitly passed than assign value from the constants - if (!params.defaultComponentImage) { - params.defaultComponentImage = APITestConstants.TS_API_TEST_UDI_IMAGE; - } - } - // assign value from the constants if not explicitly passed - if (APITestConstants.TS_API_TEST_PLUGIN_REGISTRY_URL && !params.pluginRegistryUrl) { - params.pluginRegistryUrl = APITestConstants.TS_API_TEST_PLUGIN_REGISTRY_URL; - } - if (APITestConstants.TS_API_TEST_CHE_CODE_EDITOR_DEVFILE_URI && !params.editorContent) { - params.editorContent = ShellExecutor.curl(APITestConstants.TS_API_TEST_CHE_CODE_EDITOR_DEVFILE_URI).stdout; - } - this.params = params; + constructor(params: IContextParams) { + // check if all undefined + if (!(params.editorPath || params.editorEntry || params.editorContent)) { + params.editorEntry = 'che-incubator/che-code/latest'; } + // check if one or both has value + if (APITestConstants.TS_API_TEST_UDI_IMAGE || params.defaultComponentImage) { + params.injectDefaultComponent = 'true'; + // check if not explicitly passed than assign value from the constants + if (!params.defaultComponentImage) { + params.defaultComponentImage = APITestConstants.TS_API_TEST_UDI_IMAGE; + } + } + // assign value from the constants if not explicitly passed + if (APITestConstants.TS_API_TEST_PLUGIN_REGISTRY_URL && !params.pluginRegistryUrl) { + params.pluginRegistryUrl = APITestConstants.TS_API_TEST_PLUGIN_REGISTRY_URL; + } + if (APITestConstants.TS_API_TEST_CHE_CODE_EDITOR_DEVFILE_URI && !params.editorContent) { + params.editorContent = ShellExecutor.curl(APITestConstants.TS_API_TEST_CHE_CODE_EDITOR_DEVFILE_URI).stdout; + } + this.params = params; + } - async generateDevfileContext(): Promise { - Logger.debug(); - if (!this.params.projects) { - this.params.projects = []; - } - return await this.generator.generateDevfileContext( - { - ...this.params, - projects: this.params.projects - }, - axios.default as any - ); + async generateDevfileContext(): Promise { + Logger.debug(); + if (!this.params.projects) { + this.params.projects = []; } + return await this.generator.generateDevfileContext( + { + ...this.params, + projects: this.params.projects + }, + axios.default as any + ); + } - // write templates and then DevWorkspace in a single file - async getDevWorkspaceConfigurationYamlAsString(context: DevfileContext): Promise { - Logger.debug(); - const allContentArray: any[] = context.devWorkspaceTemplates.map( - (template: V1alpha2DevWorkspaceTemplate) => YAML.stringify(template) - ); - allContentArray.push(YAML.stringify(context.devWorkspace)); + // write templates and then DevWorkspace in a single file + async getDevWorkspaceConfigurationYamlAsString(context: DevfileContext): Promise { + Logger.debug(); + const allContentArray: any[] = context.devWorkspaceTemplates.map( + (template: V1alpha2DevWorkspaceTemplate) => YAML.stringify(template) + ); + allContentArray.push(YAML.stringify(context.devWorkspace)); - return allContentArray.join('---\n'); - } + return allContentArray.join('---\n'); + } } diff --git a/tests/e2e/utils/DevfilesRegistryHelper.ts b/tests/e2e/utils/DevfilesRegistryHelper.ts index 8443b682b5f..8a6170ce4e0 100644 --- a/tests/e2e/utils/DevfilesRegistryHelper.ts +++ b/tests/e2e/utils/DevfilesRegistryHelper.ts @@ -14,64 +14,64 @@ import { APITestConstants, SupportedDevfilesRegistries } from '../constants/APIT export class DevfilesRegistryHelper { - async getInbuiltDevfilesRegistryContent(): Promise { - Logger.debug(); - return await this.getContent(SupportedDevfilesRegistries.INBUILT_APPLICATION_DEVFILE_REGISTRY_URL()); - } + async getInbuiltDevfilesRegistryContent(): Promise { + Logger.debug(); + return await this.getContent(SupportedDevfilesRegistries.INBUILT_APPLICATION_DEVFILE_REGISTRY_URL()); + } - async getGitHubCheDevfileRegistryContent(): Promise { - Logger.debug(); - return await this.getContent(SupportedDevfilesRegistries.GIT_HUB_CHE_DEVFILE_REGISTRY_URL); - } + async getGitHubCheDevfileRegistryContent(): Promise { + Logger.debug(); + return await this.getContent(SupportedDevfilesRegistries.GIT_HUB_CHE_DEVFILE_REGISTRY_URL); + } - async collectPathsToDevfilesFromRegistry(): Promise { - Logger.debug(); - const devfileSamples: object[] = []; - const sampleNames: string[] = []; - switch (APITestConstants.TS_API_ACCEPTANCE_TEST_REGISTRY_URL()) { - case (SupportedDevfilesRegistries.GIT_HUB_CHE_DEVFILE_REGISTRY_URL): { - const content: any[any] = await this.getGitHubCheDevfileRegistryContent(); - content.forEach((e: any) => { - if (e.name[0] !== '.') { sampleNames.push(e.name); } - }); + async collectPathsToDevfilesFromRegistry(): Promise { + Logger.debug(); + const devfileSamples: object[] = []; + const sampleNames: string[] = []; + switch (APITestConstants.TS_API_ACCEPTANCE_TEST_REGISTRY_URL()) { + case (SupportedDevfilesRegistries.GIT_HUB_CHE_DEVFILE_REGISTRY_URL): { + const content: any[any] = await this.getGitHubCheDevfileRegistryContent(); + content.forEach((e: any) => { + if (e.name[0] !== '.') { sampleNames.push(e.name); } + }); - for (const sample of sampleNames) { - const sampleEndpoint: string = `${SupportedDevfilesRegistries.GIT_HUB_CHE_DEVFILE_REGISTRY_URL}${sample}/meta.yaml`; - const sampleEndpointContent: AxiosResponse = await this.getContent(sampleEndpoint); - const decodedFileContent: string = Buffer.from((sampleEndpointContent as any).content, 'base64').toString(); - const metaYamlContent: any = YAML.parse(decodedFileContent); - devfileSamples.push({name: sample, link: metaYamlContent.links.v2}); - } - Logger.debug(`samples list: ${JSON.stringify(devfileSamples)}`); - } - break; - case (SupportedDevfilesRegistries.INBUILT_APPLICATION_DEVFILE_REGISTRY_URL()): { - const content: any[any] = await this.getInbuiltDevfilesRegistryContent(); + for (const sample of sampleNames) { + const sampleEndpoint: string = `${SupportedDevfilesRegistries.GIT_HUB_CHE_DEVFILE_REGISTRY_URL}${sample}/meta.yaml`; + const sampleEndpointContent: AxiosResponse = await this.getContent(sampleEndpoint); + const decodedFileContent: string = Buffer.from((sampleEndpointContent as any).content, 'base64').toString(); + const metaYamlContent: any = YAML.parse(decodedFileContent); + devfileSamples.push({ name: sample, link: metaYamlContent.links.v2 }); + } + Logger.debug(`samples list: ${JSON.stringify(devfileSamples)}`); + } + break; + case (SupportedDevfilesRegistries.INBUILT_APPLICATION_DEVFILE_REGISTRY_URL()): { + const content: any[any] = await this.getInbuiltDevfilesRegistryContent(); - for (const sample of content) { - devfileSamples.push({name: sample.displayName, link: sample.links.v2}); - } - Logger.debug(`samples list: ${JSON.stringify(devfileSamples)}`); - } - break; - default: { - Logger.error(`unsupported registry url - ${APITestConstants.TS_API_ACCEPTANCE_TEST_REGISTRY_URL()}\n - supported registries: ${JSON.stringify(SupportedDevfilesRegistries)}`); - } + for (const sample of content) { + devfileSamples.push({ name: sample.displayName, link: sample.links.v2 }); } - return devfileSamples; + Logger.debug(`samples list: ${JSON.stringify(devfileSamples)}`); + } + break; + default: { + Logger.error(`unsupported registry url - ${APITestConstants.TS_API_ACCEPTANCE_TEST_REGISTRY_URL()}\n + supported registries: ${JSON.stringify(SupportedDevfilesRegistries)}`); + } } + return devfileSamples; + } - private async getContent(url: string, headers?: object): Promise { - Logger.debug(`${url}`); + private async getContent(url: string, headers?: object): Promise { + Logger.debug(`${url}`); - let response: AxiosResponse | undefined; - try { - response = await axios.get(url, headers); - } catch (error) { - Logger.error(`${error} + ${url}`); - throw error; - } - return response?.data; + let response: AxiosResponse | undefined; + try { + response = await axios.get(url, headers); + } catch (error) { + Logger.error(`${error} + ${url}`); + throw error; } + return response?.data; + } } diff --git a/tests/e2e/utils/DriverHelper.ts b/tests/e2e/utils/DriverHelper.ts index ac122b8f481..eb8f641f2ca 100644 --- a/tests/e2e/utils/DriverHelper.ts +++ b/tests/e2e/utils/DriverHelper.ts @@ -15,704 +15,703 @@ import 'reflect-metadata'; import { Logger } from './Logger'; import { TimeoutConstants } from '../constants/TimeoutConstants'; - @injectable() export class DriverHelper { - private readonly driver: ThenableWebDriver; + private readonly driver: ThenableWebDriver; - constructor(@inject(TYPES.Driver) driver: IDriver) { - this.driver = driver.get() as ThenableWebDriver; - } + constructor(@inject(TYPES.Driver) driver: IDriver) { + this.driver = driver.get() as ThenableWebDriver; + } + + getAction(): Actions { + Logger.trace(); + + return this.driver.actions(); + } - getAction(): Actions { - Logger.trace(); + async isVisible(locator: By): Promise { + Logger.trace(`${locator}`); - return this.driver.actions(); + try { + const element: WebElement = await this.driver.findElement(locator); + return await element.isDisplayed(); + } catch { + return false; } + } - async isVisible(locator: By): Promise { - Logger.trace(`${locator}`); + async wait(milliseconds: number): Promise { + Logger.trace(`(${milliseconds} milliseconds)`); - try { - const element: WebElement = await this.driver.findElement(locator); - return await element.isDisplayed(); - } catch { - return false; - } + await this.driver.sleep(milliseconds); + } + + async refreshPage(): Promise { + Logger.trace(); + + await this.driver.navigate().refresh(); + } + + async waitVisibilityBoolean(locator: By, + attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, + polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { + + Logger.trace(`${locator}`); + + for (let i: number = 0; i < attempts; i++) { + const isVisible: boolean = await this.isVisible(locator); + + if (isVisible) { + return true; + } + + await this.wait(polling); } - async wait(milliseconds: number): Promise { - Logger.trace(`(${milliseconds} milliseconds)`); + return false; + } + + async waitDisappearanceBoolean(locator: By, + attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, + polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { + + Logger.trace(`${locator}`); + + for (let i: number = 0; i < attempts; i++) { + const isVisible: boolean = await this.isVisible(locator); - await this.driver.sleep(milliseconds); + if (!isVisible) { + return true; + } + + await this.wait(polling); } - async refreshPage(): Promise { - Logger.trace(); + return false; + } + + async waitVisibility(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); + + Logger.trace(`${elementLocator}`); + + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.driver.wait(until.elementLocated(elementLocator), polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } + + if (err instanceof error.TimeoutError) { + if (attempts !== 1) { // waitVisibility was spamming other methods when the number of attempts was 1 - only show message if attempts > 1 + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + } + continue; + } + + if (err instanceof error.NoSuchWindowError) { // sometimes waitVisibility fails with NoSuchWindowError when the check is run too soon before the page loads + Logger.trace(`failed with NoSuchWindow exception. Attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } + + try { + const visibleWebElement: WebElement = await this.driver.wait(until.elementIsVisible(element), polling); + Logger.trace('element is located and is visible.'); + return visibleWebElement; + } catch (err) { + if (err instanceof error.TimeoutError) { + if (attempts !== 1) { // waitVisibility was spamming other methods when the number of attempts was 1 - only show message if attempts > 1 + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + } + continue; + } - await this.driver.navigate().refresh(); + if (err instanceof error.StaleElementReferenceError) { + Logger.debug(`stale element error - ${err}`); + await this.wait(polling); + continue; + } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async waitVisibilityBoolean(locator: By, - attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, - polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { + throw new error.TimeoutError(`Exceeded maximum visibility checking attempts for '${elementLocator}' element, timeouted after ${timeout}`); + } - Logger.trace(`${locator}`); + async waitPresence(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); - for (let i: number = 0; i < attempts; i++) { - const isVisible: boolean = await this.isVisible(locator); + Logger.trace(`${elementLocator}`); - if (isVisible) { - return true; - } + for (let i: number = 0; i < attempts; i++) { + try { + return await this.driver.wait(until.elementLocated(elementLocator), polling); + } catch (err) { + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } - await this.wait(polling); + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; } - return false; + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async waitDisappearanceBoolean(locator: By, - attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, - polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { + throw new error.TimeoutError(`Exceeded maximum presence checking attempts, problems with 'StaleElementReferenceError' of '${elementLocator}' element`); + } - Logger.trace(`${locator}`); + async waitAllPresence(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise> { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); - for (let i: number = 0; i < attempts; i++) { - const isVisible: boolean = await this.isVisible(locator); + Logger.trace(`${elementLocator}`); - if (!isVisible) { - return true; - } + for (let i: number = 0; i < attempts; i++) { + try { + return await this.driver.wait(until.elementsLocated(elementLocator), polling); + } catch (err) { + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } - await this.wait(polling); + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; } - return false; + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async waitVisibility(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator}`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.driver.wait(until.elementLocated(elementLocator), polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - if (attempts !== 1) { // waitVisibility was spamming other methods when the number of attempts was 1 - only show message if attempts > 1 - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - } - continue; - } - - if (err instanceof error.NoSuchWindowError) { // sometimes waitVisibility fails with NoSuchWindowError when the check is run too soon before the page loads - Logger.trace(`failed with NoSuchWindow exception. Attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - const visibleWebElement: WebElement = await this.driver.wait(until.elementIsVisible(element), polling); - Logger.trace('element is located and is visible.'); - return visibleWebElement; - } catch (err) { - if (err instanceof error.TimeoutError) { - if (attempts !== 1) { // waitVisibility was spamming other methods when the number of attempts was 1 - only show message if attempts > 1 - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - } - continue; - } - - if (err instanceof error.StaleElementReferenceError) { - Logger.debug(`stale element error - ${err}`); - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum visibility checking attempts for '${elementLocator}' element, timeouted after ${timeout}`); + throw new error.TimeoutError(`Exceeded maximum presence checkings attempts, problems with 'StaleElementReferenceError' of '${elementLocator}' element`); + } + + async waitAllVisibility(locators: Array, timeout: number): Promise { + Logger.trace(`${locators}`); + + for (const elementLocator of locators) { + await this.waitVisibility(elementLocator, timeout); } + } + + async waitDisappearance(elementLocator: By, + attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, + polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { - async waitPresence(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); + Logger.trace(`${elementLocator}`); - Logger.trace(`${elementLocator}`); + const isDisappeared: boolean = await this.waitDisappearanceBoolean(elementLocator, attempts, polling); - for (let i: number = 0; i < attempts; i++) { - try { - return await this.driver.wait(until.elementLocated(elementLocator), polling); - } catch (err) { - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } + if (!isDisappeared) { + throw new error.TimeoutError(`Waiting attempts exceeded, element '${elementLocator}' is still visible`); + } + } - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } + async waitDisappearanceWithTimeout(elementLocator: By, timeout: number): Promise { + Logger.trace(`${elementLocator}`); - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } + await this.getDriver().wait(async () => { + const isVisible: boolean = await this.isVisible(elementLocator); + + if (!isVisible) { + return true; + } + }, timeout); + } + + async waitAllDisappearance(locators: Array, + attemptsPerLocator: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, + pollingPerLocator: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { - throw new error.TimeoutError(`Exceeded maximum presence checking attempts, problems with 'StaleElementReferenceError' of '${elementLocator}' element`); + Logger.trace(`${locators}`); + + for (const elementLocator of locators) { + await this.waitDisappearance(elementLocator, attemptsPerLocator, pollingPerLocator); } + } + + async waitAndClick(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); - async waitAllPresence(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise> { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); + Logger.trace(`${elementLocator}`); - Logger.trace(`${elementLocator}`); + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitVisibility(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } - for (let i: number = 0; i < attempts; i++) { - try { - return await this.driver.wait(until.elementsLocated(elementLocator), polling); - } catch (err) { - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } + try { + await element.click(); + return; + } catch (err) { + function isElementClickInterceptedOnLastAttempt(err: Error, i: number): boolean { + return err instanceof error.ElementClickInterceptedError && i === attempts - 1; } - throw new error.TimeoutError(`Exceeded maximum presence checkings attempts, problems with 'StaleElementReferenceError' of '${elementLocator}' element`); + if (err instanceof error.StaleElementReferenceError || err instanceof error.ElementClickInterceptedError) { + Logger.debug(`${elementLocator} - ${err}`); + await this.wait(polling); + continue; + } + + if (isElementClickInterceptedOnLastAttempt(err, i)) { + Logger.debug(`element is not clickable, try to perform pointer click`); + await this.getAction() + .move({ + origin: await this.waitPresence(elementLocator) + }) + .click() + .perform(); + return; + } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async waitAllVisibility(locators: Array, timeout: number): Promise { - Logger.trace(`${locators}`); + throw new error.TimeoutError(`Exceeded maximum clicking attempts, the '${elementLocator}' element is not clickable`); + } + + async waitAndGetElementAttribute(elementLocator: By, attribute: string, + timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); + + Logger.trace(`${elementLocator} attribute: '${attribute}'`); + + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitVisibility(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } + + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } - for (const elementLocator of locators) { - await this.waitVisibility(elementLocator, timeout); + try { + return await element.getAttribute(attribute); + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async waitDisappearance(elementLocator: By, - attempts: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, - polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { + throw new error.TimeoutError(`Exceeded maximum gettin of the '${attribute}' attribute attempts, from the '${elementLocator}' element`); + } + + async waitAndGetCssValue(elementLocator: By, cssAttribute: string, + timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); + + Logger.trace(`${elementLocator} cssAttribute: ${cssAttribute}`); - Logger.trace(`${elementLocator}`); + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitVisibility(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } + + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } - const isDisappeared: boolean = await this.waitDisappearanceBoolean(elementLocator, attempts, polling); + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } - if (!isDisappeared) { - throw new error.TimeoutError(`Waiting attempts exceeded, element '${elementLocator}' is still visible`); + try { + return await element.getCssValue(cssAttribute); + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async waitDisappearanceWithTimeout(elementLocator: By, timeout: number): Promise { - Logger.trace(`${elementLocator}`); + throw new error.TimeoutError(`Exceeded maximum gettin of the '${cssAttribute}' css attribute attempts, from the '${elementLocator}' element`); + } + + async waitAttributeValue(elementLocator: By, + attribute: string, + expectedValue: string, + timeout: number): Promise { + + Logger.trace(`${elementLocator}`); + + await this.driver.wait(async () => { + const attributeValue: string = await this.waitAndGetElementAttribute(elementLocator, attribute, timeout); - await this.getDriver().wait(async () => { - const isVisible: boolean = await this.isVisible(elementLocator); + return expectedValue === attributeValue; + }, + timeout, + `The '${attribute}' attribute value doesn't match with expected value '${expectedValue}'`); + } - if (!isVisible) { - return true; - } - }, timeout); + async type(elementLocator: By, text: string, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); + + if (elementLocator.toString().toLocaleLowerCase().includes('password')) { + Logger.trace(`${elementLocator} text: ***`); + } else { + Logger.trace(`${elementLocator} text: ${text}`); } - async waitAllDisappearance(locators: Array, - attemptsPerLocator: number = TimeoutConstants.TS_SELENIUM_DEFAULT_ATTEMPTS, - pollingPerLocator: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING): Promise { + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitVisibility(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } - Logger.trace(`${locators}`); + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } - for (const elementLocator of locators) { - await this.waitDisappearance(elementLocator, attemptsPerLocator, pollingPerLocator); + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } + + try { + await element.sendKeys(text); + return; + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; } - } - async waitAndClick(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator}`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitVisibility(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - await element.click(); - return; - } catch (err) { - function isElementClickInterceptedOnLastAttempt(err: Error, i: number): boolean { - return err instanceof error.ElementClickInterceptedError && i === attempts - 1; - } - - if (err instanceof error.StaleElementReferenceError || err instanceof error.ElementClickInterceptedError) { - Logger.debug(`${elementLocator} - ${err}`); - await this.wait(polling); - continue; - } - - if (isElementClickInterceptedOnLastAttempt(err, i)) { - Logger.debug(`element is not clickable, try to perform pointer click`); - await this.getAction() - .move({ - origin: await this.waitPresence(elementLocator) - }) - .click() - .perform(); - return; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum clicking attempts, the '${elementLocator}' element is not clickable`); + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async waitAndGetElementAttribute(elementLocator: By, attribute: string, - timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator} attribute: '${attribute}'`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitVisibility(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - return await element.getAttribute(attribute); - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum gettin of the '${attribute}' attribute attempts, from the '${elementLocator}' element`); - } + throw new error.TimeoutError(`Exceeded maximum typing attempts, to the '${elementLocator}' element`); + } - async waitAndGetCssValue(elementLocator: By, cssAttribute: string, - timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator} cssAttribute: ${cssAttribute}`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitVisibility(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - return await element.getCssValue(cssAttribute); - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum gettin of the '${cssAttribute}' css attribute attempts, from the '${elementLocator}' element`); - } + async typeToInvisible(elementLocator: By, text: string, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); - async waitAttributeValue(elementLocator: By, - attribute: string, - expectedValue: string, - timeout: number): Promise { + Logger.trace(`${elementLocator} text: ${text}`); - Logger.trace(`${elementLocator}`); + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitPresence(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } - await this.driver.wait(async () => { - const attributeValue: string = await this.waitAndGetElementAttribute(elementLocator, attribute, timeout); + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } - return expectedValue === attributeValue; - }, - timeout, - `The '${attribute}' attribute value doesn't match with expected value '${expectedValue}'`); - } + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } + + try { + await element.sendKeys(text); + return; + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; + } - async type(elementLocator: By, text: string, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - if (elementLocator.toString().toLocaleLowerCase().includes('password')) { - Logger.trace(`${elementLocator} text: ***`); - } else { - Logger.trace(`${elementLocator} text: ${text}`); - } - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitVisibility(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - await element.sendKeys(text); - return; - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum typing attempts, to the '${elementLocator}' element`); + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async typeToInvisible(elementLocator: By, text: string, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator} text: ${text}`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitPresence(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - await element.sendKeys(text); - return; - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum typing attempts, to the '${elementLocator}' element`); - } + throw new error.TimeoutError(`Exceeded maximum typing attempts, to the '${elementLocator}' element`); + } - async clear(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator}`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitVisibility(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - await element.clear(); - return; - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum clearing attempts, to the '${elementLocator}' element`); - } + async clear(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); - async clearInvisible(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator}`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitPresence(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - await element.clear(); - return; - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum clearing attempts, to the '${elementLocator}' element`); - } + Logger.trace(`${elementLocator}`); - async enterValue(elementLocator: By, text: string, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - if (elementLocator.toString().toLocaleLowerCase().includes('password')) { - Logger.trace(`${elementLocator} text: ***`); - } else { - Logger.trace(`${elementLocator} text: ${text}`); + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitVisibility(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; } - await this.waitVisibility(elementLocator, timeout); - await this.clear(elementLocator); - await this.waitAttributeValue(elementLocator, 'value', '', timeout); - await this.type(elementLocator, text, timeout); - await this.waitAttributeValue(elementLocator, 'value', text, timeout); - } + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } - async waitAndSwitchToFrame(iframeLocator: By, timeout: number): Promise { - Logger.trace(`${iframeLocator}`); + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } + + try { + await element.clear(); + return; + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; + } - await this.driver.wait(until.ableToSwitchToFrame(iframeLocator), timeout); + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async waitAndGetText(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator}`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitVisibility(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - return await element.getText(); - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum text obtaining attempts, from the '${elementLocator}' element`); - } + throw new error.TimeoutError(`Exceeded maximum clearing attempts, to the '${elementLocator}' element`); + } - async waitAndGetValue(elementLocator: By, timeout: number): Promise { - Logger.trace(`${elementLocator}`); + async clearInvisible(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); - return await this.waitAndGetElementAttribute(elementLocator, 'value', timeout); - } + Logger.trace(`${elementLocator}`); - async waitUntilTrue(callback: any, timeout: number): Promise { - Logger.trace(); + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitPresence(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } - await this.driver.wait(callback, timeout); - } + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } - async scrollTo(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - const attempts: number = Math.ceil(timeout / polling); - - Logger.trace(`${elementLocator}`); - - for (let i: number = 0; i < attempts; i++) { - let element: WebElement; - try { - element = await this.waitPresence(elementLocator, polling); - } catch (err) { - if (i >= attempts - 1) { - Logger.error(`failed with exception, out of attempts - ${err}`); - throw err; - } - - if (err instanceof error.TimeoutError) { - Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - - try { - await this.getDriver() - .executeScript('arguments[0].scrollIntoView(true);', element); - return; - } catch (err) { - if (err instanceof error.StaleElementReferenceError) { - await this.wait(polling); - continue; - } - - Logger.error(`failed with an unexpected exception - ${err}`); - throw err; - } - } - - throw new error.TimeoutError(`Exceeded maximum mouse move attempts, for the '${elementLocator}' element`); - } + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } + + try { + await element.clear(); + return; + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; + } - async scrollToAndClick(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - await this.scrollTo(elementLocator, timeout); - await this.waitAndClick(elementLocator, timeout); + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - async scrollToAndEnterValue(elementLocator: By, value: string, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { - await this.scrollTo(elementLocator, timeout); - await this.enterValue(elementLocator, value, timeout); + throw new error.TimeoutError(`Exceeded maximum clearing attempts, to the '${elementLocator}' element`); + } + + async enterValue(elementLocator: By, text: string, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + if (elementLocator.toString().toLocaleLowerCase().includes('password')) { + Logger.trace(`${elementLocator} text: ***`); + } else { + Logger.trace(`${elementLocator} text: ${text}`); } - // method is useful to debug page object elements - async highLightElement(element: WebElement): Promise { - await this.getDriver().executeScript('arguments[0].style.border=\'2px solid red\'', element); + await this.waitVisibility(elementLocator, timeout); + await this.clear(elementLocator); + await this.waitAttributeValue(elementLocator, 'value', '', timeout); + await this.type(elementLocator, text, timeout); + await this.waitAttributeValue(elementLocator, 'value', text, timeout); + } + + async waitAndSwitchToFrame(iframeLocator: By, timeout: number): Promise { + Logger.trace(`${iframeLocator}`); + + await this.driver.wait(until.ableToSwitchToFrame(iframeLocator), timeout); + } + + async waitAndGetText(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); + + Logger.trace(`${elementLocator}`); + + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitVisibility(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } + + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } + + try { + return await element.getText(); + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; + } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } - getDriver(): ThenableWebDriver { - Logger.trace(); + throw new error.TimeoutError(`Exceeded maximum text obtaining attempts, from the '${elementLocator}' element`); + } + + async waitAndGetValue(elementLocator: By, timeout: number): Promise { + Logger.trace(`${elementLocator}`); + + return await this.waitAndGetElementAttribute(elementLocator, 'value', timeout); + } + + async waitUntilTrue(callback: any, timeout: number): Promise { + Logger.trace(); + + await this.driver.wait(callback, timeout); + } - return this.driver; + async scrollTo(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + const polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + const attempts: number = Math.ceil(timeout / polling); + + Logger.trace(`${elementLocator}`); + + for (let i: number = 0; i < attempts; i++) { + let element: WebElement; + try { + element = await this.waitPresence(elementLocator, polling); + } catch (err) { + if (i >= attempts - 1) { + Logger.error(`failed with exception, out of attempts - ${err}`); + throw err; + } + + if (err instanceof error.TimeoutError) { + Logger.trace(`polling timed out attempt #${(i + 1)}, retrying with ${polling}ms timeout`); + continue; + } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } + + try { + await this.getDriver() + .executeScript('arguments[0].scrollIntoView(true);', element); + return; + } catch (err) { + if (err instanceof error.StaleElementReferenceError) { + await this.wait(polling); + continue; + } + + Logger.error(`failed with an unexpected exception - ${err}`); + throw err; + } } + + throw new error.TimeoutError(`Exceeded maximum mouse move attempts, for the '${elementLocator}' element`); + } + + async scrollToAndClick(elementLocator: By, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + await this.scrollTo(elementLocator, timeout); + await this.waitAndClick(elementLocator, timeout); + } + + async scrollToAndEnterValue(elementLocator: By, value: string, timeout: number = TimeoutConstants.TS_SELENIUM_CLICK_ON_VISIBLE_ITEM): Promise { + await this.scrollTo(elementLocator, timeout); + await this.enterValue(elementLocator, value, timeout); + } + + // method is useful to debug page object elements + async highLightElement(element: WebElement): Promise { + await this.getDriver().executeScript('arguments[0].style.border=\'2px solid red\'', element); + } + + getDriver(): ThenableWebDriver { + Logger.trace(); + + return this.driver; + } } diff --git a/tests/e2e/utils/KubernetesCommandLineToolsExecutor.ts b/tests/e2e/utils/KubernetesCommandLineToolsExecutor.ts index e959759ac7f..41d5dd623e2 100644 --- a/tests/e2e/utils/KubernetesCommandLineToolsExecutor.ts +++ b/tests/e2e/utils/KubernetesCommandLineToolsExecutor.ts @@ -35,7 +35,8 @@ export class KubernetesCommandLineToolsExecutor extends ShellExecutor { const url: string = this.getServerUrl(); if (this.isUserLoggedIn()) { Logger.debug(`${this.KUBERNETES_COMMAND_LINE_TOOL} - user already logged`); - } else {Logger.debug(`${this.KUBERNETES_COMMAND_LINE_TOOL} - login ${url}, ${OAuthConstants.TS_SELENIUM_OCP_USERNAME}`); + } else { + Logger.debug(`${this.KUBERNETES_COMMAND_LINE_TOOL} - login ${url}, ${OAuthConstants.TS_SELENIUM_OCP_USERNAME}`); exec(`oc login --server=${url} -u=${OAuthConstants.TS_SELENIUM_OCP_USERNAME} -p=${OAuthConstants.TS_SELENIUM_OCP_PASSWORD} --insecure-skip-tls-verify`); } } else { diff --git a/tests/e2e/utils/ScreenCatcher.ts b/tests/e2e/utils/ScreenCatcher.ts index 77f6530d77b..24f65fbd83c 100644 --- a/tests/e2e/utils/ScreenCatcher.ts +++ b/tests/e2e/utils/ScreenCatcher.ts @@ -8,67 +8,67 @@ * SPDX-License-Identifier: EPL-2.0 **********************************************************************/ import * as fs from 'fs'; -import { injectable, inject } from 'inversify'; +import { WriteStream } from 'fs'; +import { inject, injectable } from 'inversify'; import { CLASSES } from '../configs/inversify.types'; import { DriverHelper } from './DriverHelper'; import { error } from 'selenium-webdriver'; -import { WriteStream } from 'fs'; import { StringUtil } from './StringUtil'; import { ReporterConstants } from '../constants/ReporterConstants'; @injectable() export class ScreenCatcher { - constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } + constructor(@inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper) { } - async catchMethodScreen(methodName: string, methodIndex: number, screenshotIndex: number): Promise { - const executionScreenCastDir: string = `${ReporterConstants.TS_SELENIUM_REPORT_FOLDER}/executionScreencast`; - const executionScreenCastErrorsDir: string = `${ReporterConstants.TS_SELENIUM_REPORT_FOLDER}/executionScreencastErrors`; - const formattedMethodIndex: string = new Intl.NumberFormat('en-us', { minimumIntegerDigits: 3 }).format(methodIndex); - const formattedScreenshotIndex: string = new Intl.NumberFormat('en-us', { minimumIntegerDigits: 5 }).format(screenshotIndex).replace(/,/g, ''); + async catchMethodScreen(methodName: string, methodIndex: number, screenshotIndex: number): Promise { + const executionScreenCastDir: string = `${ReporterConstants.TS_SELENIUM_REPORT_FOLDER}/executionScreencast`; + const executionScreenCastErrorsDir: string = `${ReporterConstants.TS_SELENIUM_REPORT_FOLDER}/executionScreencastErrors`; + const formattedMethodIndex: string = new Intl.NumberFormat('en-us', { minimumIntegerDigits: 3 }).format(methodIndex); + const formattedScreenshotIndex: string = new Intl.NumberFormat('en-us', { minimumIntegerDigits: 5 }).format(screenshotIndex).replace(/,/g, ''); - if (!fs.existsSync(ReporterConstants.TS_SELENIUM_REPORT_FOLDER)) { - fs.mkdirSync(ReporterConstants.TS_SELENIUM_REPORT_FOLDER); - } + if (!fs.existsSync(ReporterConstants.TS_SELENIUM_REPORT_FOLDER)) { + fs.mkdirSync(ReporterConstants.TS_SELENIUM_REPORT_FOLDER); + } - if (!fs.existsSync(executionScreenCastDir)) { - fs.mkdirSync(executionScreenCastDir); - } + if (!fs.existsSync(executionScreenCastDir)) { + fs.mkdirSync(executionScreenCastDir); + } - const date: Date = new Date(); - const timeStr: string = date.toLocaleTimeString('en-us', { hour12: false }) + '.' + new Intl.NumberFormat('en-us', { minimumIntegerDigits: 3 }).format(date.getMilliseconds()); + const date: Date = new Date(); + const timeStr: string = date.toLocaleTimeString('en-us', { hour12: false }) + '.' + new Intl.NumberFormat('en-us', { minimumIntegerDigits: 3 }).format(date.getMilliseconds()); - const screenshotPath: string = `${executionScreenCastDir}/${formattedMethodIndex}-${formattedScreenshotIndex}--(${StringUtil.sanitizeTitle(timeStr)})_${StringUtil.sanitizeTitle(methodName)}.png`; + const screenshotPath: string = `${executionScreenCastDir}/${formattedMethodIndex}-${formattedScreenshotIndex}--(${StringUtil.sanitizeTitle(timeStr)})_${StringUtil.sanitizeTitle(methodName)}.png`; - try { - await this.catchScreen(screenshotPath); - } catch (err) { - if (!fs.existsSync(executionScreenCastErrorsDir)) { - fs.mkdirSync(executionScreenCastErrorsDir); - } + try { + await this.catchScreen(screenshotPath); + } catch (err) { + if (!fs.existsSync(executionScreenCastErrorsDir)) { + fs.mkdirSync(executionScreenCastErrorsDir); + } - let errorLogFilePath: string = screenshotPath.replace('.png', '.txt'); - errorLogFilePath = errorLogFilePath.replace(executionScreenCastDir, executionScreenCastErrorsDir); - if (err instanceof error.IError) { - await this.writeErrorLog(errorLogFilePath, err); - } - } + let errorLogFilePath: string = screenshotPath.replace('.png', '.txt'); + errorLogFilePath = errorLogFilePath.replace(executionScreenCastDir, executionScreenCastErrorsDir); + if (err instanceof error.IError) { + await this.writeErrorLog(errorLogFilePath, err); + } } + } - async catchScreen(screenshotPath: string): Promise { - const screenshot: string = await this.driverHelper.getDriver().takeScreenshot(); - const screenshotStream: WriteStream = fs.createWriteStream(screenshotPath); - screenshotStream.write(Buffer.from(screenshot, 'base64')); - screenshotStream.end(); - } + async catchScreen(screenshotPath: string): Promise { + const screenshot: string = await this.driverHelper.getDriver().takeScreenshot(); + const screenshotStream: WriteStream = fs.createWriteStream(screenshotPath); + screenshotStream.write(Buffer.from(screenshot, 'base64')); + screenshotStream.end(); + } - async writeErrorLog(errorLogPath: string, err: error.IError): Promise { - console.log(`Failed to save screenshot, additional information in the ${errorLogPath}`); + async writeErrorLog(errorLogPath: string, err: error.IError): Promise { + console.log(`Failed to save screenshot, additional information in the ${errorLogPath}`); - if (err.stack) { - const screenshotStream: WriteStream = fs.createWriteStream(errorLogPath); - screenshotStream.write(Buffer.from(err.stack, 'utf8')); - screenshotStream.end(); - } + if (err.stack) { + const screenshotStream: WriteStream = fs.createWriteStream(errorLogPath); + screenshotStream.write(Buffer.from(err.stack, 'utf8')); + screenshotStream.end(); } + } } diff --git a/tests/e2e/utils/ShellExecutor.ts b/tests/e2e/utils/ShellExecutor.ts index ff6613b531a..d189ba61311 100644 --- a/tests/e2e/utils/ShellExecutor.ts +++ b/tests/e2e/utils/ShellExecutor.ts @@ -2,16 +2,16 @@ import { echo, exec, ShellString } from 'shelljs'; export class ShellExecutor { - static wait(seconds: number): void { - this.execWithLog(`sleep ${seconds}s`); - } + static wait(seconds: number): void { + this.execWithLog(`sleep ${seconds}s`); + } - static curl(link: string): ShellString { - return this.execWithLog(`curl -k ${link}`); - } + static curl(link: string): ShellString { + return this.execWithLog(`curl -k ${link}`); + } - protected static execWithLog(command: string): ShellString { - echo(command); - return exec(command); - } + protected static execWithLog(command: string): ShellString { + echo(command); + return exec(command); + } } diff --git a/tests/e2e/utils/StringUtil.ts b/tests/e2e/utils/StringUtil.ts index d64a11292be..421068da7c8 100644 --- a/tests/e2e/utils/StringUtil.ts +++ b/tests/e2e/utils/StringUtil.ts @@ -13,37 +13,37 @@ import { Logger } from './Logger'; @injectable() export class StringUtil { - /** - * Method extracts a test repo name from git clone https url; - * it splits the url into string[] by "/" or ".", deletes empty elements and elements that contains just "git", "main" or "tree" word, than returns the last one; - * please, avoid to call the test repo as just "git" or to use dots in the name, like: github.com/user/git.git, github.com/user/name.with.dots. - * @param url git https url (which using for "git clone") - * @return project name - */ - static getProjectNameFromGitUrl(url: string): string { - Logger.debug(`${url}`); - if (url.includes('?')) { - url = url.substring(0, url.indexOf('?')); - } - if (url.includes('/tree/')) { - url = url.split('/').slice(0, -2).join('/'); - } - const projectName: string = url.split(/[\/.]/).filter((e: string) => !['git', ''].includes(e)).reverse()[0]; - Logger.debug(`${projectName}`); - return projectName; + /** + * Method extracts a test repo name from git clone https url; + * it splits the url into string[] by "/" or ".", deletes empty elements and elements that contains just "git", "main" or "tree" word, than returns the last one; + * please, avoid to call the test repo as just "git" or to use dots in the name, like: github.com/user/git.git, github.com/user/name.with.dots. + * @param url git https url (which using for "git clone") + * @return project name + */ + static getProjectNameFromGitUrl(url: string): string { + Logger.debug(`${url}`); + if (url.includes('?')) { + url = url.substring(0, url.indexOf('?')); } - - static sanitizeTitle(arg: string): string { - return arg.replace(/\//g, '+').replace(/,/g, '.').replace(/:/g, '-').replace(/['"]/g, '').replace(/[^a-z0-9+\-.()\[\]_]/gi, '_'); + if (url.includes('/tree/')) { + url = url.split('/').slice(0, -2).join('/'); } + const projectName: string = url.split(/[\/.]/).filter((e: string) => !['git', ''].includes(e)).reverse()[0]; + Logger.debug(`${projectName}`); + return projectName; + } - /** - * Replaces ${ENV}, $ENV to "$ENV" - * @param command string command with environmental variables in unsupported format - * @return updated command with environmental variables in supported format - */ + static sanitizeTitle(arg: string): string { + return arg.replace(/\//g, '+').replace(/,/g, '.').replace(/:/g, '-').replace(/['"]/g, '').replace(/[^a-z0-9+\-.()\[\]_]/gi, '_'); + } - static updateCommandEnvsToShStyle(command: string): string { - return command.replace(/[{}]/g, '').replace(/(? { - try { - let request_censored: AxiosRequestConfig = JSON.parse(JSON.stringify(request)); - if (request_censored === undefined) { - Logger.error('JSON.parse returned an undefined object, cannot process request'); - return request; - } - if (request_censored.headers === undefined) { - Logger.warn('request does not contain any headers object'); - return request; - } - request_censored.headers.Authorization = 'CENSORED'; - request_censored.headers.Cookie = 'CENSORED'; - Logger.info(`request:\n` + request_censored); - } catch (err) { - Logger.error(`request: Failed to deep clone AxiosRequestConfig:` + err); - } - return request; - }); - } + /** + * This method adds a request interceptor into axios request interceptors list and returns an ID of the interceptor + */ + static enableRequestInterceptor(): number { + Logger.debug(); + return axios.interceptors.request.use(request => { + try { + let request_censored: AxiosRequestConfig = JSON.parse(JSON.stringify(request)); + if (request_censored === undefined) { + Logger.error('JSON.parse returned an undefined object, cannot process request'); + return request; + } + if (request_censored.headers === undefined) { + Logger.warn('request does not contain any headers object'); + return request; + } + request_censored.headers.Authorization = 'CENSORED'; + request_censored.headers.Cookie = 'CENSORED'; + Logger.info(`request:\n` + request_censored); + } catch (err) { + Logger.error(`request: Failed to deep clone AxiosRequestConfig:` + err); + } + return request; + }); + } - /** - * This method adds a response interceptor into axios response interceptors list and returns an ID of the interceptor - */ - static enableResponseInterceptor(): number { - Logger.debug(); - return axios.interceptors.response.use( response => { - try { - let response_censored: AxiosResponse = JSON.parse(JSON.stringify(response, (key, value) => { - switch (key) { - case 'request': return 'CENSORED'; - default: return value; - } - })); - if (response_censored === undefined) { - Logger.error('JSON.parse returned an undefined object, cannot process response'); - return response; - } - if (response_censored.config === undefined) { - Logger.warn('response does not contain any config object'); - return response; - } - if (response_censored.config.headers === undefined) { - Logger.warn('response does not contain any config.headers object'); - return response; - } - response_censored.config.headers.Authorization = 'CENSORED'; - response_censored.config.headers.Cookie = 'CENSORED'; - if (response_censored.data.access_token !== null) { - response_censored.data.access_token = 'CENSORED'; - } - if (response_censored.data.refresh_token !== null) { - response_censored.data.refresh_token = 'CENSORED'; - } - Logger.info(`response:\n` + response_censored); - } catch (err) { - Logger.error(`response: Failed to deep clone AxiosResponse:` + err); - } - return response; - }); - } + /** + * This method adds a response interceptor into axios response interceptors list and returns an ID of the interceptor + */ + static enableResponseInterceptor(): number { + Logger.debug(); + return axios.interceptors.response.use(response => { + try { + let response_censored: AxiosResponse = JSON.parse(JSON.stringify(response, (key, value) => { + switch (key) { + case 'request': + return 'CENSORED'; + default: + return value; + } + })); + if (response_censored === undefined) { + Logger.error('JSON.parse returned an undefined object, cannot process response'); + return response; + } + if (response_censored.config === undefined) { + Logger.warn('response does not contain any config object'); + return response; + } + if (response_censored.config.headers === undefined) { + Logger.warn('response does not contain any config.headers object'); + return response; + } + response_censored.config.headers.Authorization = 'CENSORED'; + response_censored.config.headers.Cookie = 'CENSORED'; + if (response_censored.data.access_token !== null) { + response_censored.data.access_token = 'CENSORED'; + } + if (response_censored.data.refresh_token !== null) { + response_censored.data.refresh_token = 'CENSORED'; + } + Logger.info(`response:\n` + response_censored); + } catch (err) { + Logger.error(`response: Failed to deep clone AxiosResponse:` + err); + } + return response; + }); + } - constructor(@inject(TYPES.IAuthorizationHeaderHandler) private readonly headerHandler: IAuthorizationHeaderHandler) { } + constructor(@inject(TYPES.IAuthorizationHeaderHandler) private readonly headerHandler: IAuthorizationHeaderHandler) { } - async get(relativeUrl: string): Promise { - return await axios.get(this.assembleUrl(relativeUrl), await this.headerHandler.get()); - } + async get(relativeUrl: string): Promise { + return await axios.get(this.assembleUrl(relativeUrl), await this.headerHandler.get()); + } - async post(relativeUrl: string, data?: string | any ): Promise { - return await axios.post(this.assembleUrl(relativeUrl), data, await this.headerHandler.get()); - } + async post(relativeUrl: string, data?: string | any): Promise { + return await axios.post(this.assembleUrl(relativeUrl), data, await this.headerHandler.get()); + } - async delete(relativeUrl: string): Promise { - return await axios.delete(this.assembleUrl(relativeUrl), await this.headerHandler.get()); - } + async delete(relativeUrl: string): Promise { + return await axios.delete(this.assembleUrl(relativeUrl), await this.headerHandler.get()); + } - async patch(relativeUrl: string, patchParams: object): Promise { - return await axios.patch(this.assembleUrl(relativeUrl), patchParams, await this.headerHandler.get()); - } + async patch(relativeUrl: string, patchParams: object): Promise { + return await axios.patch(this.assembleUrl(relativeUrl), patchParams, await this.headerHandler.get()); + } - private assembleUrl(relativeUrl: string): string { - return `${BaseTestConstants.TS_SELENIUM_BASE_URL}/${relativeUrl}`; - } + private assembleUrl(relativeUrl: string): string { + return `${BaseTestConstants.TS_SELENIUM_BASE_URL}/${relativeUrl}`; + } } diff --git a/tests/e2e/utils/request-handlers/headers/IAuthorizationHeaderHandler.ts b/tests/e2e/utils/request-handlers/headers/IAuthorizationHeaderHandler.ts index 6f81e5a48c1..4172e323b63 100644 --- a/tests/e2e/utils/request-handlers/headers/IAuthorizationHeaderHandler.ts +++ b/tests/e2e/utils/request-handlers/headers/IAuthorizationHeaderHandler.ts @@ -11,5 +11,5 @@ import { AxiosRequestConfig } from 'axios'; export interface IAuthorizationHeaderHandler { - get(): Promise; + get(): Promise; } diff --git a/tests/e2e/utils/workspace/ApiUrlResolver.ts b/tests/e2e/utils/workspace/ApiUrlResolver.ts index 3ce98aa3de4..b7d42bda392 100644 --- a/tests/e2e/utils/workspace/ApiUrlResolver.ts +++ b/tests/e2e/utils/workspace/ApiUrlResolver.ts @@ -15,33 +15,33 @@ import { AxiosResponse } from 'axios'; @injectable() export class ApiUrlResolver { - private static readonly DASHBOARD_API_URL: string = 'dashboard/api/namespace'; - private static readonly KUBERNETES_API_URL: string = 'api/kubernetes/namespace'; + private static readonly DASHBOARD_API_URL: string = 'dashboard/api/namespace'; + private static readonly KUBERNETES_API_URL: string = 'api/kubernetes/namespace'; - private userNamespace: string = ''; + private userNamespace: string = ''; - constructor(@inject(CLASSES.CheApiRequestHandler) private readonly processRequestHandler: CheApiRequestHandler) {} + constructor(@inject(CLASSES.CheApiRequestHandler) private readonly processRequestHandler: CheApiRequestHandler) {} - async getWorkspaceApiUrl(workspaceName: string): Promise { - return `${await this.getWorkspacesApiUrl()}/${workspaceName}`; - } + async getWorkspaceApiUrl(workspaceName: string): Promise { + return `${await this.getWorkspacesApiUrl()}/${workspaceName}`; + } - async getWorkspacesApiUrl(): Promise { - const namespace: string = await this.obtainUserNamespace(); - return `${ApiUrlResolver.DASHBOARD_API_URL}/${namespace}/devworkspaces`; - } + async getWorkspacesApiUrl(): Promise { + const namespace: string = await this.obtainUserNamespace(); + return `${ApiUrlResolver.DASHBOARD_API_URL}/${namespace}/devworkspaces`; + } - private async obtainUserNamespace(): Promise { - Logger.debug(`${this.userNamespace}`); - if (this.userNamespace.length === 0) { - Logger.trace(`USER_NAMESPACE.length = 0, calling kubernetes API`); - const kubernetesResponse: AxiosResponse = await this.processRequestHandler.get(ApiUrlResolver.KUBERNETES_API_URL); - if (kubernetesResponse.status !== 200) { - throw new Error(`Cannot get user namespace from kubernetes API. Code: ${kubernetesResponse.status} Data: ${kubernetesResponse.data}`); - } - this.userNamespace = kubernetesResponse.data[0].name; - Logger.debug(`kubeapi success: ${this.userNamespace}`); - } - return this.userNamespace; + private async obtainUserNamespace(): Promise { + Logger.debug(`${this.userNamespace}`); + if (this.userNamespace.length === 0) { + Logger.trace(`USER_NAMESPACE.length = 0, calling kubernetes API`); + const kubernetesResponse: AxiosResponse = await this.processRequestHandler.get(ApiUrlResolver.KUBERNETES_API_URL); + if (kubernetesResponse.status !== 200) { + throw new Error(`Cannot get user namespace from kubernetes API. Code: ${kubernetesResponse.status} Data: ${kubernetesResponse.data}`); + } + this.userNamespace = kubernetesResponse.data[0].name; + Logger.debug(`kubeapi success: ${this.userNamespace}`); } + return this.userNamespace; + } } diff --git a/tests/e2e/utils/workspace/ITestWorkspaceUtil.ts b/tests/e2e/utils/workspace/ITestWorkspaceUtil.ts index 29d6f923664..1426fda1af1 100644 --- a/tests/e2e/utils/workspace/ITestWorkspaceUtil.ts +++ b/tests/e2e/utils/workspace/ITestWorkspaceUtil.ts @@ -11,33 +11,33 @@ import { WorkspaceStatus } from './WorkspaceStatus'; export interface ITestWorkspaceUtil { - waitWorkspaceStatus(namespace: string, workspaceName: string, expectedWorkspaceStatus: WorkspaceStatus): void; - - stopWorkspaceByName(workspaceName: string): void; - - /** - * Delete a workspace without stopping phase (similar with force deleting) - */ - deleteWorkspaceByName(workspaceName: string): void; - - /** - * Stop workspace before deleting with checking stopping phase - */ - stopAndDeleteWorkspaceByName(workspaceName: string): void; - - /** - * Stop all run workspaces in the namespace - */ - stopAllRunningWorkspaces(namespace: string): void; - - /** - * Stop all run workspaces, check statused and remove the workspaces - */ - stopAndDeleteAllRunningWorkspaces(namespace: string): void; - - /** - * Stop all run workspaces without stopping and waiting for of 'Stopped' phase - * Similar with 'force' deleting - */ - deleteAllWorkspaces(namespace: string): void; + waitWorkspaceStatus(namespace: string, workspaceName: string, expectedWorkspaceStatus: WorkspaceStatus): void; + + stopWorkspaceByName(workspaceName: string): void; + + /** + * Delete a workspace without stopping phase (similar with force deleting) + */ + deleteWorkspaceByName(workspaceName: string): void; + + /** + * Stop workspace before deleting with checking stopping phase + */ + stopAndDeleteWorkspaceByName(workspaceName: string): void; + + /** + * Stop all run workspaces in the namespace + */ + stopAllRunningWorkspaces(namespace: string): void; + + /** + * Stop all run workspaces, check statused and remove the workspaces + */ + stopAndDeleteAllRunningWorkspaces(namespace: string): void; + + /** + * Stop all run workspaces without stopping and waiting for of 'Stopped' phase + * Similar with 'force' deleting + */ + deleteAllWorkspaces(namespace: string): void; } diff --git a/tests/e2e/utils/workspace/TestWorkspaceUtil.ts b/tests/e2e/utils/workspace/TestWorkspaceUtil.ts index a0b4c3f6b48..2df5c0b5152 100644 --- a/tests/e2e/utils/workspace/TestWorkspaceUtil.ts +++ b/tests/e2e/utils/workspace/TestWorkspaceUtil.ts @@ -9,7 +9,7 @@ **********************************************************************/ import 'reflect-metadata'; -import { injectable, inject } from 'inversify'; +import { inject, injectable } from 'inversify'; import { DriverHelper } from '../DriverHelper'; import { WorkspaceStatus } from './WorkspaceStatus'; import { error } from 'selenium-webdriver'; @@ -23,142 +23,146 @@ import { TimeoutConstants } from '../../constants/TimeoutConstants'; @injectable() export class TestWorkspaceUtil implements ITestWorkspaceUtil { - readonly polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; - readonly attempts: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT / this.polling; + readonly polling: number = TimeoutConstants.TS_SELENIUM_DEFAULT_POLLING; + readonly attempts: number = TimeoutConstants.TS_DASHBOARD_WORKSPACE_STOP_TIMEOUT / this.polling; - constructor( - @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper, - @inject(CLASSES.CheApiRequestHandler) private readonly processRequestHandler: CheApiRequestHandler, - @inject(CLASSES.ApiUrlResolver) private readonly apiUrlResolver: ApiUrlResolver - ) { } + constructor( + @inject(CLASSES.DriverHelper) private readonly driverHelper: DriverHelper, + @inject(CLASSES.CheApiRequestHandler) private readonly processRequestHandler: CheApiRequestHandler, + @inject(CLASSES.ApiUrlResolver) private readonly apiUrlResolver: ApiUrlResolver + ) { } - async waitWorkspaceStatus(workspaceName: string, expectedWorkspaceStatus: WorkspaceStatus): Promise { - Logger.debug(); + async waitWorkspaceStatus(workspaceName: string, expectedWorkspaceStatus: WorkspaceStatus): Promise { + Logger.debug(); - let workspaceStatus: string = ''; - let expectedStatus: boolean = false; - for (let i: number = 0; i < this.attempts; i++) { - const response: AxiosResponse = await this.processRequestHandler.get(await this.apiUrlResolver.getWorkspaceApiUrl(workspaceName)); + let workspaceStatus: string = ''; + let expectedStatus: boolean = false; + for (let i: number = 0; i < this.attempts; i++) { + const response: AxiosResponse = await this.processRequestHandler.get(await this.apiUrlResolver.getWorkspaceApiUrl(workspaceName)); - if (response.status !== 200) { - throw new Error(`Can not get status of a workspace. Code: ${response.status} Data: ${response.data}`); - } + if (response.status !== 200) { + throw new Error(`Can not get status of a workspace. Code: ${response.status} Data: ${response.data}`); + } - workspaceStatus = await response.data.status.phase; + workspaceStatus = await response.data.status.phase; - if (workspaceStatus === expectedWorkspaceStatus) { - expectedStatus = true; - break; - } + if (workspaceStatus === expectedWorkspaceStatus) { + expectedStatus = true; + break; + } - await this.driverHelper.wait(this.polling); - } - - if (!expectedStatus) { - let waitTime: number = this.attempts * this.polling; - throw new error.TimeoutError(`The workspace was not stopped in ${waitTime} ms. Current status is: ${workspaceStatus}`); - } + await this.driverHelper.wait(this.polling); } - async stopWorkspaceByName(workspaceName: string): Promise { - Logger.debug(`${workspaceName}`); - - const stopWorkspaceApiUrl: string = await this.apiUrlResolver.getWorkspaceApiUrl(workspaceName); - let stopWorkspaceResponse: AxiosResponse; - - try { - stopWorkspaceResponse = await this.processRequestHandler.patch(stopWorkspaceApiUrl, [{'op': 'replace', 'path': '/spec/started', 'value': false}]); - } catch (err) { - Logger.error(`stop workspace call failed. URL used: ${stopWorkspaceApiUrl}`); - throw err; - } - - if (stopWorkspaceResponse.status !== 200) { - throw new Error(`Cannot stop workspace. Code: ${stopWorkspaceResponse.status} Data: ${stopWorkspaceResponse.data}`); - } - - await this.waitWorkspaceStatus(workspaceName, WorkspaceStatus.STOPPED); - Logger.debug(`${workspaceName} stopped successfully`); + if (!expectedStatus) { + let waitTime: number = this.attempts * this.polling; + throw new error.TimeoutError(`The workspace was not stopped in ${waitTime} ms. Current status is: ${workspaceStatus}`); + } + } + + async stopWorkspaceByName(workspaceName: string): Promise { + Logger.debug(`${workspaceName}`); + + const stopWorkspaceApiUrl: string = await this.apiUrlResolver.getWorkspaceApiUrl(workspaceName); + let stopWorkspaceResponse: AxiosResponse; + + try { + stopWorkspaceResponse = await this.processRequestHandler.patch(stopWorkspaceApiUrl, [{ + 'op': 'replace', + 'path': '/spec/started', + 'value': false + }]); + } catch (err) { + Logger.error(`stop workspace call failed. URL used: ${stopWorkspaceApiUrl}`); + throw err; } - // delete a workspace without stopping phase (similar with force deleting) - async deleteWorkspaceByName(workspaceName: string): Promise { - Logger.debug(`${workspaceName}` ); - - const deleteWorkspaceApiUrl: string = await this.apiUrlResolver.getWorkspaceApiUrl(workspaceName); - let deleteWorkspaceResponse: AxiosResponse; - let deleteWorkspaceStatus: boolean = false; - try { - deleteWorkspaceResponse = await this.processRequestHandler.delete(deleteWorkspaceApiUrl); - } catch (error) { - if (axios.isAxiosError(error) && error.response?.status === 404) { - Logger.error(`the workspace :${workspaceName} not found`); - throw error; - } - Logger.error(`delete workspace call failed. URL used: ${deleteWorkspaceStatus}`); - throw error; - } - - if (deleteWorkspaceResponse.status !== 204) { - throw new Error(`Can not delete workspace. Code: ${deleteWorkspaceResponse.status} Data: ${deleteWorkspaceResponse.data}`); - } - - for (let i: number = 0; i < this.attempts; i++) { - try { - deleteWorkspaceResponse = await this.processRequestHandler.get(deleteWorkspaceApiUrl); - } catch (error) { - if (axios.isAxiosError(error) && error.response?.status === 404) { - deleteWorkspaceStatus = true; - Logger.debug(`${workspaceName} deleted successfully`); - break; - } - } - } - - if (!deleteWorkspaceStatus) { - let waitTime: number = this.attempts * this.polling; - throw new error.TimeoutError(`The workspace was not deleted in ${waitTime} ms.`); - } + if (stopWorkspaceResponse.status !== 200) { + throw new Error(`Cannot stop workspace. Code: ${stopWorkspaceResponse.status} Data: ${stopWorkspaceResponse.data}`); } - // stop workspace before deleting with checking stopping phase - async stopAndDeleteWorkspaceByName(workspaceName: string): Promise { - Logger.debug(); + await this.waitWorkspaceStatus(workspaceName, WorkspaceStatus.STOPPED); + Logger.debug(`${workspaceName} stopped successfully`); + } + + // delete a workspace without stopping phase (similar with force deleting) + async deleteWorkspaceByName(workspaceName: string): Promise { + Logger.debug(`${workspaceName}`); + + const deleteWorkspaceApiUrl: string = await this.apiUrlResolver.getWorkspaceApiUrl(workspaceName); + let deleteWorkspaceResponse: AxiosResponse; + let deleteWorkspaceStatus: boolean = false; + try { + deleteWorkspaceResponse = await this.processRequestHandler.delete(deleteWorkspaceApiUrl); + } catch (error) { + if (axios.isAxiosError(error) && error.response?.status === 404) { + Logger.error(`the workspace :${workspaceName} not found`); + throw error; + } + Logger.error(`delete workspace call failed. URL used: ${deleteWorkspaceStatus}`); + throw error; + } - await this.stopWorkspaceByName(workspaceName); - await this.deleteWorkspaceByName(workspaceName); + if (deleteWorkspaceResponse.status !== 204) { + throw new Error(`Can not delete workspace. Code: ${deleteWorkspaceResponse.status} Data: ${deleteWorkspaceResponse.data}`); } - // stop all run workspaces in the namespace - async stopAllRunningWorkspaces(namespace: string): Promise { - Logger.debug(); - let response: AxiosResponse = await this.processRequestHandler.get(await this.apiUrlResolver.getWorkspacesApiUrl()); - for (let i: number = 0; i < response.data.items.length; i++) { - Logger.info('the project is being stopped: ' + response.data.items[i].metadata.name); - await this.stopWorkspaceByName(response.data.items[i].metadata.name); + for (let i: number = 0; i < this.attempts; i++) { + try { + deleteWorkspaceResponse = await this.processRequestHandler.get(deleteWorkspaceApiUrl); + } catch (error) { + if (axios.isAxiosError(error) && error.response?.status === 404) { + deleteWorkspaceStatus = true; + Logger.debug(`${workspaceName} deleted successfully`); + break; } + } } - // stop all run workspaces, check statuses and remove the workspaces - async stopAndDeleteAllRunningWorkspaces(namespace: string): Promise { - Logger.debug(); - let response: AxiosResponse = await this.processRequestHandler.get(await this.apiUrlResolver.getWorkspacesApiUrl()); - await this.stopAllRunningWorkspaces(namespace); - for (let i: number = 0; i < response.data.items.length; i++) { - Logger.info('the project is being deleted: ' + response.data.items[i].metadata.name); - await this.deleteWorkspaceByName(response.data.items[i].metadata.name); - } + if (!deleteWorkspaceStatus) { + let waitTime: number = this.attempts * this.polling; + throw new error.TimeoutError(`The workspace was not deleted in ${waitTime} ms.`); + } + } + + // stop workspace before deleting with checking stopping phase + async stopAndDeleteWorkspaceByName(workspaceName: string): Promise { + Logger.debug(); + + await this.stopWorkspaceByName(workspaceName); + await this.deleteWorkspaceByName(workspaceName); + } + + // stop all run workspaces in the namespace + async stopAllRunningWorkspaces(namespace: string): Promise { + Logger.debug(); + let response: AxiosResponse = await this.processRequestHandler.get(await this.apiUrlResolver.getWorkspacesApiUrl()); + for (let i: number = 0; i < response.data.items.length; i++) { + Logger.info('the project is being stopped: ' + response.data.items[i].metadata.name); + await this.stopWorkspaceByName(response.data.items[i].metadata.name); } + } + + // stop all run workspaces, check statuses and remove the workspaces + async stopAndDeleteAllRunningWorkspaces(namespace: string): Promise { + Logger.debug(); + let response: AxiosResponse = await this.processRequestHandler.get(await this.apiUrlResolver.getWorkspacesApiUrl()); + await this.stopAllRunningWorkspaces(namespace); + for (let i: number = 0; i < response.data.items.length; i++) { + Logger.info('the project is being deleted: ' + response.data.items[i].metadata.name); + await this.deleteWorkspaceByName(response.data.items[i].metadata.name); + } + } - // stop all run workspaces without stopping and waiting for of 'Stopped' phase - // similar with 'force' deleting - async deleteAllWorkspaces(namespace: string): Promise { - Logger.debug(); - let response: AxiosResponse = await this.processRequestHandler.get(await this.apiUrlResolver.getWorkspacesApiUrl()); + // stop all run workspaces without stopping and waiting for of 'Stopped' phase + // similar with 'force' deleting + async deleteAllWorkspaces(namespace: string): Promise { + Logger.debug(); + let response: AxiosResponse = await this.processRequestHandler.get(await this.apiUrlResolver.getWorkspacesApiUrl()); - for (let i: number = 0; i < response.data.items.length; i++) { - Logger.info('the project is being deleted .......: ' + response.data.items[i].metadata.name); - await this.deleteWorkspaceByName(response.data.items[i].metadata.name); - } + for (let i: number = 0; i < response.data.items.length; i++) { + Logger.info('the project is being deleted .......: ' + response.data.items[i].metadata.name); + await this.deleteWorkspaceByName(response.data.items[i].metadata.name); } + } } diff --git a/tests/e2e/utils/workspace/WorkspaceStatus.ts b/tests/e2e/utils/workspace/WorkspaceStatus.ts index dfd361597e5..953b5fd0b2b 100644 --- a/tests/e2e/utils/workspace/WorkspaceStatus.ts +++ b/tests/e2e/utils/workspace/WorkspaceStatus.ts @@ -9,7 +9,7 @@ **********************************************************************/ export enum WorkspaceStatus { - RUNNING = 'Running', - STOPPED = 'Stopped', - STARTING = 'Starting' + RUNNING = 'Running', + STOPPED = 'Stopped', + STARTING = 'Starting' }