Selenium: how to execute user-extensions.js from java code - java

I want to test a smart GWT app using Selenium.
For this I need to add up
1. user-extensions.js
2. user-extensions-ide.js
in the IDE.
This gives an additional scLocators for locating GWT elements on the page
Now if I want to test the above page using Java, then where will I add these js files in the code

The way I approached this was using the SeleniumServer method, which allowed me to specify my extension file from the java code.
A working SmartGWT example is:
public class Example {
SeleniumServer server = null;
Selenium selenium = null;
HttpCommandProcessor proc = null;
#Before
public void setUp() throws Exception {
RemoteControlConfiguration config = new RemoteControlConfiguration();
config.setUserExtensions(new File("bin/selenium/user-extensions.js"));
server = new SeleniumServer(config);
server.boot();
proc = new HttpCommandProcessor("localhost",
4444,
"*firefox",
"http://test");
selenium = new DefaultSelenium(
proc);
selenium.start();
selenium.open("http://test");
}
#Test
public String justATest() {
execCommand("waitForElementClickable", "scLocator=//Window[ID=\"errorWindow\"]/item[0][Class=\"Label\"]/");
String elementTest = selenium.getText("scLocator=//Window[ID=\"errorWindow\"]/item[0][Class=\"Label\"]/");
assertEquals(elementTest, "lorem");
}
protected String execCommand(String command, String locator) {
String[] locatorArg = {locator};
return proc.doCommand(command, locatorArg);
}
#After
public void stopSelenium() {
System.out.println("in after hook");
if (selenium != null) {
selenium.deleteAllVisibleCookies();
selenium.stop();
}
if (server != null) {
server.stop();
}
System.out.println("after after hook");
}
}

Related

How to Validate ui data with rest api responses

I need to validate my ui data and api responses are same,
here is my code I tried,
private ValidateContentPage cp = new ValidateContentPage();
public void getTitle() {
String UITitle = driver.findElement(titlepage).getText();
System.out.println(UITitle);
Assert.assertEquals(UITitle, cp.getAPICall(),"Passed");
}
here im getting my api responses,
public class ValidateContentPage {
public common cm = new common();
public Properties prop;
public void baseURI() {
prop = cm.getProperties("./src/test/API/IndiaOne/propertyfile/EndpointURL.properties");
RestAssured.baseURI = prop.getProperty("baseURI");
}
public String getAPICall() {
objectpojo ps = given().expect().defaultParser(Parser.JSON).when().get(prop.getProperty("resources")).as(objectpojo.class, cm.getMapper());
int number = ps.getPosts().size();
System.out.println(number);
System.out.println(ps.getPosts().get(0).getTitle());
return ps.getPosts().get(0).getTitle();
}
If i validate both using testng assertion it throwing null pointer exception, anyone help me on how to validate my ui data and api responses.
You need to call your ValidateContentPage from #Test itself or from #BeforeTest
#Test
public void getTitle() {
String UITitle = driver.findElement(titlepage).getText();
System.out.println(UITitle);
ValidateContentPage cp = new ValidateContentPage();
Assert.assertEquals(UITitle, cp.getAPICall(),"Passed");
}

How to spock integration test with standalone tomcat runner?

Our project is not currently using a spring framework.
Therefore, it is being tested based on the standalone tomcat runner.
However, since integration-enabled tests such as #SpringBootTest are not possible, Tomcat is operated in advance and the HTTP API test is carried out using Spock.
Is there a way to turn this like #SpringBootTest?
TomcatRunner
private Tomcat tomcat = null;
private int port = 8080;
private String contextPath = null;
private String docBase = null;
private Context rootContext = null;
public Tomcat8Launcher(){
init();
}
public Tomcat8Launcher(int port, String contextPath, String docBase){
this.port = port;
this.contextPath = contextPath;
this.docBase = docBase;
init();
}
private void init(){
tomcat = new Tomcat();
tomcat.setPort(port);
tomcat.enableNaming();
if(contextPath == null){
contextPath = "";
}
if(docBase == null){
File base = new File(System.getProperty("java.io.tmpdir"));
docBase = base.getAbsolutePath();
}
rootContext = tomcat.addContext(contextPath, docBase);
}
public void addServlet(String servletName, String uri, HttpServlet servlet){
Tomcat.addServlet(this.rootContext, servletName, servlet);
rootContext.addServletMapping(uri, servletName);
}
public void addListenerServlet(ServletContextListener listener){
rootContext.addApplicationListener(listener.getClass().getName());
}
public void startServer() throws LifecycleException {
tomcat.start();
tomcat.getServer().await();
}
public void stopServer() throws LifecycleException {
tomcat.stop();
}
public static void main(String[] args) throws Exception {
System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");
System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, "org.apache.naming");
Tomcat8Launcher tomcatServer = new Tomcat8Launcher();
tomcatServer.addListenerServlet(new ConfigInitBaseServlet());
tomcatServer.addServlet("restServlet", "/rest/*", new RestServlet());
tomcatServer.addServlet("jsonServlet", "/json/*", new JsonServlet());
tomcatServer.startServer();
}
Spock API Test example
class apiTest extends Specification {
//static final Tomcat8Launcher tomcat = new Tomcat8Launcher()
static final String testURL = "http://localhost:8080/api/"
#Shared
def restClient
def setupSpec() {
// tomcat.main()
restClient = new RESTClient(testURL)
}
def 'findAll user'() {
when:
def response = restClient.get([path: 'user/all'])
then:
with(response){
status == 200
contentType == "application/json"
}
}
}
The test will not work if the annotations are removed from the annotations below.
// static final Tomcat8Launcher tomcat = new Tomcat8Launcher()
This line is specified API Test at the top.
// tomcat.main()
This line is specified API Test setupSpec() method
I don't know why, but only logs are recorded after Tomcat has operated and the test method is not executed.
Is there a way to fix this?
I would suggest to create a Spock extension to encapsulate everything you need. See writing custom extensions of the Spock docs as well as the built-in extensions for inspiration.

