Is there a way to run the same Selenium test case on many pages without specifically defining a list of pages?
Say, for example, I have a UIMap pageset defined like this:
var map = new UIMap();
map.addPageset({
name: 'pages',
description: 'all pages',
pathRegexp: '^thisistheroot/$'
});
In the pageset, I have all the elements defined for a test script that I want to test on each page in the pageset.
All of this is added to my core extensions.
Am I able to run a test case on the entire pageset? How can I do that?
I've looked into the issue a little more. Is there a way this is possible with Jenkins? https://jenkins-ci.org/
Edit:
I was trying to avoid using selenium webdriver, but if it is possible to obtain links as you would in a UIMap, that would probably point me in the right direction as well. I would try to iterate over the links with a single test case, which can easily be done in java. I'm using java for webdriver by the way.
Thanks.
The simple answer is "no" but Selenium WebDriver is one of the best choices for sure to find the links of a page and iterate over them. There is a very similar concept of your UIMapping called PageFactory where you map all the page elements in separate classes to keep the responsibility separate which makes debugging and refactoring much easier. I have used the PageFactory concept here.
Now coming back to your question, you can easily find the list of the links present in a page. In that case you just need to write the selector little carefully. You can then easily iterate over the links and come back and forth and so on.
Proof of concept on Google
BasePage
package google;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.NoSuchElementException;
/**
* Defines the generic methods/functions for PageObjects.
*/
public class BaseClass {
protected WebDriver driver;
/**
* #param _driver
* #param byKnownElement
*/
public BaseClass(WebDriver _driver, By byKnownElement) {
//assigning driver instance globally.
driver = _driver;
this.correctPageLoadedCheck(byKnownElement);
/* Instantiating all elements since this is super class
and inherited by each and every page object */
PageFactory.initElements(driver, this);
}
/**
* Verifies correct page was returned.
*
* #param by
*/
private void correctPageLoadedCheck(By by) {
try {
driver.findElement(by).isDisplayed();
} catch (NoSuchElementException ex) {
throw ex;
}
}
}
PageObject inherited BasePage
package google;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import java.util.List;
/**
* Created by Saifur on 5/30/2015.
*/
public class GoogleLandingPage extends BaseClass {
private static final By byKnownElement = By.xpath("//a[text()='Sign in']");
/**
* #param _driver
*/
public GoogleLandingPage(WebDriver _driver) {
super(_driver, byKnownElement);
}
//This should find all the links of the page
//You need to write the selector such a way
// so that it will grab all intended links.
#FindBy(how = How.CSS,using = ".gb_e.gb_0c.gb_r.gb_Zc.gb_3c.gb_oa>div:first-child a")
public List<WebElement> ListOfLinks;
}
BaseTest
package tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
public class BaseTest {
public WebDriver driver;
String url = "https://www.google.com/";
#BeforeClass
public void SetUpTests() {
driver = new FirefoxDriver();
//Navigate to url
driver.navigate().to(url);
//Maximize the browser window
driver.manage().window().maximize();
}
#AfterClass
public void CleanUpDriver() throws Exception {
try {
driver.quit();
}catch (Exception ex){
throw ex;
}
}
}
Link Iterator test inheriting BaseTest
package tests;
import google.GoogleLandingPage;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import java.util.List;
/**
* Created by Saifur on 5/30/2015.
*/
public class LinksIteratorTests extends BaseTest {
#Test
public void IterateOverLinks(){
GoogleLandingPage google = new GoogleLandingPage(driver);
List<WebElement> elementList = google.ListOfLinks;
for (int i=0;i<elementList.size(); i++){
elementList.get(i).click();
//possibly do something else to go back to the previous page
driver.navigate().back();
}
}
}
Note: I am using TestNG to maintain the tests and please note for lazy loading page you may need to add some explicit wait if necessary
Actually it's simple to run an IDE test against 1 specific page (base url actually): java -jar selenium-server.jar -htmlSuite "*firefox" "http://baseURL.com" "mytestsuite.html" "results.html"
So what you need to do is use jenkins (or any bash/batch script) to run that command multiple times with the base url set as "http://baseURL.com/page1", "http://baseURL.com/page2", etc.
This will only get you as far as static list of pages to test against. If you want a dynamic list you'd have to also "crawl" the pages and you could do that in the similar batch/bash script to obtain the list of pages to test against.
In this case you'd best be investing beyond selenium IDE and switch to webdriver where you'll have more power to loop and flow control.
Related
I am working on a springboot project, I created a scheduler which has to run after every 10 mins, I have two pods running #shedlock is also implemented but it sometimes run sometimes doesn't run neither it throws any error, after sometime again it started executing.
Can anyone help on this
so the given information is not too much.
I can show you a working example in a distributed system, that I assume you have since you are mentioned pods that means your service is on Kubernetes.
application.yml/application.properties
your-app-config-root:
scheduling:
shedlock:
min-time-lock-should-kept: ${SHEDLOCK_MIN_TIME_LOCK_KEPT:PT10S}
max-time-lock-should-kept: ${SHEDLOCK_MAX_TIME_LOCK_KEPT:PT30S}
alert-on-unfinished-cleanup-scheduler:
enabled: ${ALERT_ON_UNFINISHED_CLEANUP_SCHEDULER_ENABLED:false}
cron: ${ALERT_ON_UNFINISHED_CLEANUP_SCHEDULER_CRON:0 0 8,11,14 * * *} # by default every day at 8, 11, 14
minutes-since-cleanup-job-unfinished: ${MINUTES_SINCE_CLEANUP_JOB_UNFINISHED:1440} # by default 24 hours
Configuration for Scheduler
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.sql.DataSource;
import static net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock.InterceptMode.PROXY_METHOD;
/**
* The defaultLockAtMostFor is the default value how long the lock should be kept in case the service which obtained the lock
* died before releasing it.
* This is just a fallback, under normal circumstances the lock is released as soon the tasks finishes.
*/
#Configuration
#EnableScheduling
#EnableSchedulerLock(interceptMode = PROXY_METHOD,
defaultLockAtMostFor = "${your-app-config-root.scheduling.shedlock.max-time-lock-should-kept}",
defaultLockAtLeastFor = "${your-app-config-root.scheduling.shedlock.min-time-lock-should-kept}")
public class SchedulingConfiguration {
#Bean
public LockProvider lockProvider(final DataSource dataSource) {
return new JdbcTemplateLockProvider(dataSource);
}
}
The Cron job itself
import io.your-app-config-root.platform.cleanup.CleanupService;
import io.your-app-config-root.platform.cleanup.metric.MetricService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import static io.your-app-config-root.platform.cleanup.scheduler.AlertOnUnfinishedCleanupJob.ALERT_ON_UNFINISHED_CLEANUP_SCHEDULER_PROPERTIES;
/**
* This scheduled job is responsible for alerting on unfinished cleanup jobs after 24 hour.
* ShedLock included for making sure not running concurrent jobs on the same tasks at the same time.
*/
#Slf4j
#Component
#ConditionalOnProperty(value = ALERT_ON_UNFINISHED_CLEANUP_SCHEDULER_PROPERTIES + ".enabled", havingValue = "true")
#RequiredArgsConstructor
public class AlertOnUnfinishedCleanupJob {
public static final String ALERT_ON_UNFINISHED_CLEANUP_SCHEDULER_PROPERTIES = "your-app-config-root.scheduling.alert-on-unfinished-cleanup-scheduler";
private final CleanupService cleanupService;
private final MetricService metricService;
#Scheduled(cron = "${" + ALERT_ON_UNFINISHED_CLEANUP_SCHEDULER_PROPERTIES + ".cron}")
#SchedulerLock(name = "alertOnUnfinishedCleanup")
public void alertOnUnfinishedCleanup() {
log.info("Alert on unfinished cleanup job has started.");
// DO THINGS
}
}
Notice that this cron job can be turned on or off via env var depending on your needs.
The sql that I used for db schema migration via flyway.
CREATE TABLE shedlock
(
name varchar(64) UNIQUE NOT NULL,
lock_until timestamp(3) NOT NULL,
locked_at timestamp(3) NOT NULL,
locked_by varchar(36) NOT NULL,
CONSTRAINT pk_schedlock_name PRIMARY KEY (name)
);
There are a plenty of online cron generator to help you to generate your cron expression.
You wrote you need to run your job every 10 min, so the right expression for it
"*/10 * * * * *".
If you have any further questoin, please give more details. :)
how I can run Javascript file in the flutter_webview_plugin. I try it with this.
flutterWebViewPlugin.evalJavascript("require('./index.js');");
But nothing happens.
when I try to run flutter code it's shows nothing
my index.Js file contains a simple alert statement
alert('hello world');
First, You used "require" function. this function is not implemented in javascript itself. it's a part of NodeJs. so that function will not work.
In order to load a js file into flutter, you should consider it as a text file and load it properly. So, you need to add the file to assets folder, add into pubspec file, then load it. read the full answer here
Second, you used evalJavascript. this function can be used in many different situations. but it will work only if you have a view panel.
Check below example:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
main() async {
String jsCode = await rootBundle.loadString('assets/javascript.js');
runApp(new MaterialApp(
home: LunchWebView(jsCode),
));
}
class LunchWebView extends StatelessWidget {
final String text;
LunchWebView(this.text);
#override
Widget build(BuildContext context) {
final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
flutterWebviewPlugin.launch('https://www.google.com');
flutterWebviewPlugin.evalJavascript(text);
return Container();
}
}
NOTE: : I didn't handle reloading and other exceptions. you should check if there is any webview object open and then call Lunch method.
I am trying to get and access the elements from a pop-up/alert using selenium in java. Here is the code:
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Test {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "path_to_gecko_driver");
FirefoxDriver firefoxDriver = new FirefoxDriver();
firefoxDriver.get("some_url_which_needs_webcam_and_microphone");
WebElement element = new WebDriverWait(firefoxDriver, 20).until(ExpectedConditions.presenceOfElementLocated(new By.ByClassName("button_id")));
element.click();
JavascriptExecutor js = (JavascriptExecutor) firefoxDriver;
String title = String.valueOf(js.executeScript("return document.title"));
System.out.println("Title ==== " + title);
Object rezult = js.executeScript("return document.getElementById(\'nav-bar\')");
System.out.println("Browser element ==== " + rezult); //===>null
System.out.println("FINISH");
}
}
I am trying to access the browser pop-up elements, so I can choose between the available webcams or microphones and allow or deny the access. The JS code works just fine in the browser's console, but not in Java.
Any time I try to access any element in Java by using the JavascriptExecutor the element is null.
How can I access the pop-up elements by using the JavascriptExecutor in Java? Are there any other predefined configs or any other prerequisites that I am missing? Thank you
As you are invoking click() prior to this action we should induce WebDriverWait for the WebElement identified as getElementById('nav-bar') to render properly through ExpectedConditions.elementToBeClickable and try the following :
js.executeScript("return document.getElementById('nav-bar')");
package com.MavenLearning.Login;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class LoginOne {
#Test
public void LoginTestOne()
{
{
System.setProperty("webdriver.gecko.driver","C:\\Webdriver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.demo.guru99.com/v4/");
driver.findElement(By.name("uid")).sendKeys("mngr105709");
driver.findElement(By.name("password")).sendKeys("jajeten");
driver.findElement(By.name("btnLogin")).click();
assertEquals(driver.getTitle(), "Guru99 Bank Manager HomePage");
String A = driver.getTitle();
System.out.println(A);
String B = "Guru99 Bank Manager HomePage";
System.out.println(B);
if (A.equals(B))
System.out.println("Page Title matches");
else
System.out.println("Page Title Doesn't Match");
}
}
}
Seniors, I have written my code in Selenium and stored it in a global method. I don't know how to call the method in the other class. When I was learning Selenium with Java I was easily calling methods to different class but stuck now with TestNG. I have tried importing the method package so everything should work but no success. Thanks in advance for help.
From Global if you mean public static then you just need to call it like below:
ClassName.functionName()
If it is not static then you need to create an object of that class and then call the function like:
MyClass my = new MyClass();
my.MyFunctionName();
Updated
You need to create a xml file and specifically all classes which you need to execute.
Example of xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="example suite 1" verbose="1" >
<test name="Regression suite 1" >
<classes>
<class name="com.first.example.demoOne"/>
<class name="com.first.example.demoTwo"/>
<class name="com.second.example.demoThree"/>
</classes>
</test>
</suite>
Source:
http://www.seleniumeasy.com/testng-tutorials/testngxml-example-to-execute-with-class-names
Video tutorial:
https://www.youtube.com/watch?v=cNhnqVWD_54
Vaadin 7 supports custom javascript. But my question is if we want to integrate jQuery-ui with vaadin7, how can we add jQuery-ui css files. At the moment #Javascript supports adding javascript only. If we wanna add css, we have add that as sass style.
To add jQuery (or any other javascript library) to a Vaadin 7 application, follow these easy steps:
First Create a Vaadin project either using your favorite IDE or the vaadin maven archetype (or both). Create a new class that extends from VaadinServlet, and override the servletInitialized method:
import javax.servlet.ServletException;
import com.vaadin.server.BootstrapFragmentResponse;
import com.vaadin.server.BootstrapListener;
import com.vaadin.server.BootstrapPageResponse;
import com.vaadin.server.ServiceException;
import com.vaadin.server.SessionInitEvent;
import com.vaadin.server.SessionInitListener;
import com.vaadin.server.VaadinServlet;
public class TestJqueryVaadinServlet extends VaadinServlet {
#Override
protected void servletInitialized() throws ServletException {
super.servletInitialized();
getService().addSessionInitListener(new SessionInitListener() {
#Override
public void sessionInit(SessionInitEvent event) throws ServiceException {
event.getSession().addBootstrapListener(new BootstrapListener() {
#Override
public void modifyBootstrapPage(BootstrapPageResponse response) {
// With this code, Vaadin servlet will add the line:
//
// <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" />
//
// as the first line inside the document's head tag in the generated html document
response.getDocument().head().prependElement("script").attr("type", "text/javascript").attr("src", "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js");
}
#Override
public void modifyBootstrapFragment(BootstrapFragmentResponse response) {}
});
}
});
}
}
Then add the reference to the servlet in your web.xml or annotate the class with the #WebServlet annotation.
And then Create your jQuery snippet and invoke it using the JavaScript class, for example:
public class MyVaadinUI extends UI {
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Label label = new Label("This will fade-out once you click the button");
Button button = new Button("Hide Label");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
JavaScript.getCurrent().execute("$('.v-label').animate({opacity: 0.0}, 3000);");
}
});
layout.addComponent(label);
layout.addComponent(button);
}
}
Including style sheets or JavaScript files in your add-ons or as a part of your application can now be done by adding a #StyleSheet or #JavaScript annotation to a Component or Extension class. Each annotation takes a list of strings with URLs to the resources that should be loaded on the page before the framework initializes the client-side Component or Extension.
The URLs can either be complete absolute urls (e.g."https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js") or relative URLs (e.g. "redbutton.css"). A relative URL is converted to a special URL that will download the file from the Java package where the defining class is located. This means that e.g. #StyleSheet({"redbutton.css"}) on the class com.example.RedButton will cause the file com/example/redbutton.css on the classpath to be loaded in the browser. #JavaScript works in exactly the same way
#!java
#StyleSheet("redbutton.css")
public class RedButton extends NativeButton {
public RedButton(String caption) {
super(caption);
addStyleName("redButton");
}
}
In this simple example, the RedButton component just adds a
redButton
style name to a normal
NativeButton
. redbutton.css is located in the same folder as RedButton.java and has this content:
#!css
.redButton {
background-color: red;
}
This new mechanism makes it very easy to include style sheet or JavaScript files with add-ons and automatically load them in the browser when the add-on is used.
Second and my favorite way:
you can also use the #Stylesheet and #Javascript annotations. its much simpler.
#StyleSheet({
/*
* JQuery UI
*/
"vaadin://jquery/jquery-ui-1.9.2.custom/css/ui-darkness/jquery-ui-1.9.2.custom.min.css",
})
#JavaScript({
/*
* JQuery
*/
"vaadin://jquery/jquery-1.11.1.min.js",
/*
* JQuery UI
*/
"vaadin://jquery/jquery-ui-1.9.2.custom/js/jquery-ui-1.9.2.custom.min.js",
})
public class MyUI extends UI {
...
}