'Chrome Processes are not being "killed" after driver.quit() although the windows themselves are closed

I am facing a problem in my automation project where after I finish my tests and performing the following code:

 @AfterClass(alwaysRun = true)
    public final void baseTeardown() {
        Date testEndTime = new Date();
        if (driver != null) {
            printBrowserLog();
            driver.close();
            driver.quit();
        }
        Log.i("testEndTime=[%s]", testEndTime);
    }

and this is my @BeforeClass and initializing method:

private static DriverFactory createChromeInst(File downloadsFolder){
        Map<String, Object> pref = new Hashtable<>();
        pref.put("download.default_directory", EnvConf.getProperty("workspace.tests.downloads"));

        WebDriverManager.chromedriver().setup();

        ChromeOptions options = new ChromeOptions();
        options.setHeadless(EnvConf.getAsBoolean("selenium.headless"));
        options.setExperimentalOption("prefs", pref);
        options.setAcceptInsecureCerts(true);
        options.addArguments("--disable-dev-shm-usage");
        options.addArguments("--disable-popup-blocking");

        options.addArguments("--lang=" + EnvConf.getProperty("selenium.locale"));
        options.addArguments("--window-size=" + EnvConf.getProperty("selenium.window_size"));

        DesiredCapabilities dc = new DesiredCapabilities();
        dc.setCapability(ChromeOptions.CAPABILITY, options);


        options.merge(dc);
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.SEVERE);
        options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

        if(!EnvConf.getAsBoolean("selenium.headless")) {
            options.addArguments("--disable-gpu");
        }

        ChromeDriverService service = ChromeDriverService.createDefaultService();
        ChromeDriver driver = new ChromeDriver(service, options);

        if(!EnvConf.getAsBoolean("selenium.headless")) {//for local testings and visibility
            driver.manage().window().maximize();
        }

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      

        return new DriverFactory(driver);
    } 

where DriverFactory is my webdriver that wraps WebDriver Class.

I am facing the following problems:

  • The automation run is not ended and getting stuck.
  • I noticed that chrome processes are still alive in the server which running the test, when I run the command ps -ef | grep chrome | wc -l to count number of live processes I was getting that there are 210 processes.

I can't understand why this problem keeps occurring and actually pretty frustrating me.

==========================EDIT====================== Adding DriverFactory class:

public class DriverFactory implements WebDriver {

    private final WebDriver driver;
    private final static Logger Log = Logger.getLogger(DriverFactory.class.getName());
    private static final Duration WAIT_ELEMENT_TIMEOUT = new Duration(EnvConf.getAsInteger("ui.locator.timeout.sec"), TimeUnit.SECONDS);
    private DriverFactory(WebDriver driver){
        this.driver = driver;
    }

    public static DriverFactory open(Browser browser, File downloadsFolder) throws IOException, InterruptedException {
        Log.info(String.format("Starting new %s browser driver", browser));
        switch (browser) {
            case FIREFOX:
                return createFireFoxInst();
            case CHROME:
                return createChromeInst(downloadsFolder);
            default:
                throw new IllegalArgumentException("'" + browser + "'no such browser type");
        }
    }

    private static DriverFactory createFireFoxInst() {
        WebDriverManager.firefoxdriver().setup();
        FirefoxOptions options = new FirefoxOptions();
        options.setAcceptInsecureCerts(true);
        options.setHeadless((EnvConf.getAsBoolean("selenium.headless")));
        FirefoxDriver driver = new FirefoxDriver(options);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        return new DriverFactory(driver);
    }

    public File getScreenshotAsFile() {
        return ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    }

    public byte[] getScreenshotAsByte() {
        return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    }

    private static DriverFactory createChromeInst(File downloadsFolder){
        Map<String, Object> pref = new Hashtable<>();
        pref.put("download.default_directory", EnvConf.getProperty("workspace.tests.downloads"));

        WebDriverManager.chromedriver().setup();

        ChromeOptions options = new ChromeOptions();
        options.setHeadless(EnvConf.getAsBoolean("selenium.headless"));
        options.setExperimentalOption("prefs", pref);
        options.setAcceptInsecureCerts(true);
        options.addArguments("--disable-dev-shm-usage");
        options.addArguments("--disable-popup-blocking");
        options.addArguments("--lang=" + EnvConf.getProperty("selenium.locale"));
        options.addArguments("--window-size=" + EnvConf.getProperty("selenium.window_size"));

        DesiredCapabilities dc = new DesiredCapabilities();
        dc.setCapability(ChromeOptions.CAPABILITY, options);
//        dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);

        options.merge(dc);
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable(LogType.BROWSER, Level.SEVERE);
        options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

        if(!EnvConf.getAsBoolean("selenium.headless")) {
            options.addArguments("--disable-gpu");
        }

        ChromeDriverService service = ChromeDriverService.createDefaultService();
        ChromeDriver driver = new ChromeDriver(service, options);

        if(!EnvConf.getAsBoolean("selenium.headless")) {//for local testings and visibility
            driver.manage().window().maximize();
        }

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        //enabling downloading resources when driver is headless
        enableHeadlessDownload(service, driver, downloadsFolder);

        return new DriverFactory(driver);
    }

    private static void enableHeadlessDownload(ChromeDriverService service, ChromeDriver driver, File downloadsFolder){
        try(CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            Map<String, Object> commandParams = new HashMap<>();
            commandParams.put("cmd", "Page.setDownloadBehavior");
            Map<String, String> params = new HashMap<>();
            params.put("behavior", "allow");
            params.put("downloadPath", downloadsFolder.getAbsolutePath());
            commandParams.put("params", params);
            ObjectMapper objectMapper = new ObjectMapper();
            String command = objectMapper.writeValueAsString(commandParams);
            String u = service.getUrl().toString() + "/session/" + driver.getSessionId() + "/chromium/send_command";
            HttpPost request = new HttpPost(u);
            request.addHeader("content-type", "application/json");
            request.setEntity(new StringEntity(command));
            CloseableHttpResponse response = httpClient.execute(request);
            Log.info(String.format("enable download, status code=[%d]", response.getCode()));
        }catch (Exception e){
            Log.error("failed to send command=[age.setDownloadBehavior] to chrome server");
            Log.error(e.getMessage());
        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source