Unable to merge multiple classes in Extent Report in selenium java

I am trying to merge multiple test cases from various classes into one extent report. All test cases are running successfully but it is not adding those test cases into my extent report. The version of my Extent Report is 2.41.2.It is showing the previous extent report only, No new report showing all the test cases is generated. I am successfully generating a single class report but not able to generate multiple classes extent report. Here is my code:
// First I have created a base class for Extent Report:
public static ExtentHtmlReporter htmlReporter;
public static ExtentReports extent;
public static ExtentTest test;
#BeforeSuite
public void setUp()
{
htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir") +"/test-output/MyOwnReport.html");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("OS", "Mac Sierra");
extent.setSystemInfo("Host Name", "Krishna");
extent.setSystemInfo("Environment", "QA");
extent.setSystemInfo("User Name", "Krishna Sakinala");
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setDocumentTitle("AutomationTesting.in Demo Report");
htmlReporter.config().setReportName("My Own Report");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
#AfterSuite
public void tearDown()
{
extent.flush();
}
}
// Now Logintestcase Extending Base Extent report class:
public class LoginTestCase extends ExtentReportBaseClass {
static WebDriver driver;
Homepage login = new Homepage();
UtilityMethods util = new UtilityMethods();
String locUsernameElem;
String locPasswordelem;
String Sign_in;
String insertEmail;
String insertFirstName;
String createAccountButton;
// #Parameters("browser")
#BeforeClass
public void launchBrowser() {
driver = UtilityMethods.openBrowser(ConstantsValues.BROWSER_NAME);
UtilityMethods.launchWebsite(Utility.ConstantsValues.URL);
driver.manage().window().maximize();
}
#Test
public void registration() throws InterruptedException {
test = extent.createTest("registration", "This will check status for registration of the user.");
Sign_in = Utility.ConstantsValues.SIGN_IN;
insertEmail = Utility.ConstantsValues.EMAIL_ADDRESS;
createAccountButton = Utility.ConstantsValues.CREATE_ACOUNT;
// insertFirstName=ConstantsValues.USER_FIRSTNAME;
util.clickElement(Sign_in);
Thread.sleep(2000);
// driver.findElement(By.xpath("//input[#id='email_create']")).sendKeys("vivekkumar9652gmail.com");
util.sendData(insertEmail);
util.clickElement(ConstantsValues.CREATE_ACCOUNT);
util.clickElement(ConstantsValues.USER_TITLE);
util.sendDataById("customer_firstname", ConstantsValues.FIRST_NAME);
util.sendDataById("customer_lastname", ConstantsValues.LAST_NAME);
// util.sendData(ConstantsValues.LAST_NAME);
util.sendData(ConstantsValues.USER_PASSWORD);
util.clickElement(ConstantsValues.USER_NEWSLETTER);
Select day = new Select(driver.findElement(By.id("days")));
day.selectByValue("1");
Select month = new Select(driver.findElement(By.id("months")));
month.selectByValue("2");
Select year = new Select(driver.findElement(By.id("years")));
year.selectByValue("2014");
util.sendData(ConstantsValues.USER_COMPANY);
util.sendData(ConstantsValues.USER_STATE);
util.sendData(ConstantsValues.USER_ADDRESS1);
util.sendData(ConstantsValues.USER_MOBILENUMBER);
util.sendData(ConstantsValues.USER_ZIPCODE);
util.sendData(ConstantsValues.USER_ALIAS);
util.sendData(ConstantsValues.USER_CITY);
util.clickElement(ConstantsValues.SUBMITACCOUNT);
util.clickElement(ConstantsValues.USER_SIGN_OUT);
test.log(Status.PASS, MarkupHelper.createLabel("PASS", ExtentColor.GREEN));
}
#Test
public void userLogin() {
test = extent.createTest("userLogin", "This will check status for login of the user");
// util.clickElement(ConstantsValues.SIGN_IN);
util.sendData(ConstantsValues.LOGIN_USERNAME);
util.sendData(ConstantsValues.LOGIN_PASSWORD);
util.clickElement(ConstantsValues.USER_SIGNIN_Account);
//Assert.assertNotEquals("Krishna", "Krishna");
test.log(Status.PASS, MarkupHelper.createLabel("PASS", ExtentColor.RED));
}
}
//Now another class Extending BaseExtentReport Class:
public class PurchaseItemTestCase extends ExtentReportBaseClass {
WebDriver driver;
UtilityMethods util = new UtilityMethods();
// #Parameters("browser")
#BeforeClass
public void launchBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver = UtilityMethods.openBrowser(ConstantsValues.BROWSER_NAME);
UtilityMethods.launchWebsite(Utility.ConstantsValues.URL);
driver.manage().window().maximize();
}
#Test
public void chkPurchaseItem() throws InterruptedException {
test = extent.createTest("chkPurchaseItem", "This will check status for purchasing an item.");
driver.findElement(By.xpath("//img[#title='Faded Short Sleeve T-shirts']")).click();
driver.switchTo().defaultContent();
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(#id,'fancy')]")));
System.out.println("after frame");
Thread.sleep(4000);
driver.findElement(By.xpath("//button[#type='submit']//span[contains(.,'Add')]")).click();
Set handles = driver.getWindowHandles();
System.out.println(handles);
// Pass a window handle to the other window
for (String handle1 : driver.getWindowHandles()) {
System.out.println(handle1);
driver.switchTo().window(handle1);
Thread.sleep(3000);
driver.findElement(By.xpath("//a[#title='Proceed to checkout']//span[contains(.,'Proceed')]")).click();
Thread.sleep(3000);
driver.findElement(By.xpath(
"//a[#class='button btn btn-default standard-checkout button-medium']//span[contains(.,'Proceed')]//i[#class='icon-chevron-right right']"))
.click();
driver.findElement(By.id("email")).sendKeys("vivekkumar009#gmail.com");
driver.findElement(By.id("passwd")).sendKeys("vivek123");
Thread.sleep(3000);
// UtilityMethods.getdriver().findElement(By.id("SubmitLogin"));
driver.findElement(By.id("SubmitLogin")).click();
driver.findElement(By.name("processAddress")).click();
driver.findElement(By.id("cgv")).click();
driver.findElement(By.xpath("//button[#name=\"processCarrier\"]")).click();
driver.findElement(By.className("cheque")).click();
driver.findElement(By.xpath("//span[contains(text(),'I confirm my order')]")).click();
test.log(Status.PASS, MarkupHelper.createLabel("PASS", ExtentColor.GREEN));
}
}
}
Make your extent test as thread local variable.
Example:
Public ThreadLocal<ExtentTest> test;

