How To Make Your Automation Code Compatible With aiTest

Summary

Making other tool code compatible with aiTest offers the potential for increased efficiency, improved test coverage, cost reduction, flexibility, automation gains, centralized reporting, scalability, and collaboration. For managing the browser drivers, you can use the web driver manager. Use the code snippet provided below:

Code Snippets

Java dependency used in pom.xml


    Dependency for webdriver manager
    
    io.github.bonigarcia
    webdrivermanager
    5.8.0
    
    Dependency for network logs such as header response etc
    
    net.lightbody.bmp
    browsermob-core
    2.1.5
    

Java

  
  public class Hooks {
      public static WebDriver driver;
      public String browser;
      public static Har har;
      public static BrowserMobProxy myProxy;
      
      // Contains declaration of all browsers (FF, Chrome,Edge,Android)
      // This method is a hook which runs before every test
      @Before
      public void beforeEach() throws IOException, URISyntaxException {
          browser = System.getenv("BROWSER");
          
          System.out.println("Browser selected is " + browser);
          if (browser == null) {
              WebDriverManager.chromedriver().setup();
              ChromeOptions chromeOptions = new ChromeOptions();  
              chromeOptions.addArguments("--no-sandbox");
              chromeOptions.addArguments("--disable-dev-shm-usage");
              chromeOptions.addArguments("--headless");
              chromeOptions.addArguments("--window-size=1400,600");
              driver = new ChromeDriver(chromeOptions);
              driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
              driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
              driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
              driver.manage().window().maximize();
          }
          if (browser.equalsIgnoreCase("Chrome")) {
              //This is used for network logs such header reponse etc.

              myProxy=new BrowserMobProxyServer();
              myProxy.start(0);
              
              //2. Set SSL and HTTP proxy in SeleniumProxy
              Proxy seleniumProxy=new Proxy();
              seleniumProxy.setHttpProxy("localhost:" +myProxy.getPort());
              seleniumProxy.setSslProxy("localhost:" +myProxy.getPort());
              
              //3. Add Capability for PROXY in DesiredCapabilities
              DesiredCapabilities capability=new DesiredCapabilities();
              capability.setCapability(CapabilityType.PROXY, seleniumProxy);
              capability.acceptInsecureCerts();
              capability.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
              
              //4. Set captureTypes
              EnumSet < enter CaptureType> captureTypes=CaptureType.getAllContentCaptureTypes();
              captureTypes.addAll(CaptureType.getCookieCaptureTypes());
              captureTypes.addAll(CaptureType.getHeaderCaptureTypes());
              captureTypes.addAll(CaptureType.getRequestCaptureTypes());
              captureTypes.addAll(CaptureType.getResponseCaptureTypes());
              
              //5. setHarCaptureTypes with above captureTypes
              myProxy.setHarCaptureTypes(captureTypes);
              
              //This code is used to launch chrome driver
              
              WebDriverManager.chromedriver().setup();
              ChromeOptions chromeOptions = new ChromeOptions();
              chromeOptions.addArguments("--no-sandbox");
              chromeOptions.addArguments("--disable-dev-shm-usage");
              chromeOptions.addArguments("--headless");
              chromeOptions.addArguments("--window-size=1400,600");
              chromeOptions.merge(capability);
              driver = new ChromeDriver(chromeOptions);
              driver.manage().window().maximize();
              
              driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
              driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
              driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
          } else if (browser.equalsIgnoreCase("Firefox")) {
              //This is used for network logs such header reponse etc.

              myProxy=new BrowserMobProxyServer();
              myProxy.start(0);
              Proxy seleniumProxy=new Proxy();
              //6. HAR name
              myProxy.newHar("MyHAR");
              WebDriverManager.firefoxdriver().clearDriverCache().setup();
              myProxy.addRequestFilter(new RequestFilter() {
                    @Override
                      public HttpResponse filterRequest(HttpRequest request, HttpMessageContents contents, HttpMessageInfo messageInfo) {
                          // capture the request headers
                          Map< String, String> headers = (Map< String, String>) request.headers();
                          System.out.println("Request Headers: " + headers);
                          System.out.println("Request Headers");
                          return null;
                      }
                  });
              myProxy.addResponseFilter(new ResponseFilter() {
                  @Override
                  public void filterResponse(HttpResponse response, HttpMessageContents contents, HttpMessageInfo messageInfo) {
                      // capture the response headers
                      Map< String, String> headers = (Map< String, String>) response.headers();
                      System.out.println("Response Headers: " + headers);
                      System.out.println("Response Headers");
                      // capture the response body
                      String body = contents.getTextContents();
                      System.out.println("Response Body: " + body);
                  }
              });
              // get the Selenium proxy object
              Proxy seleniumProxy1 = ClientUtil.createSeleniumProxy(myProxy);

              //This code is used to launch firefox driver

              FirefoxOptions firefoxOptions = new FirefoxOptions();
              firefoxOptions.setProxy(seleniumProxy1);
              // create a new FirefoxDriver using the FirefoxOptions
              firefoxOptions.addArguments("--headless");
              firefoxOptions.addArguments("--window-size=1400,600");
              driver = new FirefoxDriver(firefoxOptions);
              driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
              driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
              driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
              driver.manage().window().maximize();
          }else if (browser.equalsIgnoreCase("Edge")) {
              //This is used for network logs such header reponse etc.

              myProxy=new BrowserMobProxyServer();
              
              myProxy.start(0);
              
              //2. Set SSL and HTTP proxy in SeleniumProxy
              //Proxy seleniumProxy2=new Proxy();
              Proxy seleniumProxy2 = ClientUtil.createSeleniumProxy(myProxy);
              //This code is used to launch edge driver
              WebDriverManager.edgedriver().setup();
              EdgeOptions options = new EdgeOptions();
              options.setCapability(CapabilityType.PROXY, seleniumProxy2);
              options.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
              //6. HAR name
              myProxy.newHar("MyHAR");
              List< String> args = Arrays.asList("--no-sandbox", "--disable-dev-shm-usage", "--headless");
              Map< String, Object> map = new HashMap<>();
              map.put("args", args);
              options.setCapability("ms:edgeOptions", map);
              driver = new EdgeDriver(options);
              driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
              driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
              driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
              driver.manage().window().maximize();
          }else if (browser.equalsIgnoreCase("devices")) {
              //This code is used to chrome driver in various mobile devices

              WebDriverManager.chromedriver().setup();
              ChromeOptions chromeOptions = new ChromeOptions();
              chromeOptions.addArguments("--no-sandbox");
              chromeOptions.addArguments("--disable-dev-shm-usage");
              chromeOptions.addArguments("--headless");
              chromeOptions.addArguments("--window-size=1400,600");
              
              Map< String, String> mobileEmulation = new HashMap<>();
              mobileEmulation.put("deviceName", "iPhone 12 Pro");
              chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
              driver = new ChromeDriver(chromeOptions);
              driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
              driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
              driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
              driver.manage().window().maximize();
              
          }
          try {
              Thread.sleep(5000);
          } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
      // This method kills the browser after the test is over
      // It also takes a screenshot and embeds it in the report if the test fails
      // This method is a hook which runs after every test
      @After
      public void afterEach(Scenario scenario) throws IOException {
                  String status = scenario.getStatus();
                  String scenario_name = scenario.getName();
                  String new_scenario_name = scenario_name.replaceAll("\\s", "");
                  System.out.println("scenario name="+scenario_name);
                  System.out.println("scenario name="+new_scenario_name);
          System.out.println("scenario status:"+status);
          if (scenario.isFailed()) {
              har=myProxy.getHar();
              int num = (int)(Math.random() * 500 + 1);
              System.out.println("random number="+num);
              //File myHARFile=new File(System.getProperty("user.dir")+"/target/reports/"+browser+"HAR"+num+".har");
              File myHARFile=new File(System.getProperty("user.dir")+"/target/reports/HARFolder/Failed"+new_scenario_name+".har");
              har.writeTo(myHARFile);
              
              System.out.println("==> HAR details has been successfully written in the file when scenario failed.....");
              
              try {
                  
                  scenario.write("Current Page URL is " + driver.getCurrentUrl());
                  byte[] screenshot = ((TakesScreenshot) driver)
                          .getScreenshotAs(OutputType.BYTES);
                  scenario.embed(screenshot, "image/png");
              } catch (WebDriverException somePlatformsDontSupportScreenshots) {
                  System.err.println(somePlatformsDontSupportScreenshots
                          .getMessage());
              }
          }
          else if(status.equals("passed"))
          {
              har=myProxy.getHar();
              int num = (int)(Math.random() * 100 + 1);
              System.out.println("random number="+num);
              //File myHARFile=new File(System.getProperty("user.dir")+"/target/reports/"+browser+"HAR"+num+".har");
              File myHARFile=new File(System.getProperty("user.dir")+"/target/reports/HARFolder/Passed"+scenario_name+".har");
              //File myHARFile=new File(System.getProperty("user.dir")+"/HARFolder/googleHAR.har");
              har.writeTo(myHARFile);
              
              System.out.println("==> HAR details has been successfully written in the file.....");
              try {
                  
                  
                  scenario.write("Current Page URL is " + driver.getCurrentUrl());
                  scenario.write("test case is pass successfuly  Screenshot is attached below");
                  byte[] screenshot = ((TakesScreenshot) driver)
                          .getScreenshotAs(OutputType.BYTES);
                  scenario.embed(screenshot, "image/png");
              } catch (WebDriverException somePlatformsDontSupportScreenshots) {
                  System.err.println(somePlatformsDontSupportScreenshots
                          .getMessage());
              }
          
              
          driver.quit();
      }
      }
  }
  

Python

  
    import pytest
    from selenium import webdriver
    from webdrivermanager import ChromeDriverManager
    import os
    browser = os.environ['BROWSER']
    @pytest.fixture(params=['chrome', 'firefox', 'edge'])
    def browser(request):
        # Set up the browser driver in headless mode using WebDriverManager
        if request.param == 'chrome':
            options = webdriver.ChromeOptions()
            options.add_argument('--headless')
            options.add_argument('--disable-dev-shm-usage')
            options.add_argument('--no-sandbox')
            options.add_argument('--window-size=1400,600')
            driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
        elif request.param == 'firefox':
            options = webdriver.FirefoxOptions()
            options.add_argument('--headless')
            options.add_argument('--disable-dev-shm-usage')
            options.add_argument('--no-sandbox')
            options.add_argument('--window-size=1400,600')
            driver = webdriver.Firefox(webdriver.FirefoxProfile(), options=options)
        elif request.param == 'edge':
            options = webdriver.EdgeOptions()
            options.add_argument('--headless')
            options.add_argument('--disable-dev-shm-usage')
            options.add_argument('--no-sandbox')
            options.add_argument('--window-size=1400,600')
            driver = webdriver.Edge(options=options)
        else:
            raise ValueError(f'Invalid browser: {request.param}')
        yield driver
        # Tear down the driver after the test
        driver.quit()
  

With chrome driver exe

  
    import pytest
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    @pytest.fixture()
    def setup(pytestconfig):
      if pytestconfig.getoption("browser").lower() == "chrome":
          options = webdriver.ChromeOptions()
          options.add_argument("--headless")
          options.add_argument("--disable-gpu")
          options.add_argument("--no-sandbox")
          options.add_argument("--disable-dev-shm-usage")
          chromedriver_path =Service(r"/usr/local/bin/chromedriver")
          driver = webdriver.Chrome(service= chromedriver_path,options=options)
          driver.maximize_window()
      yield {"driver": driver, "url": pytestconfig.getoption("url")}
  

While using driver binary location

  
    /usr/local/bin/chromedriver
  

Note:

  1. Please update surefire , webdrivermanager and extentreports plugin dependency in the Respective POM file as per current Versions.
  2. Make sure you that you are using above mentioned arguments in your automation.

Compatibilty

Language

  • Python
  • Java (Automation build tool maven)

Automation Framework

  • Selenium
  • Playwright
  • Robot
  • Testng

Reporting Format

  • .xml, .json, .html

Questions answered

  • Automation compatibility for Java and Python
×

Subscribe

The latest tutorials sent straight to your inbox.