release Selenium chromedriver.exe from memory - selenium

I set up a python code to run Selenium chromedriver.exe. At the end of the run I have browser.close() to close the instance. (browser = webdriver.Chrome()) I believe it should release chromedriver.exe from memory (I'm on Windows 7). However after each run there is one chromedriver.exe instance remain in the memory. I hope there is a way I can write something in python to kill the chromedriver.exe process. Obviously browser.close() doesn't do the work. Thanks.

per the Selenium API, you really should call browser.quit() as this method will close all windows and kills the process. You should still use browser.quit().
However: At my workplace, we've noticed a huge problem when trying to execute chromedriver tests in the Java platform, where the chromedriver.exe actually still exists even after using browser.quit(). To counter this, we created a batch file similar to this one below, that just forces closed the processes.
kill_chromedriver.bat
#echo off
rem just kills stray local chromedriver.exe instances.
rem useful if you are trying to clean your project, and your ide is complaining.
taskkill /im chromedriver.exe /f
Since chromedriver.exe is not a huge program and does not consume much memory, you shouldn't have to run this every time, but only when it presents a problem. For example when running Project->Clean in Eclipse.

browser.close() will close only the current chrome window.
browser.quit() should close all of the open windows, then exit webdriver.

Theoretically, calling browser.Quit will close all browser tabs and kill the process.
However, in my case I was not able to do that - since I running multiple tests in parallel, I didn't wanted to one test to close windows to others. Therefore, when my tests finish running, there are still many "chromedriver.exe" processes left running.
In order to overcome that, I wrote a simple cleanup code (C#):
Process[] chromeDriverProcesses = Process.GetProcessesByName("chromedriver");
foreach(var chromeDriverProcess in chromeDriverProcesses)
{
chromeDriverProcess.Kill();
}

//Calling close and then quit will kill the driver running process.
driver.close();
driver.quit();

I had success when using driver.close() before driver.quit(). I was previously only using driver.quit().

It's kinda strange but it works for me. I had the similar issue, after some digging I found that there was still a UI action going on in the browser (URL loading or so), when I hit WebDriver.Quit().
The solution for me (altough very nasty) was to add a Sleep() of 3 seconds before calling Quit().

This answer is how to properly dispose of the driver in C#
If you want to use a 'proper' mechanism that should be used to 'tidy up' after running ChromeDriver you should use IWebDriver.Dispose();
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
(Inherited from IDisposable.)
I usually implement IDisposable on class that is dealing with IWebDriver
public class WebDriverController : IDisposable
{
public IWebDriver Driver;
public void Dispose()
{
this.Driver.Dispose();
}
}
and use it like:
using (var controller = new WebDriverController())
{
//code goes here
}
Hope this saves you some time

Kill Multiple Processes From the Command Line
The first thing you’ll need to do is open up a command prompt, and then use the taskkill command with the following syntax:
taskkill /F /IM <processname.exe> /T
These parameters will forcibly kill any process matching the name of the executable that you specify. For instance, to kill all iexplore.exe processes, we’d use:
taskkill /F /IM iexplore.exe

So, you can use the following:
driver.close()
Close the browser (emulates hitting the close button)
driver.quit()
Quit the browser (emulates selecting the quit option)
driver.dispose()
Exit the browser (tries to close every tab, then quit)
However, if you are STILL running into issues with hanging instances (as I was), you might want to also kill the instance. In order to do that, you need the PID of the chrome instance.
import os
import signal
driver = webdriver.Chrome()
driver.get(('http://stackoverflow.com'))
def get_pid(passdriver):
chromepid = int(driver.service.process.pid)
return (chromepid)
def kill_chrome(thepid)
try:
os.kill(pid, signal.SIGTERM)
return 1
except:
return 0
print ("Loaded thing, now I'mah kill it!")
try:
driver.close()
driver.quit()
driver.dispose()
except:
pass
kill_chrome(chromepid)
If there's a chrome instance leftover after that, I'll eat my hat. :(

You should apply close before than quit
driver.close()
driver.quit()

Code c#
using System.Diagnostics;
using System.Management;
public void KillProcessAndChildren(string p_name)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select * From Win32_Process Where Name = '"+ p_name +"'");
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
try
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
catch (ArgumentException)
{
break;
}
}
}
and this function
public void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
try
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
catch
{
break;
}
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
Calling
try
{
KillProcessAndChildren("chromedriver.exe");
}
catch
{
}

I had the same issue when running it in Python and I had to manually run 'killall' command to kill all processes. However when I implemented the driver using the Python context management protocol all processes were gone. It seems that Python interpreter does a really good job of cleaning things up.
Here is the implementation:
class Browser:
def __enter__(self):
self.options = webdriver.ChromeOptions()
self.options.add_argument('headless')
self.driver = webdriver.Chrome(chrome_options=self.options)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.driver.close()
self.driver.quit()
And the usage:
with Browser() as browser:
browser.navigate_to_page()

Python code:
try:
# do my automated tasks
except:
pass
finally:
driver.close()
driver.quit()

I know this is somewhat of an old question, but I thought I'd share what worked for me. I was having problems with Eclipse -- it wouldn't kill the processes, and so I had a bunch of phantom processes hanging around after testing the code using the Eclipse runner.
My solution was to run Eclipse as administrator. That fixed it for me. Seems that Windows wasn't permitting Eclipse to close the process it spawned.

This work with python for me
import os
os.system('cmd /k "taskkill /F /IM chromedriver.exe /T"')
os.system('cmd /k "taskkill /F /IM chrome.exe /T"')

I have looked at all the responses and tested them all. I pretty much compiled them all into one as a 'Safety closure'. This in C#
Note: you can change the param from IModule app to that of the actual driver.
public class WebDriverCleaner
{
public static void CloseWebDriver(IModule app)
{
try
{
if (app?.GetDriver() != null)
{
app.GetDriver().Close();
Thread.Sleep(3000); // Gives time for everything to close before quiting
app.GetDriver().Quit();
app.GetDriver().Dispose();
KillProcessAndChildren("chromedriver.exe"); // One more to make sure we get rid of them chromedrivers.
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public static void KillProcessAndChildren(string p_name)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select * From Win32_Process Where Name = '" + p_name + "'");
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
try
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
catch (ArgumentException)
{
break;
}
}
}
public static void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
try
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
catch
{
break;
}
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
}

I have this issue. I suspect its due to the version of Serenity BDD and Selenium. The chromedriver process never releases until the entire test suite finishes. There are only 97 tests, but having 97 processes eat up the memory of a server that hasn't much resources may be having an affect on the performance.
To address I did 2 things (this is specific to windows).
before each test (annotated with #Before) get the process id (PID) of the chromedriver process with:
List<Integer> pids = new ArrayList<Integer>();
String out;
Process p = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq chromedriver.exe*\"");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((out = input.readLine()) != null) {
String[] items = StringUtils.split(out, " ");
if (items.length > 1 && StringUtils.isNumeric(items[1])) {
pids.add(NumberUtils.toInt(items[1]));
}
}
after each test (annotated with #After) kill the PID with:
Runtime.getRuntime().exec("taskkill /F /PID " + pid);

For Ubuntu/Linux users: -
the command is either pkill or killall . pkill is generally recommended, since on some systems, killall will actually kill all processes.

I am using Protractor with directConnect. Disabling the "--no-sandbox" option fixed the issue for me.
// Capabilities to be passed to the webdriver instance.
capabilities: {
'directConnect': true,
'browserName': 'chrome',
chromeOptions: {
args: [
//"--headless",
//"--hide-scrollbars",
"--disable-software-rasterizer",
'--disable-dev-shm-usage',
//"--no-sandbox",
"incognito",
"--disable-gpu",
"--window-size=1920x1080"]
}
},

Make Sure You get the Driver instance as Singleton
then Apply at end
driver.close()
driver.quit()
Note: Now if we see task manager you will not find any driver or chrome process still hanging

I simply use in every test a method tearDown() as following and I have no problem at all.
#AfterTest
public void tearDown() {
driver.quit();
driver = null;
}
After quitting the driver instance clear it from the cache by driver = null
Hope the answer the question

There is another way which is working only for windows, but now it is deprecated. it works for previous selenium releases (it works on 3.11.0 version).
import org.openqa.selenium.os.WindowsUtils;
WindowsUtils.killByName("chromedriver.exe") // any process name you want

So, nothing worked for me. What I ended up doing was setting a unique ID on my addArguments to launch chromedriver, then when I want to quit I do something like this:
opts.addArguments(...args, 'custompid' + randomId());
Then to make sure it quits:
await this.driver.close()
await this.driver.quit()
spawn(`kill $(ps aux | grep ${RANDOM_PID_HERE} | grep -v "grep" | awk '{print $2}')`).on('error', e => { /* ignores when grep returns empty */ })
Ugly af, but it's the only thing that worked for my case.

just use this two ways:
open console and run this: taskkill /F /IM chromedriver.exe /T for kill all chrome processes
after how your test is complete you should driver.Dispose, not Close and also not Quit, just Dispose it.
Good Luck.

I came here initially thinking surely this would have been answered/resolved but after reading all the answers I was a bit surprised no one tried to call all three methods together:
try
{
blah
}
catch
{
blah
}
finally
{
driver.Close(); // Close the chrome window
driver.Quit(); // Close the console app that was used to kick off the chrome window
driver.Dispose(); // Close the chromedriver.exe
}
I was only here to look for answers and didn't intend to provide one. So the above solution is based on my experience only. I was using chrome driver in a C# console app and I was able to clean up the lingering processes only after calling all three methods together.

Observed on version 3.141.0:
If you initialize your ChromeDriver with just ChromeOptions, quit() will not close out chromedriver.exe.
ChromeOptions chromeOptions = new ChromeOptions();
ChromeDriver driver = new ChromeDriver(chromeOptions);
// .. do stuff ..
driver.quit()
If you create and pass in a ChromeDriverService, quit() will close chromedriver.exe out correctly.
ChromeDriverService driverService = ChromeDriverService.CreateDefaultService();
ChromeOptions chromeOptions = new ChromeOptions();
ChromeDriver driver = new ChromeDriver(driverService, chromeOptions);
// .. do stuff ..
driver.quit()

I have used the below in nightwatch.js in afterEach hooks.
afterEach: function(browser, done) {
// performing an async operation
setTimeout(function() {
// finished async duties
done();
browser.closeWindow();
browser.end();
}, 200);
}
.closeWindow() just simply closes the window. (But wont work for multiple windows opened).
Whereas .end() ends all the remaining chrome processes.

Please try this tested codes:
ChromeDriverService driverService = ChromeDriverService.createDefaultService();
ChromeDriver chrome = new ChromeDriver(driverService, chromeOptions);
//
// code
//
//
chrome.close();
chrome.quit();
driverService.close();

Related

GEB :One class Test cases are not opening in separate browser

I imported an old project from that has a class named "TestGebSpec". The test cases of it were running on the same browser so I added a "CachingDriverFactory.clearCacheAndQuitDriver()" to gebConfig.groovy file. Still, test cases were running on the same browser so I create a new groovy test case file "Login TC"
Now the problem is the test case of Login TC are running on a separate browser i.e for each test case a new driver is initiated but for file "TestGebSpec" somehow TC runs on the same browser
Any suggestions???
Code of "TestGebSpec" file
#Stepwise
#SuppressWarnings(["GrUnresolvedAccess", "GroovyAssignabilityCheck", "UnnecessaryQualifiedReference"])
class KohlerSanityTestGebSpec extends GebReportingSpec {
public static final String USER_EMAIL = "test_user." + UUID.randomUUID() + "#kohler.com"
public static final String USER_PASSWORD = "pass123Word"
#Shared
productAddedToFolder
def setupSpec() {
driver.manage().window().maximize()
}
def setup() {}
def cleanup() {}
def cleanupSpec() {}
//--------------------------------------------------------------
// Utility methods start here.
//--------------------------------------------------------------
/** Using javascript runner to scroll an element into view so selenium can work with it. */
protected void scrollIntoViewJS(NonEmptyNavigator element) {
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView(true);",
element.firstElement());
sleep(1000)
}
protected void scrollUp(int distance) {
((JavascriptExecutor) driver).executeScript("scroll( 0, ${-distance});");
sleep(100)
}
protected void scrollDown(int distance) {
((JavascriptExecutor) driver).executeScript("scroll( 0, ${distance});");
sleep(100)
}
protected void hoverTest2(NonEmptyNavigator element) {
((JavascriptExecutor) driver).executeScript(
"arguments[0].trigger(\"hover\");",
element.firstElement());
}
protected void hoverOver(String path) {
org.openqa.selenium.WebElement element =
driver.findElement(org.openqa.selenium.By.cssSelector(path))
hoverOver(element)
}
protected void hoverOver(NonEmptyNavigator element) {
org.openqa.selenium.interactions.Actions builder = new
org.openqa.selenium.interactions.Actions(driver)
builder.moveToElement(element.getElement(0)).build().perform()
}
/** click, when the click() method does not work. */
#SuppressWarnings("GroovyUnusedDeclaration")
protected void clickElement(NonEmptyNavigator element) {
org.openqa.selenium.interactions.Actions builder = new org.openqa.selenium.interactions.Actions(driver)
builder.moveToElement(element.getElement(0)).click().build().perform()
}
protected void moveElement(NonEmptyNavigator handleElement, NonEmptyNavigator trackElement, int xPercent) {
org.openqa.selenium.WebElement handle = handleElement.getElement(0)
org.openqa.selenium.WebElement track = trackElement.getElement(0)
org.openqa.selenium.interactions.Actions builder = new org.openqa.selenium.interactions.Actions(driver)
int width = track.getSize().getWidth()
int moveLength = width * xPercent / 100
builder.dragAndDropBy(handle as org.openqa.selenium.WebElement, moveLength.intValue(), (int) 0).build().perform()
}
protected void closeSurveyPopup() {
if ($("#IPEbgCover")) {
$("area", alt: "close").click()
}
}
//----------------------------------------------------------------
// End of utility methods. Start of feature methods.
//----------------------------------------------------------------
def "Create project in bCC TESTCASE1"() {
browser.baseUrl = "URL"
when: "I log in to the BCC"
to BccLoginPage
loginForm.login = "data"
loginForm.$("#loginPassword").value("data")
$("input", type: "submit").click()
then:
at BccHomePage
when:
newCaProjectButton.click()
then:
at BccNewCaProject01Page
when: "I name and describe the new project."
def newProjectName = "gebtest-" + randomString(16, ('A'..'Z') + ('0'..'9'))
println "Creating BCC project \"$newProjectName\"."
projectNameInput.value(newProjectName)
projectDescriptionInput.value(randomString(50))
createProcessButton.click()
then:
at BccCaProjectDetailsPage
}
}
code of "Login TC" file
class LoginTC extends GebReportingSpec{
def setupSpec() {
driver.manage().window().maximize()
//driver.manage().window().size = new org.openqa.selenium.Dimension( 1200, 1200 )
} // run before the first feature method
def setup() {} // run before every feature method
def cleanup() {} // run after every feature method
def cleanupSpec() {} // run after the last feature method
void "login tc2"(){
setup:
to HomePage
final String searchString = "string data"
searchInput = searchString
when:
btnSearch.click()
then:
at waitFor{ ProductDetailPage }
and:
sku.text().toLowerCase().contains( searchString.toLowerCase() )
}
void "login tc3"(){
setup:
to HomePage
final String searchString = "string data"
searchInput = searchString
when:
btnSearch.click()
then:
at waitFor{ ProductDetailPage }
}
}
In short problem is why features on "TestGebSpec" file runs on same browser
Flow is as below
1.Open browser
2.Feature 1 run
3.Feature 2 run
.
.
.
final point. Browser close
What I except
1.open browser
2.Feature 1 run
3.Close browser
4.Open browser
5.Feature 2 run
6.Close browser
Actually an error on your web page should not be a problem if the next feature opens the initial URL it needs afresh. Also cookies should not be a problem because you can delete them manually or automatically. Over-using #Stepwise is a source of problems for many users, too. You should avoid it whenever possible. I even see you use it in a specification with only one feature (or maybe you only showed me one and actually there are more). Using many browsers is a huge resource waste and just makes your tests slow. The Book of Geb (manual) is an excellent source of information.
Take a look at implicit lifecycle with regard to clearCookies() andclearWebStorage(). Auto-clearing cookies and/or web storage might also be helpful. The same chapter also explains that if you just use CachingDriverFactory.clearCacheAndQuitDriver() at the end of a feature method (or in cleanup() if you need it in every feature), the next method will get a new browser instance automatically.
Of course you can quit the browser via quit() (quits the browser) and close() (closes current browser window) if you want to start the new browser manually. But implicit driver management is easier to use IMO, so I am just mentioning it for completeness' sake.
Now for a very special case: You can even use something like resetBrowser(); CachingDriverFactory.clearCacheAndQuitDriver() in the middle of a single feature method like this:
package de.scrum_master.testing
import geb.driver.CachingDriverFactory
import geb.spock.GebReportingSpec
class RestartBrowserIT extends GebReportingSpec {
def "Search web site Scrum-Master.de"() {
when:_ "download page is opened"
go "https://scrum-master.de"
report "welcome page"
then:_ "expected text is found on page"
$("h2").text().startsWith("Herzlich Willkommen bei Scrum-Master.de")
when:_ "browser is reset"
resetBrowser()
CachingDriverFactory.clearCacheAndQuitDriver()
and:_ "download page is opened again in new browser"
go "https://scrum-master.de/Downloads"
report "download page"
then:_ "expected text is found on page"
$("h2").text().startsWith("Scrum on a Page")
}
}
Then on the console you see something like this:
download page is opened
07:49:49.105 [main] INFO i.g.bonigarcia.wdm.WebDriverManager - Using chromedriver 83.0.4103.39 (since Google Chrome 83 is installed in your machine)
07:49:49.146 [main] INFO i.g.bonigarcia.wdm.WebDriverManager - Exporting webdriver.chrome.driver as C:\Users\alexa\.m2\repository\webdriver\chromedriver\win32\83.0.4103.39\chromedriver.exe
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103#{#416}) on port 3302
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jul 03, 2020 7:49:53 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Detected dialect: W3C
expected text is found on page
browser is reset
download page is opened again in new browser
07:49:57.387 [main] INFO i.g.bonigarcia.wdm.WebDriverManager - Using chromedriver 83.0.4103.39 (since Google Chrome 83 is installed in your machine)
07:49:57.413 [main] INFO i.g.bonigarcia.wdm.WebDriverManager - Exporting webdriver.chrome.driver as C:\Users\alexa\.m2\repository\webdriver\chromedriver\win32\83.0.4103.39\chromedriver.exe
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103#{#416}) on port 27426
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Jul 03, 2020 7:50:00 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Detected dialect: W3C
expected text is found on page
P.S.: Just in case you are wondering why I write when:_ "label" instead of just when: "label", I use this SpockConfig.groovy file in order to help me print labels in my test, as you can also see in the console log above:
import spock.lang.Specification
/**
* Use like this in order to print Spock/Geb labels:
* given:_ "foo"
* when:_ "bar"
* then:_ "zot"
*/
class LabelPrinter {
def _(def message) {
println message
true
}
}
Specification.mixin LabelPrinter
The Spock configuration file should be in src/main/resources/SpockConfig.groovy if you use a standard Maven directory layout.

driver.close() will hang for forever

driver.close() is not working on Jenkins and the whole test will hang for forever. I am using Selenium Grid with Java and using Chrome Driver.
I don't want to user driver.quit(). I have to use driver.close(). I have two tabs open and i have to close one.
public static void closeBrowser()
{
try
{
WebDriver testDriver = BrowserFactory.getInstance().getDriver();
if (testDriver != null)
{
testDriver.close();
}
wait.wait(2);
Log.info("Closing the browser");
}
catch (Exception e)
{
Log.info("Cannot close browser");
}
}
This used to work and started to happen recently.
Try this following:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");
This code will close the currently opened tab.
Better solution i found to close window is:
((JavascriptExecutor) BrowserFactory.getInstance().getDriver()).executeScript( "window.close()" );

How to leave the browser open when a Behat/Mink test fails

I'm using the selenium2 driver to test my Drupal site using Behat/Mink in a docker container.
Using the Selenium Standalone-Chrome container, I can watch my behat tests fail, but the problem is that as soon as they fail, the browser is closed, which makes it harder for me to see what the problem is.
I'm running my tests like this:
behat --tags '#mystuff' --config=behat-myconfig.yml --strict --stop-on-failure
Is there a way to leave the remote-controlled browser open even when a test fails?
By default it is not possible.
Maybe you could find some hack to do it but it is not recommended, since each scenario should be isolated and this is not a good solution at least when running some suite with multiple tests.
For one time only see if you can use the logic for printscreen and use a breakpoint instead.
Anyway, you should use a verbose (-vvv for Behat 3) output + ide debugger to debug your code.
Finally I found a good solution for this: behat-fail-aid.
Add the fail aid to your FeatureContext and then run behat with the --wait-on-failure option:
the --wait-on-failure={seconds} option can be used to
investigate/inspect failures in the browser.
You can take a screenshot whenever an error occurs using Behat hook "AfterStep".
Consider having a look at the Panther Driver or DChrome Driver.
Here you are a shortened example considering also non javascript tests (which are faster):
use Behat\Mink\Driver\Selenium2Driver;
/** Context Class Definition ... */
/**
* #AfterStep
*/
public function takeScreenShotAfterFailedStep(AfterStepScope $scope)
{
if (99 !== $scope->getTestResult()->getResultCode()) {
return;
}
$this->takeAScreenShot('error');
}
private function takeAScreenShot($prefix = 'screenshot')
{
$baseName= sprintf('PATH_FOR_YOUR_SCREENSHOTS/%s-%s', $prefix, (new \DateTime())->format('Y_m_d_H_i_s'));
if ($this->supportsJavascript()) {
$extension = '.png';
$content = $this->session->getScreenshot();
} else {
$extension = '.html';
$content = $this->getSession()->getPage()->getOuterHtml();
}
file_put_contents(sprintf('%s%s', $baseName, $extension), $content);
}
private function supportsJavascript()
{
return $this->getSession()->getDriver() instanceof Selenium2Driver;
}

Browser Restart Using Geb & Spock within same test

I would like to be able to restart my browser session mid test using Geb and Spock Framework. I no howto close the browser and update after test compltion etc, but when i close during the test and try and re use the browser object i get a session error thrown by selenium. Below is the base outline i am trying to execute. NB never allows me to navigate to the new StoreHome and if i try and use just Browser i get error thrown.
#Category(High.class)
def "TC1: Verify Browser Restart"() {
when: "On my StoreFront HP wait until title displayed"
to StoreHomePage
waitFor { homepagetitle.displayed }
then: "Update your site picker"
mySitePicker.click()
waitFor { myNewHomePageTitle.displayed }
when: "Close the browser and insure on restart new page is loaded"
browser.close()
browser.quit()
def nb = new Browser()
nb.to(NewStoreHomePage)
then: "Validate on New HP"
asset myNewHomePageTitle.displayed
}
It's as simple as doing the following in your spec:
resetBrowser()
CachingDriverFactory.clearCacheAndQuitDriver()
After that any code that tries to access browser will trigger automatic creation of new WebDriver and Browser instances.
This is how you force a new driver:
CachingDriverFactory.clearCache()
I tested it, it works beautifully. This hint can also be found in the Geb manual.
Update 2017-02-07 15:10 CET: Thanks for the follow-up question. Well, my brief answer was made under the assumption that the command is issued at the end of one feature method and the next feature method starts with a new browser session. In order to do this mid-test you would have to create a new WebDriver instance manually and somehow trick Geb into updating its browser session.
Because this is tricky at least and I do not know how to do it, I recommend using two separate feature methods for testing what should be tested before and after quitting the browser. You can share state between them via #Shared members, if necessary. This also had the advantage that if you let Geb create the new WebDriver and browser session for you, everything configured in GebConfig.groovy, such as browser type and capabilities, will automatically be considered. If you would create a driver manually, you would have to parse the Geb config by yourself - ugly!
But the main problem with this approach is: How to assure that the feature methods are executed in the (lexical) order of declaration? Normally tests should be runnable in any order, so you cannot and should not rely on a specific execution order. Spock offers the Stepwise annotation to adress the rare case in which you want to enforce execution order, but this would lead to the same problem as in the mid-test situation because Geb implicitly assumes that it should continue to test in the same session. I.e. we need a trick to enforce lexical execution order without using #Stepwise.
Another problem is that if your spec extends GebReportingSpec because you want to take screenshots, Geb fails to take the last screenshot at the end of the feature method with the browser gone. Now you can configure Geb not to take screenshots if the test succeeds via reportOnTestFailureOnly, but that still leaves us with failed tests. So I added an override for the report method with some additional exception handling.
The full solution looks like this, derived from one of my real-life tests:
package de.scrum_master.tdd
import geb.driver.CachingDriverFactory
import geb.spock.GebReportingSpec
import org.openqa.selenium.Keys
import org.spockframework.runtime.model.FeatureInfo
import spock.lang.Shared
class SampleGebIT extends GebReportingSpec {
#Override
void report(String label = "") {
// GebReportingSpec tries to write a report (screenshot) at the end of each feature
// method. But because we use 'CachingDriverFactory.clearCacheAndQuitDriver()',
// there is no valid driver instance anymore from which to get a screenshot. Geb is
// unprepared for this kind of error, so we handle it gracefully so as to keep the
// test from failing just because the last screenshot cannot be taken anymore.
try {
super.report(label)
}
catch (Exception e) {
System.err.println("Cannot create screenshot: ${e.message}")
}
}
// We cannot use 'specificationContext' directly from 'setupSpec()' because of this
// compilation error: "Only #Shared and static fields may be accessed from here"
// Okay then, so use we a #Shared field as a workaround. ;-)
#Shared
def currentSpec = specificationContext.currentSpec
def setupSpec() {
// Make sure that feature methods are run in declaration order. Normally we could
// use #Stepwise for this, but because #Stepwise implies staying in the same
// browser session, it would not work in connection with
// 'CachingDriverFactory.clearCacheAndQuitDriver()'. This is the workaround for it.
for (FeatureInfo feature : currentSpec.features)
feature.executionOrder = feature.declarationOrder
}
def "Search web site Scrum-Master.de"() {
setup:
def deactivateAutoComplete =
"document.getElementById('mod_search_searchword')" +
".setAttribute('autocomplete', 'off')"
def regexNumberOfMatches = /Insgesamt wurden ([0-9]+) Ergebnisse gefunden/
when:
go "https://scrum-master.de"
report "welcome page"
then:
$("h2").text().startsWith("Herzlich Willkommen bei Scrum-Master.de")
when:
js.exec(deactivateAutoComplete)
$("form").searchword = "Product Owner" + Keys.ENTER
then:
waitFor { $("form#searchForm") }
when:
report "search results"
def searchResultSummary = $("form#searchForm").$("table.searchintro").text()
def numberOfMatches = (searchResultSummary =~ regexNumberOfMatches)[0][1] as int
then:
numberOfMatches > 0
cleanup:
println "Closing browser and WebDriver"
CachingDriverFactory.clearCacheAndQuitDriver()
}
def "Visit Scrum-Master.de download page"() {
when:
go "https://scrum-master.de/Downloads"
report "download page"
then:
$("h2").text().startsWith("Scrum on a Page")
}
}
BTW, I tested this successfully with several browsers on my Windows 10 machine:
HtmlUnit (with activated JavaScript)
PhantomJS
Chrome
Internet Explorer
Edge
Firefox

Manual way to Automate the verificaton process (i.e for phone(text), voice, etc.) using Selenium WebDriver

I am testing a web App which contains phone/voice verification in one process flow, I am trying to automate this verification process. My Query is:
Is there any way to do it manually like for example entering phone(text)/voice code manually when occurs, while enter code the thread sleeps or wait 'until ExpectedConditon'?
For example: we'll do in the case when the page is in processing phase so, we use
wait.until(ExpectedConditions.presenceOfElementLocated(By.some selector));
it will wait for certain 'timeOutSeconds'.
thanks in advance..........
This is a simple example that i wrote that i'll think it's going to suit your need. In this code the driver starts opening Google. Once the page fully loads the console waits for the input data on the console (i.e. http://www.stackoverflow.com).
This code will probably solve your issue with the manual input during test run.
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
InputStreamReader istream = new InputStreamReader(System.in);
BufferedReader bufRead = new BufferedReader(istream);
String nextWebSite = "http://www.google.com";
driver.get(nextWebSite);
try {
System.out.println("What's the next Website you'll like to visit? ");
nextWebSite = bufRead.readLine();
} catch (IOException err) {
System.out.println("Sorry, there was a problem reading the informed data");
}
driver.get(nextWebSite);
driver.close();
driver.quit();
}