Skip to content

Commit 9fb8a09

Browse files
author
Mat Walker
committed
Added closing of driver and url goto
1 parent 99e2797 commit 9fb8a09

File tree

1 file changed

+132
-20
lines changed

1 file changed

+132
-20
lines changed

src/main/java/TeamControlium/Controlium/SeleniumDriver.java

Lines changed: 132 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package TeamControlium.Controlium;
22

3-
import TeamControlium.Utilities.Logger;
3+
import TeamControlium.Utilities.*;
44

5-
import TeamControlium.Utilities.TestData;
5+
import org.apache.commons.io.FileUtils;
66
import org.apache.commons.io.FilenameUtils;
77
import org.apache.commons.lang3.time.StopWatch;
88
import org.junit.jupiter.api.Assertions;
@@ -306,6 +306,7 @@ public List<HTMLElement> findElements(HTMLElement parentElement, ObjectMapping m
306306
catch (WebDriverException e)
307307
{
308308
checkIfConnectionIssue(e);
309+
throw new RuntimeException("Selenium Driver error finding elements. See inner exception.",e);
309310
}
310311
catch (Exception e) {
311312
if (parentElement==null) {
@@ -338,6 +339,30 @@ public List<HTMLElement> findElements(HTMLElement parentElement, ObjectMapping m
338339
}
339340

340341

342+
public void gotoURL(String fullURLPath) {
343+
try {
344+
webDriver.navigate().to(fullURLPath);
345+
}
346+
catch (Exception e) {
347+
Logger.WriteLine(Logger.LogLevels.Error, "Error browsing to [%s]: %s",(fullURLPath==null || fullURLPath.isEmpty())?"NO URL!!":fullURLPath,e.getMessage());
348+
checkIfConnectionIssue(e);
349+
throw e;
350+
}
351+
}
352+
353+
public String getPageTitle() {
354+
try {
355+
String title = webDriver.getTitle();
356+
return (title==null?"":title);
357+
}
358+
catch (Exception e) {
359+
Logger.WriteLine(Logger.LogLevels.Error, "Error getting window title: %s",e.getMessage());
360+
checkIfConnectionIssue(e);
361+
throw e;
362+
}
363+
}
364+
365+
341366
//////////// JAVASCRIPT EXECUTION
342367

343368
/// <summary>Injects and executes Javascript in the currently active Selenium browser with no exception thrown. Javascript has return object which is passed back as a string</summary>
@@ -357,6 +382,7 @@ public <T> T executeJavaScript(Class<T> type, String script, Object... args)
357382
catch (WebDriverException e)
358383
{
359384
checkIfConnectionIssue(e);
385+
throw new RuntimeException("Selenium Driver error executing javascript. See inner exception.",e);
360386
}
361387
catch (Exception ex)
362388
{
@@ -383,24 +409,115 @@ public void executeJavaScriptNoReturnData(String script, Object[] args)
383409
Object dummy = executeJavaScript(Object.class,script,args);
384410
}
385411

386-
public void quit() {
387-
try {
388-
if (webDriver != null) {
389-
webDriver.quit();
412+
413+
public String TakeScreenshot() { return TakeScreenshot(null);}
414+
public String TakeScreenshot(String fileName)
415+
{
416+
String filename = null;
417+
String filepath = null;
418+
419+
try
420+
{
421+
if (webDriver != null)
422+
{
423+
if (webDriver instanceof TakesScreenshot)
424+
{
425+
try
426+
{
427+
fileName = TestData.getItem(String.class, "Screenshot", "Filename");
428+
}
429+
catch (Exception e){ }
430+
try
431+
{
432+
filepath = TestData.getItem(String.class, "Screenshot", "Filepath");
433+
}
434+
catch (Exception e) { }
435+
436+
if (filename == null) filename = (fileName==null)?"Screenshot" : fileName;
437+
438+
//
439+
// Ensure filename friendly
440+
//
441+
//filename = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars())))).Replace(filename, "");
442+
if (filepath == null)
443+
{
444+
445+
filename = Paths.get(System.getProperty("user.dir"),"images", filename + ".jpg").toString();
446+
}
447+
else
448+
{
449+
filename = Paths.get(filepath, filename + ".jpg").toString();
450+
}
451+
File screenshot=null;
452+
try {
453+
screenshot = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
454+
Logger.WriteLine(Logger.LogLevels.TestInformation, "Screenshot - {0}", filename);
455+
}
456+
catch (Exception e) {
457+
checkIfConnectionIssue(e);
458+
throw new RuntimeException("Selenium Driver error taking screenshot. See inner exception.",e);
459+
}
460+
461+
try {
462+
FileUtils.copyFile(screenshot, new File(filename));
463+
}
464+
catch (Exception e) {
465+
Logger.WriteLine(Logger.LogLevels.Error, "Saving Screenshot - %s: %s", filename,e);
466+
}
467+
return filename;
468+
}
469+
else
470+
{
471+
throw new RuntimeException("Error taking webDriver does not implement TakesScreenshot! Is it RemoteWebDriver?");
472+
}
473+
}
474+
else
475+
{
476+
Logger.WriteLine(Logger.LogLevels.TestInformation,"webDriver is null! Unable to take screenshot.");
390477
}
391478
}
392-
catch (Exception e) {};
479+
catch (Exception ex)
480+
{
481+
Logger.WriteLine(Logger.LogLevels.TestInformation, "Exception saving screenshot [{0}]", filename==null?"filename null!":filename);
482+
Logger.WriteLine(Logger.LogLevels.TestInformation, "> {0}", ex);
483+
}
484+
return "";
393485
}
394486

395-
public void finalize() {
396-
//
397-
// We use finalize here in full awareness that it MAY NOT be called and that it may be called after a full clean-up! We are only doing this to prevent
398-
// a ruckload of browsers accumulating! As finalize is a terrible method to use, we use it VERY carefully!
399-
//
487+
488+
public void CloseDriver() {
489+
boolean TakeScreenshotOption = false;
400490
try {
401-
webDriver.quit();
491+
try {
492+
TakeScreenshotOption = General.IsValueTrue(TestData.getItem(String.class, "Debug", "TakeScreenshot"));
493+
} catch (Exception ex) {
494+
Logger.WriteLine(Logger.LogLevels.TestInformation, "RunCategory Option [Debug, TakeScreenshot] Exception ignored, defaults to false: %s", ex);
495+
}
496+
497+
498+
if (TakeScreenshotOption) {
499+
Logger.WriteLine(Logger.LogLevels.FrameworkInformation, "Debug.TakeScreenshot = {0} - Taking screenshot...", TakeScreenshotOption);
500+
TakeScreenshot(Detokenizer.ProcessTokensInString("{Date;today;yy-MM-dd_HH-mm-ssFFF}"));
501+
} else
502+
Logger.WriteLine(Logger.LogLevels.FrameworkInformation, "Debug.TakeScreenshot = {0} - NOT Taking screenshot...", TakeScreenshotOption);
503+
504+
try {
505+
if (webDriver != null) webDriver.quit();
506+
webDriver = null;
507+
} catch (Exception e) {
508+
try {
509+
checkIfConnectionIssue(e);
510+
throw new RuntimeException("Selenium Driver error closing Selenium. See inner exception.", e);
511+
} catch (Exception ex) {
512+
Logger.WriteLine(Logger.LogLevels.Error, "Ignoring Error: %s", ex);
513+
webDriver = null;
514+
}
515+
}
516+
}
517+
catch (Exception e) {
518+
Logger.WriteLine(Logger.LogLevels.Error,String.format("Error closing selenium driver: %s",e.getMessage()));
519+
// Dummy to be sure we dont pollute results!
402520
}
403-
catch (Exception e) {}
404521
}
405522

406523
private void startOrConnectToSeleniumServer(boolean killFirst) {
@@ -677,17 +794,12 @@ private String CallingMethodDetails(StackTraceElement methodBase)
677794
return String.format("%s",methodName);
678795
}
679796

680-
681-
private void checkIfConnectionIssue(WebDriverException e) throws RuntimeException {
797+
private void checkIfConnectionIssue(Exception e) throws RuntimeException {
682798
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
683799
StackTraceElement caller = stackTraceElements[2];
684800
if (e.getCause().getClass()==ConnectException.class) {
685801
throw new RuntimeException(String.format("Selenium Driver method [%s] called but Selenium WebDriver not connected!",CallingMethodDetails(caller)),e);
686802
}
687-
else
688-
{
689-
throw new RuntimeException(String.format("Selenium Driver method [%s] error using Selenium. See inner exception.",CallingMethodDetails(caller)),e);
690-
}
691803
}
692804

693805
}

0 commit comments

Comments
 (0)