Skip to content
Snippets Groups Projects
Verified Commit 3f519e3e authored by Julien Wittouck's avatar Julien Wittouck
Browse files

:sparkles: : import cucumber base code

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 2010 additions and 0 deletions
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
plugins {
id 'java'
}
group = 'fr.univ-lille.gitlab.sra1-2023'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
ext {
cucumberVersion = '7.13.0'
seleniumVersion = '4.8.3'
assertJVersion = '3.24.2'
}
dependencies {
implementation "io.cucumber:cucumber-java:$cucumberVersion"
implementation "org.seleniumhq.selenium:selenium-api:$seleniumVersion"
implementation "org.seleniumhq.selenium:selenium-support:$seleniumVersion"
implementation "org.seleniumhq.selenium:htmlunit3-driver:$seleniumVersion"
implementation "org.assertj:assertj-core:$assertJVersion"
}
// build an executable jar
def mainClassName = "io.cucumber.core.cli.Main"
jar {
manifest {
attributes "Main-Class": "$mainClassName"
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from {
configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
File added
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
gradlew 0 → 100755
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'cucumber-runner'
package fr.univlille.gitlab.sra12023.cucumberrunner;
import io.cucumber.core.exception.CucumberException;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import static org.assertj.core.api.Assertions.assertThat;
public class Controler101StepsDef {
private HttpResponse<String> response;
private int port;
private String host = "localhost";
@Given("L'application écoute sur le port {int}")
public void lApplicationÉcouteSurLePort(int port) throws IOException {
this.port = port;
try(var socket = new Socket("localhost", port)){
assertThat(socket.isConnected()).isTrue();
}
catch(ConnectException e){
throw new CucumberException("L'application n'est pas disponible sur le port " + port, e);
}
}
@When("La requête HTTP {string} est envoyée")
public void laRequêteHTTPEstEnvoyée(String requestLine) throws IOException, InterruptedException {
var requestParts = requestLine.split(" ");
var verb = requestParts[0];
var uri = requestParts[1];
var request = HttpRequest.newBuilder()
.uri(URI.create("http://" + host + ":" + port + uri))
.GET()
.build();
var client = HttpClient.newHttpClient();
this.response = client.send(request, HttpResponse.BodyHandlers.ofString());
}
@Then("La réponse a un code HTTP {int}")
public void laRéponseAUnCodeHTTP(int code) {
assertThat(response.statusCode()).isEqualTo(code);
}
@And("La réponse a un header HTTP {string}")
public void laRéponseAUnHeaderHTTP(String header) {
var headerParts = header.split(": ");
var headerKey = headerParts[0];
var headerValue = headerParts[1];
assertThat(response.headers().firstValue(headerKey).get()).contains(headerValue);
}
@And("La réponse a un body {string}")
public void laRéponseAUnBody(String body) {
assertThat(response.body()).isEqualTo(body);
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner;
import io.cucumber.core.cli.Main;
public class CucumberRunnerApplication {
public static void main(String[] args) {
// run cucumber !
Main.main(args);
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner;
import org.openqa.selenium.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
public class DriverUtil {
public static long DEFAULT_WAIT = 20;
protected static WebDriver driver;
public static WebDriver getDefaultDriver() {
if (driver != null) {
return driver;
}
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setJavascriptEnabled(true);
capabilities.setCapability("takesScreenshot", true);
capabilities.setBrowserName("htmlunit");
driver = new HtmlUnitDriver(capabilities);
driver.manage().timeouts().setScriptTimeout(DEFAULT_WAIT,
TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
public static WebElement waitAndGetElementByCssSelector(WebDriver driver, String selector,
int seconds) {
By selection = By.cssSelector(selector);
return (new WebDriverWait(driver, Duration.ofSeconds(seconds))).until( // ensure element is visible!
ExpectedConditions.visibilityOfElementLocated(selection));
}
public static void closeDriver() {
if (driver != null) {
try {
driver.close();
driver.quit(); // fails in current geckodriver! TODO: Fixme
} catch (NoSuchMethodError nsme) { // in case quit fails
} catch (NoSuchSessionException nsse) { // in case close fails
} catch (SessionNotCreatedException snce) {
} // in case close fails
driver = null;
}
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner;
import fr.univlille.gitlab.sra12023.cucumberrunner.selenium.BaseTest;
import fr.univlille.gitlab.sra12023.cucumberrunner.selenium.TestCaseFailed;
import io.cucumber.java.en.Then;
import org.openqa.selenium.WebDriver;
import java.io.IOException;
public class PredefinedStepDefinitions implements BaseTest {
protected WebDriver driver = DriverUtil.getDefaultDriver();
//Navigation Steps
//Step to navigate to specified URL
@Then("^I navigate to \"([^\"]*)\"$")
public void navigate_to(String link)
{
navigationObj.navigateTo(link);
}
//Step to navigate forward
@Then("^I navigate forward")
public void navigate_forward()
{
navigationObj.navigate("forward");
}
//Step to navigate backward
@Then("^I navigate back")
public void navigate_back()
{
navigationObj.navigate("back");
}
// steps to refresh page
@Then("^I refresh page$")
public void refresh_page()
{
driver.navigate().refresh();
}
// Switch between windows
//Switch to new window
@Then("^I switch to new window$")
public void switch_to_new_window()
{
navigationObj.switchToNewWindow();
}
//Switch to old window
@Then("^I switch to previous window$")
public void switch_to_old_window()
{
navigationObj.switchToOldWindow();
}
//Switch to new window by window title
@Then("^I switch to window having title \"(.*?)\"$")
public void switch_to_window_by_title(String windowTitle) throws Exception
{
navigationObj.switchToWindowByTitle(windowTitle);
}
//Close new window
@Then("^I close new window$")
public void close_new_window()
{
navigationObj.closeNewWindow();
}
// Switch between frame
// Step to switch to frame by web element
@Then("^I switch to frame having (.+) \"(.*?)\"$")
public void switch_frame_by_element(String method, String value)
{
navigationObj.switchFrame(method, value);
}
// step to switch to main content
@Then("^I switch to main content$")
public void switch_to_default_content()
{
navigationObj.switchToDefaultContent();
}
// To interact with browser
// step to resize browser
@Then("^I resize browser window size to width (\\d+) and height (\\d+)$")
public void resize_browser(int width, int heigth)
{
navigationObj.resizeBrowser(width, heigth);
}
// step to maximize browser
@Then("^I maximize browser window$")
public void maximize_browser()
{
navigationObj.maximizeBrowser();
}
//Step to close the browser
@Then("^I close browser$")
public void close_browser()
{
navigationObj.closeDriver();
}
// zoom in/out page
// steps to zoom in page
@Then("^I zoom in page$")
public void zoom_in()
{
navigationObj.zoomInOut("ADD");
}
// steps to zoom out page
@Then("^I zoom out page$")
public void zoom_out()
{
navigationObj.zoomInOut("SUBTRACT");
}
// zoom out webpage till necessary element displays
// steps to zoom out till element displays
@Then("^I zoom out page till I see element having (.+) \"(.*?)\"$")
public void zoom_till_element_display(String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
navigationObj.zoomInOutTillElementDisplay(type,"substract", accessName);
}
// reset webpage view use
@Then("^I reset page view$")
public void reset_page_zoom()
{
navigationObj.zoomInOut("reset");
}
// scroll webpage
@Then("^I scroll to (top|end) of page$")
public void scroll_page(String to) throws Exception
{
navigationObj.scrollPage(to);
}
// scroll webpage to specific element
@Then("^I scroll to element having (.+) \"(.*?)\"$")
public void scroll_to_element(String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
navigationObj.scrollToElement(type, accessName);
}
// hover over element
// Note: Doesn't work on Windows firefox
@Then("^I hover over element having (.+) \"(.*?)\"$")
public void hover_over_element(String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
navigationObj.hoverOverElement(type, accessName);
}
//Assertion steps
/** page title checking
* @param present :
* @param title :
*/
@Then("^I should\\s*((?:not)?)\\s+see page title as \"(.+)\"$")
public void check_title(String present,String title) throws TestCaseFailed
{
//System.out.println("Present :" + present.isEmpty());
assertionObj.checkTitle(title,present.isEmpty());
}
// step to check element partial text
@Then("^I should\\s*((?:not)?)\\s+see page title having partial text as \"(.*?)\"$")
public void check_partial_text(String present, String partialTextTitle) throws TestCaseFailed
{
//System.out.println("Present :" + present.isEmpty());
assertionObj.checkPartialTitle(partialTextTitle, present.isEmpty());
}
// step to check element text
@Then("^element having (.+) \"([^\"]*)\" should\\s*((?:not)?)\\s+have text as \"(.*?)\"$")
public void check_element_text(String type, String accessName,String present,String value) throws Exception
{
miscmethodObj.validateLocator(type);
assertionObj.checkElementText(type, value, accessName,present.isEmpty());
}
//step to check element partial text
@Then("^element having (.+) \"([^\"]*)\" should\\s*((?:not)?)\\s+have partial text as \"(.*?)\"$")
public void check_element_partial_text(String type,String accessName,String present,String value) throws Exception
{
miscmethodObj.validateLocator(type);
assertionObj.checkElementPartialText(type, value, accessName, present.isEmpty());
}
// step to check attribute value
@Then("^element having (.+) \"([^\"]*)\" should\\s*((?:not)?)\\s+have attribute \"(.*?)\" with value \"(.*?)\"$")
public void check_element_attribute(String type,String accessName,String present,String attrb,String value) throws Exception
{
miscmethodObj.validateLocator(type);
assertionObj.checkElementAttribute(type, attrb, value, accessName, present.isEmpty());
}
// step to check element enabled or not
@Then("^element having (.+) \"([^\"]*)\" should\\s*((?:not)?)\\s+be (enabled|disabled)$")
public void check_element_enable(String type, String accessName,String present,String state) throws Exception
{
miscmethodObj.validateLocator(type);
boolean flag = state.equals("enabled");
if(!present.isEmpty())
{
flag = !flag;
}
assertionObj.checkElementEnable(type, accessName, flag);
}
//step to check element present or not
@Then("^element having (.+) \"(.*?)\" should\\s*((?:not)?)\\s+be present$")
public void check_element_presence(String type,String accessName,String present) throws Exception
{
miscmethodObj.validateLocator(type);
assertionObj.checkElementPresence(type, accessName, present.isEmpty());
}
//step to assert checkbox is checked or unchecked
@Then("^checkbox having (.+) \"(.*?)\" should be (checked|unchecked)$")
public void is_checkbox_checked(String type, String accessName,String state) throws Exception
{
miscmethodObj.validateLocator(type);
boolean flag = state.equals("checked");
assertionObj.isCheckboxChecked(type, accessName, flag);
}
//steps to assert radio button checked or unchecked
@Then("^radio button having (.+) \"(.*?)\" should be (selected|unselected)$")
public void is_radio_button_selected(String type,String accessName,String state) throws Exception
{
miscmethodObj.validateLocator(type);
boolean flag = state.equals("selected");
assertionObj.isRadioButtonSelected(type, accessName, flag);
}
//steps to assert option by text from radio button group selected/unselected
@Then("^option \"(.*?)\" by (.+) from radio button group having (.+) \"(.*?)\" should be (selected|unselected)$")
public void is_option_from_radio_button_group_selected(String option,String attrb,String type,String accessName,String state) throws Exception
{
miscmethodObj.validateLocator(type);
boolean flag = state.equals("selected");
assertionObj.isOptionFromRadioButtonGroupSelected(type,attrb,option,accessName,flag);
}
//steps to check link presence
@Then("^link having text \"(.*?)\" should\\s*((?:not)?)\\s+be present$")
public void check_element_presence(String accessName,String present) throws TestCaseFailed, Exception
{
assertionObj.checkElementPresence("linkText",accessName,present.isEmpty());
}
//steps to check partail link presence
@Then("^link having partial text \"(.*?)\" should\\s*((?:not)?)\\s+be present$")
public void check_partial_element_presence(String accessName,String present) throws TestCaseFailed, Exception
{
assertionObj.checkElementPresence("partialLinkText", accessName, present.isEmpty());
}
//step to assert javascript pop-up alert text
@Then("^I should see alert text as \"(.*?)\"$")
public void check_alert_text(String actualValue) throws TestCaseFailed
{
assertionObj.checkAlertText(actualValue);
}
// step to select dropdown list
@Then("^option \"(.*?)\" by (.+) from dropdown having (.+) \"(.*?)\" should be (selected|unselected)$")
public void is_option_from_dropdown_selected(String option,String by,String type,String accessName,String state) throws Exception
{
miscmethodObj.validateLocator(type);
boolean flag = state.equals("selected");
assertionObj.isOptionFromDropdownSelected(type,by,option,accessName,flag);
}
//Input steps
// enter text into input field steps
@Then("^I enter \"([^\"]*)\" into input field having (.+) \"([^\"]*)\"$")
public void enter_text(String text, String type,String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.enterText(type, text, accessName);
}
// clear input field steps
@Then("^I clear input field having (.+) \"([^\"]*)\"$")
public void clear_text(String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.clearText(type, accessName);
}
// select option by text/value from dropdown
@Then("^I select \"(.*?)\" option by (.+) from dropdown having (.+) \"(.*?)\"$")
public void select_option_from_dropdown(String option,String optionBy,String type,String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
miscmethodObj.validateOptionBy(optionBy);
inputObj.selectOptionFromDropdown(type,optionBy, option, accessName);
}
// select option by index from dropdown
@Then("^I select (\\d+) option by index from dropdown having (.+) \"(.*?)\"$")
public void select_option_from_dropdown_by_index(String option, String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.selectOptionFromDropdown(type,"selectByIndex", option, accessName);
}
// select option by text/value from multiselect
@Then("^I select \"(.*?)\" option by (.+) from multiselect dropdown having (.+) \"(.*?)\"$")
public void select_option_from_multiselect_dropdown(String option,String optionBy, String type,String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
miscmethodObj.validateOptionBy(optionBy);
inputObj.selectOptionFromDropdown(type,optionBy, option, accessName);
}
// select option by index from multiselect
@Then("^I select (\\d+) option by index from multiselect dropdown having (.+) \"(.*?)\"$")
public void select_option_from_multiselect_dropdown_by_index(String option, String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.selectOptionFromDropdown(type,"selectByIndex", option, accessName);
}
// deselect option by text/value from multiselect
@Then("^I deselect \"(.*?)\" option by (.+) from multiselect dropdown having (.+) \"(.*?)\"$")
public void deselect_option_from_multiselect_dropdown(String option,String optionBy, String type,String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
miscmethodObj.validateOptionBy(optionBy);
inputObj.deselectOptionFromDropdown(type, optionBy, option, accessName);
}
// deselect option by index from multiselect
@Then("^I deselect (\\d+) option by index from multiselect dropdown having (.+) \"(.*?)\"$")
public void deselect_option_from_multiselect_dropdown_by_index(String option, String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.deselectOptionFromDropdown(type, "selectByIndex", option, accessName);
}
// step to select option from mutliselect dropdown list
/*@Then("^I select all options from multiselect dropdown having (.+) \"(.*?)\"$")
public void select_all_option_from_multiselect_dropdown(String type,String accessName) throws Exception
{
miscmethod.validateLocator(type);
//inputObj.
//select_all_option_from_multiselect_dropdown(type, access_name)
}*/
// step to unselect option from mutliselect dropdown list
@Then("^I deselect all options from multiselect dropdown having (.+) \"(.*?)\"$")
public void unselect_all_option_from_multiselect_dropdown(String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.unselectAllOptionFromMultiselectDropdown(type, accessName);
}
//check checkbox steps
@Then("^I check the checkbox having (.+) \"(.*?)\"$")
public void check_checkbox(String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.checkCheckbox(type, accessName);
}
//uncheck checkbox steps
@Then("^I uncheck the checkbox having (.+) \"(.*?)\"$")
public void uncheck_checkbox(String type,String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.uncheckCheckbox(type, accessName);
}
//steps to toggle checkbox
@Then("^I toggle checkbox having (.+) \"(.*?)\"$")
public void toggle_checkbox(String type,String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.toggleCheckbox(type, accessName);
}
// step to select radio button
@Then("^I select radio button having (.+) \"(.*?)\"$")
public void select_radio_button(String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
inputObj.selectRadioButton(type, accessName);
}
// steps to select option by text from radio button group
@Then("^I select \"(.*?)\" option by (.+) from radio button group having (.+) \"(.*?)\"$")
public void select_option_from_radio_btn_group(String option,String by, String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
//miscmethodObj.validateOptionBy(optionBy);
inputObj.selectOptionFromRadioButtonGroup(type, option, by, accessName);
}
//Click element Steps
// click on web element
@Then("^I click on element having (.+) \"(.*?)\"$")
public void click(String type,String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
clickObj.click(type, accessName);
}
//Forcefully click on element
@Then("^I forcefully click on element having (.+) \"(.*?)\"$")
public void click_forcefully(String type,String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
clickObj.clickForcefully(type,accessName);
}
// double click on web element
@Then("^I double click on element having (.+) \"(.*?)\"$")
public void double_click(String type, String accessValue) throws Exception
{
miscmethodObj.validateLocator(type);
clickObj.doubleClick(type, accessValue);
}
// steps to click on link
@Then("^I click on link having text \"(.*?)\"$")
public void click_link(String accessName)
{
clickObj.click("linkText", accessName);
}
//Step to click on partial link
@Then("^I click on link having partial text \"(.*?)\"$")
public void click_partial_link(String accessName)
{
clickObj.click("partialLinkText", accessName);
}
//Progress methods
// wait for specific period of time
@Then("^I wait for (\\d+) sec$")
public void wait(String time) throws NumberFormatException, InterruptedException
{
progressObj.wait(time);
}
//wait for specific element to display for specific period of time
@Then("^I wait (\\d+) seconds for element having (.+) \"(.*?)\" to display$")
public void wait_for_ele_to_display(String duration, String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
progressObj.waitForElementToDisplay(type, accessName, duration);
}
// wait for specific element to enable for specific period of time
@Then("^I wait (\\d+) seconds for element having (.+) \"(.*?)\" to be enabled$")
public void wait_for_ele_to_click(String duration, String type, String accessName) throws Exception
{
miscmethodObj.validateLocator(type);
progressObj.waitForElementToClick(type, accessName, duration);
}
//JavaScript handling steps
//Step to handle java script
@Then("^I accept alert$")
public void handle_alert()
{
javascriptObj.handleAlert("accept");
}
//Steps to dismiss java script
@Then("^I dismiss alert$")
public void dismiss_alert()
{
javascriptObj.handleAlert("dismiss");
}
//Screen shot methods
@Then("^I take screenshot$")
public void take_screenshot() throws IOException
{
screenshotObj.takeScreenShot();
}
//Configuration steps
// step to print configuration
@Then("^I print configuration$")
public void print_config()
{
configObj.printDesktopConfiguration();
}
// @After
// public final void takeScreenShot(Scenario scenario) {
// if (scenario.isFailed()) {
// TakesScreenshot ts = (TakesScreenshot) driver;
// File srcFile = ts.getScreenshotAs(OutputType.FILE);
// try {
// ScenarioImpl impl = (ScenarioImpl) scenario;
// Collection<String> tags = impl.getSourceTagNames();
// String name = "Scenario";
// for (String t : tags) {
// name += "_" + t;
// }
// String name = "Screenshots/" + impl.getId().replaceAll("\\W", "_");
// FileUtils.copyFile(srcFile, new File(name + ".png"));
// } catch (IOException ex) {
// //Logger.getLogger(SmapScenario.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
// }
// @After
// public final void tearDown() {
// DriverUtil.closeDriver();
// }
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
public class AssertionMethods extends SelectElementByType implements BaseTest
{
//This file contains assertion methods which are called from predefinedStepDefinitions
//SelectElementByType eleType= new SelectElementByType();
private WebElement element=null;
/** Method to get page title
* @return String
* */
public String getPageTitle()
{
return driver.getTitle();
}
/** Method to verify page title
* @param title : String : expected title
* @param testCase : Boolean : test case [true or false]
*/
public void checkTitle(String title,boolean testCase) throws TestCaseFailed
{
String pageTitle = getPageTitle();
if(testCase)
{
if(!pageTitle.equals(title))
throw new TestCaseFailed("Page Title Not Matched, Actual Page Title : "+pageTitle);
}
else
{
if(pageTitle.equals(title))
throw new TestCaseFailed("Page Title Matched, Actual Page Title : "+pageTitle);
}
}
/** Method to verify partial page title
* @param partialTitle : String : partial title string
* @param testCase : Boolean : test case [true or false]
*/
public void checkPartialTitle(String partialTitle,boolean testCase) throws TestCaseFailed
{
String pageTitle = getPageTitle();
if(testCase)
{
if(!pageTitle.contains(partialTitle))
throw new TestCaseFailed("Partial Page Title Not Present, Actual Page Title : "+pageTitle);
}
else
{
if(pageTitle.contains(partialTitle))
throw new TestCaseFailed("Partial Page Title Present, Actual Page Title : "+pageTitle);
}
}
/** Method to get element text
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param accessName : String : Locator value
* @return String
*/
public String getElementText(String accessType, String accessName)
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
return element.getText();
}
/** Method to check element text
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param actualValue : String : Expected element text
* @param accessName : String : Locator value
* @param testCase : Boolean : test case [true or false]
*/
public void checkElementText(String accessType,String actualValue,String accessName,boolean testCase) throws TestCaseFailed
{
String elementText = getElementText(accessType, accessName);
if (testCase)
{
if (!elementText.equals(actualValue))
throw new TestCaseFailed("Text Not Matched");
}
else
{
if (elementText.equals(actualValue))
throw new TestCaseFailed("Text Matched");
}
}
/** Method to check partial element text
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param actualValue : String : Expected element text
* @param accessName : String : Locator value
* @param testCase : Boolean : test case [true or false]
*/
public void checkElementPartialText(String accessType,String actualValue,String accessName,boolean testCase) throws TestCaseFailed
{
String elementText = getElementText(accessType, accessName);
if (testCase)
{
if (!elementText.contains(actualValue))
throw new TestCaseFailed("Text Not Matched");
}
else
{
if (elementText.contains(actualValue))
throw new TestCaseFailed("Text Matched");
}
}
/** Method to return element status - enabled?
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param accessName : String : Locator value
* @return Boolean
*/
public boolean isElementEnabled(String accessType, String accessName)
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
return element.isEnabled();
}
/** Element enabled checking
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
@param testCase : Boolean : test case [true or false]
*/
public void checkElementEnable(String accessType, String accessName, boolean testCase) throws TestCaseFailed
{
boolean result=isElementEnabled(accessType,accessName);
if(testCase)
{
if (!result)
throw new TestCaseFailed("Element Not Enabled");
}
else
{
if(result)
throw new TestCaseFailed("Element Enabled");
}
}
/** method to get attribute value
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
@param attributeName : String : attribute name
@return String
*/
public String getElementAttribute(String accessType,String accessName,String attributeName)
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
return element.getAttribute(attributeName);
}
/** method to check attribute value
@param accessType : String : Locator type (id, name, class, xpath, css)
@param attributeName : String : attribute name
@param attributeValue : String : attribute value
@param accessName : String : Locator value
@param testCase : Boolean : test case [true or false]
*/
public void checkElementAttribute(String accessType, String attributeName, String attributeValue, String accessName, boolean testCase) throws TestCaseFailed
{
String attrVal = getElementAttribute(accessType, accessName, attributeName);
if(testCase)
{
if(!attrVal.equals(attributeValue))
throw new TestCaseFailed("Attribute Value Not Matched");
}
else
{
if(attrVal.equals(attributeValue))
throw new TestCaseFailed("Attribute Value Matched");
}
}
/** method to get element status - displayed?
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
@return Boolean
*/
public boolean isElementDisplayed(String accessType,String accessName)
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
return element.isDisplayed();
}
/** method to check element presence
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
@param testCase : Boolean : test case [true or false]
*/
public void checkElementPresence(String accessType,String accessName,boolean testCase) throws TestCaseFailed
{
if (testCase)
{
if (!isElementDisplayed(accessType, accessName))
throw new TestCaseFailed("Element Not Present");
}
else
{
try
{
if(isElementDisplayed(accessType, accessName))
throw new Exception("Present"); //since it is negative test and we found element
}
catch(Exception e)
{
if(e.getMessage().equals("Present")) //only raise if it present
throw new TestCaseFailed("Element Present");
}
}
}
/** method to assert checkbox check/uncheck
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
@param shouldBeChecked : Boolean : test case [true or false]
*/
public void isCheckboxChecked(String accessType,String accessName,boolean shouldBeChecked) throws TestCaseFailed
{
WebElement checkbox = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
if((!checkbox.isSelected()) && shouldBeChecked)
throw new TestCaseFailed("Checkbox is not checked");
else if(checkbox.isSelected() && !shouldBeChecked)
throw new TestCaseFailed("Checkbox is checked");
}
/** method to assert radio button selected/unselected
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
@param shouldBeChecked : Boolean : test case [true or false]
*/
public void isRadioButtonSelected(String accessType,String accessName,boolean shouldBeSelected) throws TestCaseFailed
{
WebElement radioButton = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
if((!radioButton.isSelected()) && shouldBeSelected)
throw new TestCaseFailed("Radio Button not selected");
else if(radioButton.isSelected() && !shouldBeSelected)
throw new TestCaseFailed("Radio Button is selected");
}
//method to assert option from radio button group is selected/unselected
public void isOptionFromRadioButtonGroupSelected(String accessType,String by,String option,String accessName,boolean shouldBeSelected) throws TestCaseFailed
{
List<WebElement> radioButtonGroup = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(getelementbytype(accessType, accessName)));
for (WebElement rb : radioButtonGroup) {
if(by.equals("value"))
{
if(rb.getAttribute("value").equals(option))
{
if((!rb.isSelected()) && shouldBeSelected)
throw new TestCaseFailed("Radio Button not selected");
else if(rb.isSelected() && !shouldBeSelected)
throw new TestCaseFailed("Radio Button is selected");
}
}
else if(rb.getText().equals(option))
{
if((!rb.isSelected()) && shouldBeSelected)
throw new TestCaseFailed("Radio Button not selected");
else if(rb.isSelected() && !shouldBeSelected)
throw new TestCaseFailed("Radio Button is selected");
}
}
}
/** method to get javascript pop-up alert text
* @return String
*/
public String getAlertText()
{
return driver.switchTo().alert().getText();
}
/**method to check javascript pop-up alert text
* @param text : String : Text to verify in Alert
* @throws TestCaseFailed
*/
public void checkAlertText(String text) throws TestCaseFailed
{
if(!getAlertText().equals(text))
throw new TestCaseFailed("Text on alert pop up not matched");
}
/** Method to verify if the particular option is Selected from Dropdown
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param by : String : Select element from dropdown by text or value
* @param option : String : Element to select from dropdown
* @param accessName : String : Locator value
* @param shouldBeSelected : Boolean : test case [true or false]
* @throws TestCaseFailed
*/
public void isOptionFromDropdownSelected(String accessType,String by,String option,String accessName,boolean shouldBeSelected) throws TestCaseFailed
{
Select selectList=null;
WebElement dropdown = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
selectList = new Select(dropdown);
String actualValue="";
if(by.equals("text"))
actualValue = selectList.getFirstSelectedOption().getText();
else
actualValue = selectList.getFirstSelectedOption().getAttribute("value");
if((!actualValue.equals(option))&&(shouldBeSelected))
throw new TestCaseFailed("Option Not Selected From Dropwdown");
else if ((actualValue.equals(option))&&(!shouldBeSelected))
throw new TestCaseFailed("Option Selected From Dropwdown");
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
public interface BaseTest
{
MiscMethods miscmethodObj = new MiscMethods();
NavigateMethods navigationObj = new NavigateMethods();
AssertionMethods assertionObj = new AssertionMethods();
ClickElementsMethods clickObj = new ClickElementsMethods();
ConfigurationMethods configObj = new ConfigurationMethods();
InputMethods inputObj = new InputMethods();
ProgressMethods progressObj = new ProgressMethods();
JavascriptHandlingMethods javascriptObj = new JavascriptHandlingMethods();
ScreenShotMethods screenshotObj = new ScreenShotMethods();
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class ClickElementsMethods extends SelectElementByType implements BaseTest
{
//SelectElementByType eleType= new SelectElementByType();
private WebElement element=null;
/** Method to click on an element
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void click(String accessType, String accessName)
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
element.click();
}
/** Method to forcefully click on an element
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void clickForcefully(String accessType, String accessName)
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();",element);
}
/** Method to Double click on an element
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void doubleClick(String accessType, String accessValue)
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessValue)));
Actions action = new Actions(driver);
action.moveToElement(element).doubleClick().perform();
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
import fr.univlille.gitlab.sra12023.cucumberrunner.DriverUtil;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class ConfigurationMethods implements BaseTest
{
protected WebDriver driver;
public ConfigurationMethods() {
driver = DriverUtil.getDefaultDriver();
}
/** Method to print desktop configuration */
public void printDesktopConfiguration()
{
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Following are machine configurations : \n");
System.out.println("Date (MM/DD/YYYY) and Time (HH:MM:SS) : "+dateFormat.format(cal.getTime()));
Capabilities cap = (Capabilities)((RemoteWebDriver) driver).getCapabilities();
System.out.println("Browser : "+cap.getBrowserName());
System.out.println("Platform : "+cap.getPlatformName());
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
import java.util.Arrays;
public class ErrorHandlingMethods
{
//Method to check browser type
public void validateParameters(String platform, String browserType, String appPath)
{
if(platform.equals("desktop"))
{
if(Arrays.asList("ff","ie","chrome","safari","opera").contains(browserType))
printErrorDesktop();
}
else if(platform.equals("android"))
printErrorAndroid(browserType,appPath);
else if(platform.equals("iOS"))
System.out.println("Not Implemented...");
else
printInvalidPlatform();
}
//print error for desktop
private void printErrorDesktop()
{
System.out.println("\nInappropraite desktop browser : \"#{ENV['BROWSER']}\"");
System.out.println("\nUsage : cucumber BROWSER=browser_name");
System.out.println("\nBrowser Supported :\n");
System.out.println("\n1.ie\n2.chrome\n3.ff\n4.safari\n5.opera");
System.exit(0);
}
//print error for android
public void printErrorAndroid(String browserType,String appPath)
{
/*if browser_type=='ff' and app_path==nil
puts "\nOops... not mentioned \"Browser\" or \"App path\""
print_error_android_app
print_error_android_web
Process.exit(0)
elsif browser_type!='ff' and !%w(native chrome).include? browser_type
puts "\nOops... not supported browser"
print_error_android_web
Process.exit(0)
end
end*/
}
//print error if invalid platform
public void printInvalidPlatform()
{
System.out.println("\nOops... Invalid Platform");
System.out.println("\nSupported platform are \"android\" and \"iOS\".");
System.out.println("\nTo run on Desktop no need to mention platform.");
System.exit(0);
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
public class InputMethods extends SelectElementByType implements BaseTest
{
//SelectElementByType eleType= new SelectElementByType();
private WebElement dropdown =null;
private Select selectList=null;
/** Method to enter text into text field
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param text : String : Text value to enter in field
@param accessName : String : Locator value
*/
public void enterText(String accessType,String text,String accessName)
{
wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
driver.findElement(getelementbytype(accessType, accessName)).sendKeys(text);
}
/** Method to clear text of text field
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void clearText(String accessType, String accessName)
{
wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
driver.findElement(getelementbytype(accessType, accessName)).clear();
}
/** Method to select element from Dropdown by type
* @param select_list : Select : Select variable
* @param bytype : String : Name of by type
* @param option : String : Option to select
*/
public void selectelementfromdropdownbytype (Select select_list, String bytype, String option)
{
if(bytype.equals("selectByIndex"))
{
int index = Integer.parseInt(option);
select_list.selectByIndex(index-1);
}
else if (bytype.equals("value"))
select_list.selectByValue(option);
else if (bytype.equals("text"))
select_list.selectByVisibleText(option);
}
/** Method to select option from dropdown list
@param accessType : String : Locator type (id, name, class, xpath, css)
@param by : String : Name of by type
@param option : String : Option to select
@param accessName : String : Locator value
*/
public void selectOptionFromDropdown(String accessType, String optionBy, String option, String accessName)
{
dropdown = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
selectList = new Select(dropdown);
if(optionBy.equals("selectByIndex"))
selectList.selectByIndex(Integer.parseInt(option)-1);
else if (optionBy.equals("value"))
selectList.selectByValue(option);
else if (optionBy.equals("text"))
selectList.selectByVisibleText(option);
}
//method to select all option from dropdwon list
// public void select_all_option_from_multiselect_dropdown(String access_type, String access_name)
// {
// dropdown = driver.findElement(getelementbytype(access_type, access_name));
// selectList = new Select(dropdown);
//
// //Select all method not present in JAVA
// }
/** Method to unselect all option from dropdwon list
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void unselectAllOptionFromMultiselectDropdown(String accessType, String accessName)
{
dropdown = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
selectList = new Select(dropdown);
selectList.deselectAll();
}
/** Method to unselect option from dropdwon list
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void deselectOptionFromDropdown(String accessType, String optionBy, String option, String accessName)
{
dropdown = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
selectList = new Select(dropdown);
if(optionBy.equals("selectByIndex"))
selectList.deselectByIndex(Integer.parseInt(option)-1);
else if (optionBy.equals("value"))
selectList.deselectByValue(option);
else if (optionBy.equals("text"))
selectList.deselectByVisibleText(option);
}
/** Method to check check-box
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void checkCheckbox(String accessType, String accessName)
{
WebElement checkbox= wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
if (!checkbox.isSelected())
checkbox.click();
}
/** Method to uncheck check-box
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void uncheckCheckbox(String accessType, String accessName)
{
WebElement checkbox= wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
if (checkbox.isSelected())
checkbox.click();
}
/** Method to toggle check-box status
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void toggleCheckbox(String accessType, String accessName)
{
wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName))).click();
}
/** Method to select radio button
@param accessType : String : Locator type (id, name, class, xpath, css)
@param accessName : String : Locator value
*/
public void selectRadioButton(String accessType, String accessName)
{
WebElement radioButton = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
if(!radioButton.isSelected())
radioButton.click();
}
/** Method to select option from radio button group
@param accessType : String : Locator type (id, name, class, xpath, css)
@param by : String : Name of by type
@param option : String : Option to select
@param accessName : String : Locator value
* @param accessName2
*/
public void selectOptionFromRadioButtonGroup(String accessType, String option, String by, String accessName)
{
List<WebElement> radioButtonGroup = driver.findElements(getelementbytype(accessType, accessName));
for(WebElement rb : radioButtonGroup)
{
if(by.equals("value"))
{
if(rb.getAttribute("value").equals(option) && !rb.isSelected())
rb.click();
}
else if(by.equals("text"))
{
if(rb.getText().equals(option) && !rb.isSelected())
rb.click();
}
}
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
import fr.univlille.gitlab.sra12023.cucumberrunner.DriverUtil;
import org.openqa.selenium.WebDriver;
public class JavascriptHandlingMethods implements BaseTest {
protected WebDriver driver = DriverUtil.getDefaultDriver();
/**Method to handle alert
* @param decision : String : Accept or dismiss alert
*/
public void handleAlert(String decision)
{
if(decision.equals("accept"))
driver.switchTo().alert().accept();
else
driver.switchTo().alert().dismiss();
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
import java.util.Arrays;
public class MiscMethods
{
public boolean valid_locator_type(String type)
{
return Arrays.asList("id","class","css","name","xpath").contains(type);
}
/** Method to verify locator type
* @param type : String : Locator type (id, name, class, xpath, css)
*/
public void validateLocator(String type) throws Exception
{
if(!valid_locator_type(type))
throw new Exception("Invalid locator type - "+type);
}
// method to validate dropdown selector
public boolean valid_option_by(String option_by)
{
return Arrays.asList("text","value","index").contains(option_by);
}
/** Method to verify dropdown selector (text, value or index)
* @param optionBy : String : Locator type (text, value, index)
*/
public void validateOptionBy(String optionBy) throws Exception
{
if(!valid_option_by(optionBy))
throw new Exception("Invalid option by - "+optionBy);
}
}
package fr.univlille.gitlab.sra12023.cucumberrunner.selenium;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class NavigateMethods extends SelectElementByType implements BaseTest
{
//SelectElementByType eleType= new SelectElementByType();
private WebElement element=null;
private String old_win = null;
private String lastWinHandle;
/** Method to open link
* @param url : String : URL for navigation
*/
public void navigateTo(String url)
{
driver.get(url);
}
/** Method to navigate back & forward
* @param direction : String : Navigate to forward or backward
*/
public void navigate(String direction)
{
if (direction.equals("back"))
driver.navigate().back();
else
driver.navigate().forward();
}
/** Method to quite webdriver instance */
public void closeDriver()
{
driver.close();
}
/** Method to return key by OS wise
* @return Keys : Return control or command key as per OS
*/
public Keys getKey()
{
String os = System.getProperty("os.name").toLowerCase();
if(os.contains("win"))
return Keys.CONTROL;
else if (os.contains("nux") || os.contains("nix"))
return Keys.CONTROL;
else if (os.contains("mac"))
return Keys.COMMAND;
else
return null;
}
/** Method to zoom in/out page
* @param inOut : String : Zoom in or out
*/
public void zoomInOut(String inOut)
{
WebElement Sel= driver.findElement(getelementbytype("tagName","html"));
if(inOut.equals("ADD"))
Sel.sendKeys(Keys.chord(getKey(), Keys.ADD));
else if(inOut.equals("SUBTRACT"))
Sel.sendKeys(Keys.chord(getKey(), Keys.SUBTRACT));
else if(inOut.equals("reset"))
Sel.sendKeys(Keys.chord(getKey(), Keys.NUMPAD0));
}
/** Method to zoom in/out web page until web element displays
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param inOut : String : Zoom in or out
* @param accessName : String : Locator value
*/
public void zoomInOutTillElementDisplay(String accessType,String inOut,String accessName)
{
Actions action = new Actions(driver);
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
while(true)
{
if (element.isDisplayed())
break;
else
action.keyDown(getKey()).sendKeys(inOut).keyUp(getKey()).perform();
}
}
/** Method to resize browser
* @param width : int : Width for browser resize
* @param height : int : Height for browser resize
*/
public void resizeBrowser(int width, int height)
{
driver.manage().window().setSize(new Dimension(width,height));
}
/** Method to maximize browser */
public void maximizeBrowser()
{
driver.manage().window().maximize();
}
/** Method to hover on element
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param accessName : String : Locator value
*/
public void hoverOverElement(String accessType, String accessName)
{
Actions action = new Actions(driver);
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
action.moveToElement(element).perform();
}
/** Method to scroll page to particular element
* @param accessType : String : Locator type (id, name, class, xpath, css)
* @param accessName : String : Locator value
*/
public void scrollToElement(String accessType, String accessName)
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].scrollIntoView();", element);
}
/** Method to scroll page to top or end
* @param to : String : Scroll page to Top or End
* @throws Exception
*/
public void scrollPage(String to) throws Exception
{
JavascriptExecutor executor = (JavascriptExecutor)driver;
if (to.equals("end"))
executor.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));");
else if (to.equals("top"))
executor.executeScript("window.scrollTo(Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight),0);");
else
throw new Exception("Exception : Invalid Direction (only scroll \"top\" or \"end\")");
}
/**Method to switch to new window */
public void switchToNewWindow()
{
old_win = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles())
lastWinHandle = winHandle;
driver.switchTo().window(lastWinHandle);
}
/** Method to switch to old window */
public void switchToOldWindow()
{
driver.switchTo().window(old_win);
}
/** Method to switch to window by title
* @param windowTitle : String : Name of window title to switch
* @throws Exception */
public void switchToWindowByTitle(String windowTitle) throws Exception
{
//System.out.println("++"+windowTitle+"++");
old_win = driver.getWindowHandle();
boolean winFound = false;
for(String winHandle : driver.getWindowHandles())
{
String str = driver.switchTo().window(winHandle).getTitle();
//System.out.println("**"+str+"**");
if (str.equals(windowTitle))
{
winFound = true;
break;
}
}
if (!winFound)
throw new Exception("Window having title "+windowTitle+" not found");
}
/**Method to close new window*/
public void closeNewWindow()
{
driver.close();
}
/** Method to switch frame using web element frame
* @param accessType : String : Locator type (index, id, name, class, xpath, css)
* @param accessName : String : Locator value
* */
public void switchFrame(String accessType, String accessName)
{
if(accessType.equalsIgnoreCase("index"))
driver.switchTo().frame(accessName);
else
{
element = wait.until(ExpectedConditions.presenceOfElementLocated(getelementbytype(accessType, accessName)));
driver.switchTo().frame(element);
}
}
/** method to switch to default content*/
public void switchToDefaultContent()
{
driver.switchTo().defaultContent();
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment