How to test login page with multiple webpage(present in notepad) using selenium web driver Java? - selenium

I am testing like 100 url everything is working good. my problem is when the test starts it get web url from notepad then open the url here my process is to check the login or not in some case if the for example 10th url shows 404 error the test terminate here it cant process further urls. Any solution for this process...
my codes
public class File {
#Test(dataProvider="testdata")
public void sum(String url)
{
System.out.println(url);
}
#DataProvider
public Object[][] testdata(){
int count=20;
Object[][] obj = new Object[count][1];
for(int i=0;i<=count;i++)
{
String fileName = "E:\\ework\\Web\\bin\\Websearch\\test.txt";
try {
String line = null;
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
String[] abs={line};
int size = abs.length;
for(int j=0;j<=size;j++)
{
obj[i][0]=abs[j];
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
`}
return obj;
}
}
thank you.:)

If you are using framework like TestNG then look at DataProviders for the same.
Use Try{} Catch(Exception e){} block. Insert your assertion in try block and once the assertion fails then try to capture the exception in some list or other data structure and after all urls are processed then iterate over the exception list and report it in your Reports or logs.

Related

Null pointer exception while taking screenshot in selenium POM with extent report

A null pointer exception is thrown While trying to take screenshot when the scenario fails. I have an actions class in which i have defiled the capture screenshot method.
public static String capture(WebDriver driver) throws NullPointerException, IOException {
File scrFile;
scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File Dest = new File("D:\\Dinu\\SeleniumReports\\Test" + System.currentTimeMillis() + ".jpeg");
String filepath = Dest.getAbsolutePath();
org.openqa.selenium.io.FileHandler.copy(scrFile, Dest);
return filepath;
}
Extent reports are implemented using Itestlisterner interface. Below given code for which implements the screenshot method given:
public synchronized void onTestFailure(ITestResult result) {
System.out.println((result.getMethod().getMethodName() + " failed!"));
test.get().fail(result.getThrowable());
try {
String screenshotPath = actions.capture(driver);
test.get().addScreenCaptureFromPath(screenshotPath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And am getting the below error: Please help in resolving the same.
public static String getScreenhot(WebDriver driver, String screenshotName) throws Exception {
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
//after execution, you could see a folder "FailedTestsScreenshots" under src folder
String destination = System.getProperty("user.dir") + "/FailedTestsScreenshots/"+screenshotName+dateName+".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
return destination;
}
#AfterMethod
public void getResult(ITestResult result) throws IOException{
if(result.getStatus() == ITestResult.FAILURE){
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getName());
logger.log(LogStatus.FAIL, "Test Case Failed is "+result.getThrowable());
//To capture screenshot path and store the path of the screenshot in the string "screenshotPath"
//We do pass the path captured by this mehtod in to the extent reports using "logger.addScreenCapture" method.
String screenshotPath = ExtentReportsClass.getScreenshot(driver, result.getName());
//To add it in the extent report
logger.log(LogStatus.FAIL, logger.addScreenCapture(screenshotPath));
}else if(result.getStatus() == ITestResult.SKIP){
logger.log(LogStatus.SKIP, "Test Case Skipped is "+result.getName());
}
// ending test
//endTest(logger) : It ends the current test and prepares to create HTML report
extent.endTest(logger);
}

Scrapinghub/Splash website page fetching time increasing exponentially with parellel thread

In my trial, I hit splash instance with 50 parallel threads. Each thread will get the page source of the URL. My splash instance default slots value is 50. Here, website fetching time increases exponentially with the number of parallel threads. I can get the perfect HTML source for 50 URLs. But the time increases from 2 seconds to 45 seconds from 1st URL to 50th URL respectively. Please help me to reduce the time for fetching the page source.
My sample java code is
public class SplashThread implements Runnable {
private static final String splash ="http://localhost:8050/execute";
private String script = URLEncoder.encode("function main(splash, args) \n" +
"splash:go(args.url)\n"+
" splash.images_enabled = false\n" +
" splash:on_request(function(request)\n" +
" if string.find(request.url, \".css\")~= nil then\n" +
" request.abort()\n" +
" end\n" +
"end)\n" +
"local html = splash:html()\n" +
"return html\n"+
"end","UTF-8");
private String url =null;
public SplashThread(String url) throws UnsupportedEncodingException {
this.url = url;
}
#Override
public void run() {
HttpClientUtil clientUtil =null;
JSONObject json =null;
try {
Properties queryParms = new Properties();
queryParms.put("url",url);
queryParms.put("timeout","85.0");
queryParms.put("lua_source",script);
clientUtil = new HttpClientUtil(-1,false);
HttpResponse response = clientUtil.doGet(splash,queryParms,null);
String resp = ScrapyUtil.getResponseString(response,"UTF-8");
}
catch (Exception e){
e.printStackTrace();
System.out.println("JSN}ON :: "+json);
}
finally {
if(clientUtil!=null){
try {
clientUtil.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I am scheduling 50 threads of this runnable object with ScheduledExecutorService.
If I am fecthing the page source once by one, It will working perfectly. But I need to fecth concurrently.

AsyncTask doInBackground() does not execute correctly on run, but works on debugger

#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
ArrayList<HashMap<String, String>> PLIST = new ArrayList<>();
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(jsonUrl);
ArrayList<String> URLList = new ArrayList<>();
if (jsonStr != null) {
placesList.clear();
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray placesJsonArray = jsonObj.getJSONArray("results");
String pToken = "";
// looping through All Places
for (int i = 0; i < placesJsonArray.length(); i++) {
JSONObject placesJSONObject = placesJsonArray.getJSONObject(i);
String id = placesJSONObject.getString("id");
String name = placesJSONObject.getString("name");
HashMap<String, String> places = new HashMap<>();
// adding each child node to HashMap key => value
places.put("id", id);
places.put("name", name);
PLIST.add(places);
}
//TODO: fix this...
if (SEARCH_RADIUS == 1500) {
Log.e(TAG, "did it get to 1500?");
try {
for (int k = 0; k < 2; k++) {
//error is no value for next_page_token... this
ERROR HERE
pToken = jsonObj.getString("next_page_token"); //if I place breakpoint here, debugger runs correctly, and returns more than 20 results if there is a next_page_token.
String newjsonUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
+ midpointLocation.getLatitude() + "," + midpointLocation.getLongitude()
+ "&radius=" + SEARCH_RADIUS + "&key=AIzaSyCiK0Gnape_SW-53Fnva09IjEGvn55pQ8I&pagetoken=" + pToken;
URLList.add(newjsonUrl);
jsonObj = new JSONObject(new HttpHandler().makeServiceCall(newjsonUrl)); //moved
Log.e(TAG, "page does this try catch");
}
}
catch (Exception e ) {
Log.e(TAG, "page token not found: " + e.toString());
}
for (String url : URLList){
Log.e(TAG, "url is : " + url);
}
I made an ArrayList of URLS after many attempts to debug this code, I planned on unpacking the ArrayList after all the urls with next_page_tokens were added, and then parsing through each of them later. When running the debugger with the breakpoint on pToken = getString("next_page_token") i get the first url from the Logger, and then the second url correctly. When I run as is, I get the first url, and then the following error: JSONException: No value for next_page_token
Things I've tried
Invalidating Caches and restarting
Clean Build
Run on different SDK versions
Made sure that the if statement is hitting (SEARCH_RADIUS == 1500)
Any help would be much appreciated, thanks!
Function is called in a listener function like this.
new GetPlaces(new AsyncResponse() {
#Override
public void processFinish(ArrayList<HashMap<String, String>> output) {
Log.e(TAG, "outputasync:" );
placesList = output;
}
}).execute();
My onPostExecute method.
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
delegate.processFinish(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
It turns out that the google places api takes a few milliseconds to validate the next_page_token after it is generated. As such, I have used the wait() function to pause before creating the newly generated url based on the next_page_token. This fixed my problem. Thanks for the help.

Unable to add screenshot in ReportNG HTML report

I am trying to take a screenshot for failure methods and also want to put the same in my Report, I am able to take the screenshot but unable to show the same in HTML report. Following is my code, friends any clue on this ?
public class SB1 {
private static Logger logger = Logger.getLogger(SB1.class);
WebDriver driver = new FirefoxDriver();
#Test
public void Testone() {
driver.get("http://www.google.com/");
assert false;
}
public void catchExceptions(ITestResult result) {
System.out.println("result" + result);
String methodName = result.getName();
System.out.println(methodName);
if (!result.isSuccess()) {
try {
String failureImageFileName = new SimpleDateFormat("MM-dd-yyyy_HH-ss").format(new GregorianCalendar().getTime())+ ".png";
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(failureImageFileName));
String userDirector = System.getProperty("user.dir") + "/";
Reporter.log("<a href=\""+ userDirector + failureImageFileName +"\"><img src=\"file:///" + userDirector
+ failureImageFileName + "\" alt=\"\""+ "height='100' width='100'/> "+"<br />");
Reporter.setCurrentTestResult(null);
} catch (IOException e1) {
e1.printStackTrace();
}
}
Have you set ESCAPE_PROPERTY to false? This is what you will have to do if you want reportng to post the screenshot -
private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
and in your setUp-
System.setProperty(ESCAPE_PROPERTY, "false");
I tried this. It seems like if you set the System Property to false, it removes the escaping from the ENTIRE log... From what I can tell, the report is generated after the test, with whatever the system property is set to at the time. I want to insert the screenshot (which worked with above code) but I do not want to remove the other formatting (br tags).
You can use following code.
Reporter.log("<br>Chrome driver launched for ClassOne</br>");
Or you can use customize method, where you do not need to append the br tag everytime, use following customized method.
public void customLogReport(String testCaseDescription) throws Exception{
try{
Reporter.log("<br>" + testCaseDescription + "</br>");
}catch(Exception e){
e.printStackTrace();
}
}

excel file upload using apache file upload

I am developing an testing automation tool in linux system. I dont have write permissions for tomcat directory which is located on server. I need to develop an application where we can select an excel file so that the excel content is automatically stored in already existing table.
For this pupose i have written an form to select an file which is posted to a servlet CommonsFileUploadServlet where i am storing the uploaded file and then calling ReadExcelFile class which reads the file path and create a vector for data in file which is used to sstore data in database.
My problem is that i am not able to store the uploaded file in directory. Is it necessary to have permission rights for tomcat to do this. Can i store the file on my system and pass the path to ReadExcelFile.class
Please guide me
My code is as follows:
Form in jsp
CommonsFileUploadServlet class code:
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024);
fileItemFactory.setRepository(new File("/home/example/Documents/Project/WEB-INF/tmp"));
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize());
File file = new File("/",item.getName());
String realPath = getServletContext().getRealPath("/")+"/"+item.getName();
item.write(file);
ReadExcelFile ref= new ReadExcelFile();
String res=ref.insertReq(realPath,"1");
}
out.close();
}
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}
ReadExcelFile code:
public static String insertReq(String fileName,String sno) {
//Read an Excel File and Store in a Vector
Vector dataHolder=readExcelFile(fileName,sno);
//store the data to database
storeCellDataToDatabase(dataHolder);
}
public static Vector readExcelFile(String fileName,String Sno)
{
/** --Define a Vector
--Holds Vectors Of Cells
*/
Vector cellVectorHolder = new Vector();
try{
/** Creating Input Stream**/
//InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int s=Integer.valueOf(Sno);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(s);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector=new Vector();
short minColIndex = myRow.getFirstCellNum();
short maxColIndex = myRow.getLastCellNum();
for(short colIndex = minColIndex; colIndex < maxColIndex; colIndex++)
{
HSSFCell myCell = myRow.getCell(colIndex);
if(myCell == null)
{
cellStoreVector.addElement(myCell);
}
else
{
cellStoreVector.addElement(myCell);
}
}
cellVectorHolder.addElement(cellStoreVector);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
private static void storeCellDataToDatabase(Vector dataHolder)
{
Connection conn;
Statement stmt;
String query;
try
{
// get connection and declare statement
int z;
for (int i=1;i<dataHolder.size(); i++)
{
z=0;
Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
String []stringCellValue=new String[10];
for (int j=0; j < cellStoreVector.size();j++,z++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
if(myCell==null)
stringCellValue[z]=" ";
else
stringCellValue[z] = myCell.toString();
}
try
{
//inserting into database
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
stmt.close();
conn.close();
System.out.println("success");
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
POI will happily open from an old InputStream, it needn't be a File one.
I'd suggest you look at the Commons FileUpload Streaming API and consider just passing the excel part straight to POI without touching the disk