RestAssured - Testing Restful API using Selenium and Test NG - when run throws connection timeout error - selenium

I am testing a Weather Rest API using Restassured and TestNG framework. Following is the code:
I made sure I have all the dependencies covered in pom.xml file
This is the error:
java.lang.NoSuchMethodError: org.testng.remote.AbstractRemoteTestNG.addListener(Lorg/testng/ISuiteListener;)V
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:122)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:137)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:58)
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class RestApi_Weather_GET {
#Test
void GetWeatherDetails(){
//specify the base uri
RestAssured.baseURI = "http://restapi.demoqa.com/utilities/weather/city/";
//Request object is being created
RequestSpecification ahttprequest = RestAssured.given();
//Response object
Response aresponse = ahttprequest.request(Method.GET, "Alameda");
//print response in console
String aresponseBody = aresponse.getBody().asString();
System.out.println("Response body is : "+aresponseBody);
}
}

Related

How can I Automate Google 2 step mobile verification in selenium?

Environment
Azure websites
Dot.net framework
Configuration
Selenium 3.14
Google Version 96.0.4664.110
Challenge
Using selenium automate Google 2 step mobile verification while singing in to application.
Tried using below code but not working.
import org.jboss.aerogear.security.otp.Totp;
public class TOTPGenerator {
/**
* Method is used to get the TOTP based on the security token
* #return
*/
public static String getTwoFactorCode(){
//Replace with your security key copied from step 12
Totp totp = new Totp("nlyyriaxspwdomi7buvo32cuas6tz7aa"); // 2FA secret key
String twoFactorCode = totp.now(); //Generated 2FA code here
return twoFactorCode;
}
}
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TwoFactorGmail {
public static void gmailSignIn(){
System.setProperty("webdriver.chrome.driver", "path of the exe file\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("your application url which embeds gmail sign-in");
driver.findElement(By.id("identifierId")).sendKeys("abc#gmail.com");
driver.findElement(By.id("identifierNext")).click();
driver.findElement(By.name("password")).sendKeys("password");
driver.findElement(By.id("passwordNext")).click();
// OTP value is returned from getTwoFactor method
driver.findElement(By.id("totpPin")).sendKeys(TOTPGenerator.getTwoFactorCode());
driver.findElement(By.id("totpNext")).click();
}
}

Java Selenium 'Cannot resolve symbol Test' TestNG

I have a problem with TestNG. I cannot run a test.
I am getting this error:
POM.xml has no errors.
Here is the code in test page:
import Pages.SearchPage;
import org.testng.annotations.Test;
import core.Web.AllListeners.*;
public class Search extends Listener {
#Test(groups = "Regression")
public void ticketBookingFunctionality() {
new SearchPage()
.openUrl()
.inputCaption("Comic")
.selectCityByValue()
.inputDateFrom("2020-01-01")
.inputDateTo("2021-07-05")
.clickButtonSearch()
.clickButtonBuy()
.chooseTicket()
.choosePrice()
.pushButtonFindTickets()
.closeLoginPopup();
}
}
Where can be the problem?
You need to add the following testng related jar files within your project.

Serenity report do not have any REST Query

We have a serenity and rest assured project.
But the test report does not generate RESTQuery button to check the request response
We query with given().when().body().get(APIURL)
the response comes but no rest query is found.
pom.xml
runner class
package test_suite;
import cucumber.api.CucumberOptions;
import net.serenitybdd.cucumber.CucumberWithSerenity;
import org.junit.runner.RunWith;
#RunWith(CucumberWithSerenity.class)
#CucumberOptions(
features = "src/test/resources/features",
plugin = {"pretty"},
glue = {"steps"}
)
public class CucumberTestSuite {
}
api object
#Step
public void HTTPRequest(String ****, String ***8){
String ApiUrl = method(somestring, somestring);
response = given().when().log().body().get(ApiUrl);
//response = RestAssured.get(ApiUrl);
//response = SerenityRest.when().get(ApiUrl);
}
Error while checking with SerenityRest
net.serenitybdd.core.exceptions.SerenityManagedException: net.serenitybdd.rest.decorators.request.RequestSpecificationDecorated.getDefinedFilters()Ljava/util/List;
IT worked now with serenity version 1.9.26
IT worked now with serenity version 1.9.26

How to open a html file available in local machine in selenium grid node

