Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

problem while doing parallel testing using testng

73 views
Skip to first unread message

Utkarsh Singh

unread,
Nov 20, 2024, 7:48:27 AM11/20/24
to testng-users
  • Browser Tab Management:

    • When running tests in parallel using TestNG, multiple tabs or browsers open, but not all of them are being used effectively.
    • Initially, two tabs opened, with one idle. Later, three browser tabs opened, with two tests running in the same tab while the other two tabs remained idle. Eventually, all tests were running in a single tab or browser instance, causing concurrency issues.
  • Idle Browsers with Prototype Scope:

    • Using the prototype scope for WebDriver instances caused multiple browser instances to open, but many remained idle and unused during test execution.
  • Blank Tabs from Custom Configuration:

    • The integration of BrowserScope, BrowserScopeConfig, and BrowserScopePostProcessor caused additional blank browser tabs to open.
  • Tests Running in the Wrong Browser:

    • You want your tests to execute in a second browser instance, but they're executing in the first one.


      , what can i do to resolve this issue please help

CONFIDENTIALITY NOTICE: This email and any attachments are confidential and may be privileged. If you are not the intended recipient, please notify the sender immediately, and do not disclose, copy, distribute, or retain this email or any part of it. Also, please delete it from your system and destroy any copies immediately. Thank you.

Krishnan Mahadevan

unread,
Nov 20, 2024, 8:02:17 AM11/20/24
to testng...@googlegroups.com
Browser management is not something that TestNG does. Most often the cause seems to be in your code. Can you please share a sample project that demonstrates the problem that you are facing with respect to TestNG.


Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/
My Technical Scribblings @ https://rationaleemotions.com/

--
You received this message because you are subscribed to the Google Groups "testng-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to testng-users...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/testng-users/bf0e8868-98df-4988-b198-6e46e9a15176n%40googlegroups.com.

Utkarsh Singh

unread,
Nov 20, 2024, 11:27:42 AM11/20/24
to testng...@googlegroups.com, krishnan.ma...@gmail.com
testng.xml

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.1.dtd">
<suite name="ParallelChromeCucumberTests" parallel="methods"  data-provider-thread-count="2" verbose="2" share-thread-pool-for-data-providers="true">
    <test name="ParallelChromeTests" enabled="true">
        <classes>
            <class name="com.digite.cloud.test.steps.CucumberChromeTestCombined"/>
        </classes>
    </test>
</suite>

webdriverfactory

package com.digite.actions.drivercapabilities;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class WebDriverFactory {

    // Thread-safe driver management
    private List<WebDriverFactory> webDriverThreadPool = Collections.synchronizedList(new ArrayList<>());
    private ThreadLocal<WebDriver> threadLocalDriver = new ThreadLocal<>();

    @Value("${aws.env:http://localhost:3000/}")
    private String env;

    @Value("${browser.mode:non-headless}")
    private String browserMode;

    // Constructor
    public WebDriverFactory() {
    }

    // Create FirefoxDriver bean with prototype scope
    @Bean(name = "firefoxDriver")
    @Scope("prototype")
    public WebDriver firefoxDriver() {
        WebDriverManager.firefoxdriver().setup();
        WebDriver firefoxDriver = new FirefoxDriver();
        firefoxDriver.get(env);
        threadLocalDriver.set(firefoxDriver);
        return threadLocalDriver.get();
    }

    // Create ChromeDriver bean with prototype scope
    @Bean(name = "chromeDriver")
    @Scope("browserscope")
    @Primary
    public WebDriver chromeDriver() {
        WebDriverFactory factory = new WebDriverFactory();
        webDriverThreadPool.add(factory);
        WebDriverManager.chromedriver().setup();
        WebDriver chromeDriver = new ChromeDriver();
        chromeDriver.get(env);
        threadLocalDriver.set(chromeDriver);
        return threadLocalDriver.get();
    }

    // Return the driver instance from ThreadLocal
    public WebDriver getDriver() {
        if (threadLocalDriver.get() == null) {
            threadLocalDriver.set(chromeDriver());
        }
        return threadLocalDriver.get();
    }

    // Quit the driver instance and clean up
    public void quitDriver() {
        if (threadLocalDriver.get() != null) {
            threadLocalDriver.get().quit();
            threadLocalDriver.remove();
        }
    }

    // Initialize driver objects for each thread
    @BeforeSuite(alwaysRun = true)
    public void instantiateDriverObject() {
        WebDriverFactory factory = new WebDriverFactory();
        webDriverThreadPool.add(factory);
    }

    // Get the current driver for the test
    public WebDriver getDriverInstance() throws Exception {
        return getDriver();
    }

    // Clear cookies after each test method
    @AfterMethod(alwaysRun = true)
    public void clearCookies() throws Exception {
        getDriverInstance().manage().deleteAllCookies();
    }

    // Close all driver objects after the test suite completes
    @AfterSuite(alwaysRun = true)
    public void closeDriverObjects() {
        for (WebDriverFactory factory : webDriverThreadPool) {
            factory.quitDriver();
        }
    }
}