Variables from properties.file not being passed - TestNG - WebDriver Test

I am using Webdriver + TestNG. I created a class where you can run any test with the browser of your choice just by using the method below where you enter which browser to run and what test to run as your variables. Now I am trying to feed my "browser" variable and "test" variable from a properties file. When I run it I just get a Pass but nothing happens. If I manually enter the variables it works fine. How come it wont take the values from the properties file? If I do a print - it prints the correct value...
This is the contents of the properties file:
browser="BROWSER GOES HERE"
test="TEST GOES HERE"
Here is my method to run the test:
#Test
public void runTest() throws IOException {
Properties prop = new Properties();
prop.load(new FileInputStream(
"path\\test.properties"));
localBrowser(prop.getProperty("browser"));
masterTest(driver, prop.getProperty("test"));
}
Here is a sandbox example of my test:
If I put the variables in myself the browser will open and execute the test. If I use the property loader it will just print the variables but will not run the test. Here is a sandbox example so you can try it.
Package Structure:
-src/test/java
--SandboxTest
-src/test/resources
--test.properties
Properties File example:
browser=firefox
test=test1
Class example:
public class SandboxTest {
private WebDriver driver;
InputStream input = null;
Properties prop = new Properties();
#Test
public void runTest() throws FileNotFoundException, IOException {
input = new FileInputStream(
(new File(
"C:INSERT_PATH_HERE\\test.properties")));
prop.load(input);
//This doesnt run the test
System.out.println(prop.getProperty("browser"));
System.out.println(prop.getProperty("test"));
localBrowser(prop.getProperty("browser"));
masterTest(driver, prop.getProperty("test"));
/*
* This works
* localBrowser("firefox");
* masterTest(driver, "test1");
*/
}
public void localBrowser(String browser) {
if (browser == "firefox") {
driver = new FirefoxDriver();
} else if (browser == "chrome") {
System.setProperty("webdriver.chrome.driver",
"C:\\INSERT_PATH_HERE\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browser == "ie") {
System.setProperty("webdriver.ie.driver",
"C:\\INSERT_PATH_HERE\\IEDriverServer.exe");
driver = new InternetExplorerDriver(caps);
}
}
public void masterTest(WebDriver driver, String test) {
if (test == "test1") {
Test1(driver);
} else if (test == "test2") {
Test2(driver);
}
}
// *********************************TESTS*****************************************************
public void Test1(WebDriver driver) {
driver.get("http://www.marca.com/en/");
driver.findElement(By.linkText("Barcelona")).click();
}
public void Test2(WebDriver driver) {
driver.get("http://www.marca.com");
driver.findElement(By.linkText("FĂștbol")).click();
}
}
Well.. I am really not sure what you are doing, But if it doesn't work so probably it doesn't load the properties file properly.
try this one
Resource resource = new ClassPathResource("/environment.properties");
properties = PropertiesLoaderUtils.loadProperties(resource);
Tell me if that is ok, hope that helps
EDIT:
The above is part of Spring,
you can use
prop.load(new FileInputStream(new File("test.properties")));
Please make sure that test.properties will be under src folder in the project
EDIT:
The problem not in the property file.. The problem is in the way you are comparing 2 strings
When you do browser == "firefox" The check is for the object address(referenec)
When you are comparing Object type you need to use Eqauls
For example browser.equals("firefox") It will work this way.
Because when you put the value your self it check the refernece and it is the same.. Once you get from property this is 2 diffrent objects but they are "equal" So it will work only with Equals
What you should do instead is put the property in the testing.xml file and then read the property from there instead. Then, if you need to have different property files, you can just create multiple testing.xml files and when you execute the tests just pass the testng.xml file as an argument to TestNG.
In the project I referenced above in the hyperlink, you can see I reference the properties something like so:
#BeforeClass
public void setUp( ITestContext context ) {
suiteParams = context.getSuite().getXmlSuite().getAllParameters();
String browser = suiteParams.get( "browser" );
String sauceUser = suiteParams.get( "sauceUser" );
String sauceKey = suiteParams.get( "sauceKey" )
....
If you have to do it using a properties file, then I would change you code and do it differently. Something like so (assuming use of TestNG):
protected WebDriver driver;
protected String browser;
#BeforeTest
public void setUp() {
Properties prop = new Properties();
prop.load( new FileInputStream("path/test.properties") );
browser = prop.getProperty("browser");
if ( browser.equals("firefox") {
driver = new FirefoxDriver();
} else {
driver = null; // bad choice
}
}
#Test
public void runTest() throws IOException {
driver.navigateTo( url);
// do stuff
Assert.assertTrue( 1 == 1 );
}
#AfterTest
public void cleanUp() {
driver.quit();
}

How to hook into the internal Eclipse browser?

For my eclipse plugin I want to track every URL that is opened with the internal (and if possible also external) Eclipse browser.
So far I use
org.eclipse.swt.browser.Browser;
and
addLocationListener(...)
But I would prefer that it works also for the internal Eclipse browser. How can I achieve that?
One possible solution for the Eclipse Internal Browser would be to create an eclipse plugin that registers an IStartup extension. In your earlyStartup() method you would register an IPartListener on the workbenchPage. Then when the internal browser part is created, you will receive a callback with a reference to the WebBrowserEditor (or WebBrowserView). Since there is no direct API you will have to hack a bit and use reflection to grab the internal SWT Browser instance. Once you have that, you can add your location listener.
Sometimes during early startup there is no active Workbench window yet so you have to loop through all existing workbench windows (usually just one) and each of their workbench pages to add part listeners also.
Here is the snippet of code for the earlyStartup() routine. Note that I have omitted any cleanup of listeners during dispose for windows/pages so that still needs to be done.
//Add this code to an IStartup.earlyStartup() method
final IPartListener partListener = new IPartListener() {
#Override
public void partOpened(IWorkbenchPart part) {
if (part instanceof WebBrowserEditor)
{
WebBrowserEditor editor = (WebBrowserEditor) part;
try {
Field webBrowser = editor.getClass().getDeclaredField("webBrowser");
webBrowser.setAccessible(true);
BrowserViewer viewer = (BrowserViewer)webBrowser.get(editor);
Field browser = viewer.getClass().getDeclaredField("browser");
browser.setAccessible(true);
Browser swtBrowser = (Browser) browser.get(viewer);
swtBrowser.addLocationListener(new LocationListener() {
#Override
public void changed(LocationEvent event) {
System.out.println(event.location);
}
});
} catch (Exception e) {
}
}
else if (part instanceof WebBrowserView)
{
WebBrowserView view = (WebBrowserView) part;
try {
Field webBrowser = editor.getClass().getDeclaredField("viewer");
webBrowser.setAccessible(true);
BrowserViewer viewer = (BrowserViewer)webBrowser.get(view);
Field browser = viewer.getClass().getDeclaredField("browser");
browser.setAccessible(true);
Browser swtBrowser = (Browser) browser.get(viewer);
swtBrowser.addLocationListener(new LocationListener() {
#Override
public void changed(LocationEvent event) {
System.out.println(event.location);
}
});
} catch (Exception e) {
}
}
}
...
};
final IPageListener pageListener = new IPageListener() {
#Override
public void pageOpened(IWorkbenchPage page) {
page.addPartListener(partListener);
}
...
};
final IWindowListener windowListener = new IWindowListener() {
#Override
public void windowOpened(IWorkbenchWindow window) {
window.addPageListener(pageListener);
}
...
};
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (activeWindow != null)
{
IWorkbenchPage activePage = activeWindow.getActivePage();
if (activePage != null)
{
activePage.addPartListener(partListener);
}
else
{
activeWindow.addPageListener(pageListener);
}
}
else
{
for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows())
{
for (IWorkbenchPage page : window.getPages()) {
page.addPartListener(partListener);
}
window.addPageListener(pageListener);
}
PlatformUI.getWorkbench().addWindowListener(windowListener);
}
One last detail about this code snippet is that it requires a dependency on the org.eclipse.ui.browser plugin to have access to the WebBrowserEditor class.

Categories