I have a html file in my local machine. When running my selenium-java code locally through eclipse, I can access the html file through the code mentioned below -
File file = new File(url);
driver.get("file:///" + file.getAbsolutePath());
If I run the code through selenium grid, registered node doesn't pick up the html file path to be opened in chrome since the absolute path points to the local machine.
Is there any solution available to open the locally available html file through selenium grid-node?
You should use a LocalFileDetector.
import org.openqa.selenium.remote.LocalFileDetector
import org.openqa.selenium.remote.RemoteWebDriver
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), DesiredCapabilities.firefox());
driver.setFileDetector(new LocalFileDetector())
Your upload should now work.
There are basically two ways in which you can get this done. I will list out both the approaches. Please feel free to pick and choose whichever works for you.
Using custom node servlet
You need to follow the below steps:
Create a new custom servlet, using which you can upload a file using a HTTP POST method.
It could look something like below [ This code is borrowed from a journaldev post here and being included here only for the sake of completeness] You may need to tweak the code before use and not necessarily use it as is. The current code returns a html response, but you may need to change it so that it returns a JSON response which contains the actual path where the file was uploaded to. This path is what you will use in your driver.get() call.
package com.journaldev.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadDownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
#Override
public void init() throws ServletException{
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or empty");
}
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
if(!file.exists()){
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::"+file.getAbsolutePath());
ServletContext ctx = getServletContext();
InputStream fis = new FileInputStream(file);
String mimeType = ctx.getMimeType(file.getAbsolutePath());
response.setContentType(mimeType != null? mimeType:"application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream os = response.getOutputStream();
byte[] bufferData = new byte[1024];
int read=0;
while((read = fis.read(bufferData))!= -1){
os.write(bufferData, 0, read);
}
os.flush();
os.close();
fis.close();
System.out.println("File downloaded at client successfully");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileItem.getName());
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
out.write("File "+fileItem.getName()+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileItem.getName()+"");
}
} catch (FileUploadException e) {
out.write("Exception in uploading file.");
} catch (Exception e) {
out.write("Exception in uploading file.");
}
out.write("</body></html>");
}
}
Create a sample project, which includes a dependency on the selenium libraries and which contains the servlet built in step (1) and create a jar out of it. For instructions on how to do all of this, you can refer to my blog post here (or) to the official selenium documentation here.
Start the node, along with the -servlets parameter so that your newly created node servlet, gets injected into the node and is available via http://<Node_IP_Address>:<Node_Port>/extra/UploadDownloadFileServlet (since our sample servlet's name was UploadDownloadFileServlet)
Now in your test code, you can create a new RemoteWebDriver instance as always.
You now need to upload your html file to the remote node where the new session was created. For doing that, you need to know the IP of the node where your test ran. So you make use of a library such as talk2grid (I built this library) or leverage the approach of determining this information on your own by referring to my blog here
Once you have the IP and port, you now trigger a HTTP POST to the servlet you created earlier by hitting the endpoint http://<Node_IP_Address>:<Node_Port>/extra/UploadDownloadFileServlet and get back the path to where it was uploaded in the response.
Now use the path that was returned in step (6) in your driver.get() call (don't forget to include the file:/// protocol)
That should do.
Using Javascript
In this approach, you basically start off by loading a blank page (for e.g., driver.get("about:blank"); and then make use of Javascript to start dynamically creating your web page via document.createElement() call (Refer to this article for more information ) and create the entire page. You can now start interacting with the page.
Approach (1) would be useful only when you are working with a grid environment wherein you are allowed to add servlets etc and access its IP and port.
Approach (2) will work in all use cases including third party remote execution environment providers such as SauceLabs or BrowserStack (In case you use them as well)

selenium firefox path setting problems

no matter what I do selenium doesn't accept my firefox path in the console where I launch it from. Keep getting the same error.
I also set the path as an environment variable in win 7 64.
I'm pretty much a virgin when it comes to selenium. Trying to run my first JUNIT test.
Here is the message from selenium.
21:46:43.481 INFO - Command request: getNewBrowserSession[*chrome, http://compendiumdev.co.uk/, ] on session null
21:46:43.497 INFO - creating new remote session
21:46:43.544 INFO - Got result: Failed to start new browser session: java.lang.RuntimeException: java.lang.RuntimeException: Firefox could not be found in the path!
Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox like this:
*firefox c:\blah\firefox.exe on session null
Below is my java code
package com.eviltester.seleniumtutorials;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MyFirstSeleniumTests {
Selenium selenium=null;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome",
http://compendiumdev.co.uk/");
selenium.start();
}
#Test
public void testExported() throws Exception {
selenium.open("/selenium/search.php");
selenium.type("q", "Selenium-RC");
selenium.click("name=btnG");
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
Thank you for the help.