chromedriveroptions
package com.digite.actions.drivercapabilities;

import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.springframework.stereotype.Component;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

//import static com.digite.actions.commands.Common.driver;


@Slf4j
public class ChromeDriverOptions  {
    public ChromeOptions setOptions(String mode){
        log.info("ChromeDriver options are being set");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--no-sandbox");
        options.addArguments("disable-features=NetworkService");
        options.addArguments("--remote-allow-origins=*");
        if(mode.equalsIgnoreCase("headless")){
            options.addArguments("headless");//to run on headless chrome browser on linux.Comment this line when running on local machine
        }
        options.addArguments("window-size=1920x1080");
        options.setAcceptInsecureCerts(true);
        options.addArguments("--enable-javascript");
        options.addArguments("--disable-infobars");
        options.addArguments("--disable-plugins");
        options.addArguments("--disable-notifications");
        options.addArguments("--disable-extensions");
        options.addArguments("--disable-popup-blocking");
        HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
        chromePrefs.put("profile.default_content_settings.popups", 0);
        options.addArguments("--test-type");
        options.addArguments("start-maximized");
        options.addArguments("--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36");
        options.addArguments("--disable-gpu");
      options.addArguments("--disable-dev-shm-usage");
        LoggingPreferences logPrefs = new LoggingPreferences();
        logPrefs.enable( LogType.PERFORMANCE, Level.ALL );
        log.info("ChromeDriver options are successfully set");
        return options;
    }

}

browserscopeprocessor
package com.digite.actions.drivercapabilities;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class BrowserScopePostProcessor implements BeanFactoryPostProcessor {


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        beanFactory.registerScope("browserscope",new BrowserScope());

    }
}

browserscopeconfig
package com.digite.actions.drivercapabilities;

import com.annotation.LazyConfiguration;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BrowserScopeConfig{

    @Bean
    public  BeanFactoryPostProcessor beanFactoryPostProcessor(){

        return new BrowserScopePostProcessor();

    }

}

browserscope

package com.digite.actions.drivercapabilities;

import org.openqa.selenium.NoSuchSessionException;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.SimpleThreadScope;

public class BrowserScope extends SimpleThreadScope {

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Object driver = super.get(name, objectFactory);
        if (driver instanceof RemoteWebDriver) {
            try {
                // Check if the session is valid
                ((RemoteWebDriver) driver).getSessionId();
            } catch (NoSuchSessionException e) {
                // If the session is stale, remove the instance and create a new one
                super.remove(name);
                driver = super.get(name, objectFactory); // Recreate if stale
            }
        } else if (driver == null) {
            // If no driver exists, create a new one
            driver = super.get(name, objectFactory);
        }
        return driver;
    }
}



common.java
@PageFragment
@Component
public class Common extends ExceptionLogger {
    private final Logger log = LoggerFactory.getLogger(Common.class);
    public final WebDriver driver;
    public final AndroidDriver a_driver = null;
    public final ChromeDriver driver1 = null;
    public WebElement local_element = null;
    public final String VISIBILITY_OF_ELEMENT_LOCATED = "VISIBILITY_OF_ELEMENT_LOCATED";
    public final String CLICKABILITY_OF_ELEMENT_LOCATED = "CLICKABILITY_OF_ELEMENT_LOCATED";
    public final String PRESENCE_OF_ELEMENT_LOCATED = "PRESENCE_OF_ELEMENT_LOCATED";
    public final String INVISIBILITY_OF_ELEMENT = "INVISIBILITY_OF_ELEMENT";
    public final String IS_ALERT_PRESENT = "IS_ALERT_PRESENT";
    public final String FRAME_TO_BE_AVAILABLE_AND_SWITCH_TO_IT = "FRAME_TO_BE_AVAILABLE_AND_SWITCH_TO_IT";

    long startTime;
    long endTime;
    long duration;
    By local_by = null;
    String label = null;

    public String moduleName = null;

    // Constructor-based dependency injection
    public Common(WebDriverFactory webDriverFactory) {
        log.info("sdf");
        driver = webDriverFactory.getDriver();
    }

commonutilies
   @PageFragment
    public class CommonUtilities extends Common {

        public CommonUtilities(WebDriverFactory webDriverFactory) {
            super(webDriverFactory);
        }
        Properties common=PageObjectsFactory.loadProperties("commonUtilities.properties");

assignment.java
public class Assignment extends Common{
//    private static final Object WebDriverFactory = ;
//    CommonUtilities commonUtilities = new CommonUtilities(driver);
    Properties discussionRepo= PageObjectsFactory.loadProperties("Discussion.properties");
    Properties assignmentRepo= PageObjectsFactory.loadProperties("Assignment.properties");
    public Assignment(WebDriverFactory webDriverFactory) throws Exception{
        super(webDriverFactory);
    }

assignmentsteps.java
  @Autowired
    private WebDriverFactory webDriverFactory;

    private WebDriver driver;

    public AssignmentSteps( ) {
        Before(() -> {
            driver = webDriverFactory.getDriver();
        });


and there are two feature files,

,please help me with help of  these codes



Krishnan Mahadevan

unread,
Nov 20, 2024, 8:05:53 PM11/20/24
to testng...@googlegroups.com
Can you please create a github project, add your sample project source code there and share the link ( pls include the pom/build.gradle file as well). 

That way it’s easy to clone your project and see what’s happening. 

Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"

From: Utkarsh Singh <utkars...@nimblework.com>
Sent: Wednesday, November 20, 2024 9:57:18 PM
To: testng...@googlegroups.com <testng...@googlegroups.com>
Cc: krishnan.ma...@gmail.com <krishnan.ma...@gmail.com>
Subject: Re: [testng-users] problem while doing parallel testing using testng
 

Utkarsh Singh

unread,
Nov 21, 2024, 3:34:51 AM11/21/24
to testng...@googlegroups.com
The code  is confidential and cannot be shared. However, I have already provided code where  the driver from which it is being called. Would it be possible to resolve this issue through a Google Meet session? This way, we can collaborate in real time to identify and address the problem effectively.

Krishnan Mahadevan

unread,
Nov 21, 2024, 4:22:32 AM11/21/24
to testng...@googlegroups.com
Utkarsh

All I am requesting is that you share a sample project which can be used to reproduce the problem. I am not asking that you share confidential code.  The sample project would give me answers to a lot of questions ( your dependencies, how your code is structured, what errror/discrepancy pops up when running your code to name a few). 

Google meet is NOT going to be possible. If you can pls share a sample project that I can take a look at it and suggest what maybe going wrong. 

Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"

From: 'Utkarsh Singh' via testng-users <testng...@googlegroups.com>
Sent: Thursday, November 21, 2024 2:04:29 PM
To: testng...@googlegroups.com <testng...@googlegroups.com>

Utkarsh Singh

unread,
Nov 26, 2024, 5:53:27 AM11/26/24
to testng...@googlegroups.com
hi,
I have cloned my project into this repository:  https://github.com/Utk98/parallel_testing

Could you please take a look and help identify the defects that occur during parallel testing? Your assistance would be greatly appreciated.

Krishnan Mahadevan

unread,
Nov 26, 2024, 8:19:57 AM11/26/24
to testng...@googlegroups.com
Please help cleanup/fix the pom file such that it can be used outside of your company as well?


You currently have some in house distribution management URLs being referred which is NOT accessible  from outside.



Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/
My Technical Scribblings @ https://rationaleemotions.com/

Krishnan Mahadevan

unread,
Nov 26, 2024, 8:32:31 AM11/26/24
to testng...@googlegroups.com
You have a lot of tight coupling with your in house framework in the sample code that you shared.

You would need to clean it up such that the sample can be something that can be executed by anyone on the internet for us to be able to help you out figure out what the problem is.

On a side note, it’s my personal opinion that using a heavy weight application framework such as Spring just for the sake of leveraging its dependency injection capabilities is perhaps an overkill. If its just dependency injection that you are after, then maybe you could consider something lightweight such as Guice ( See https://testng.org/#_guice_dependency_injection )



Thanks & Regards
Krishnan Mahadevan

"All the desirable things in life are either illegal, expensive, fattening or in love with someone else!"
My Scribblings @ http://wakened-cognition.blogspot.com/
My Technical Scribblings @ https://rationaleemotions.com/
On 26 Nov 2024, at 18:49, Krishnan Mahadevan <krishnan.ma...@gmail.com> wrote:

Please help cleanup/fix the pom file such that it can be used outside of your company as well?


You currently have some in house distribution management URLs being referred which is NOT accessible  from outside.

Reply all
Reply to author
Forward
0 new messages