Friday, July 3, 2020

Java generate JSON file


To Generate the JSON object of below formate using json.jar


{
    "employees": {
        {"firstName": "John", "lastName": "Doe"}, 
        {"firstName": "Anna", "lastName": "Smith"}, 
        {"firstName": "Peter", "lastName": "Jones"}
    },
    "manager": [
        {"firstName": "John", "lastName": "Doe"}, 
        {"firstName": "Anna", "lastName": "Smith"}, 
        {"firstName": "Peter", "lastName": "Jones"}
    ], 
}

import org.json.JSONArray;
import org.json.JSONObject;

public JSONObject getJsonResponse(){

    JSONObject employees = new JSONObject();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));
JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));
   JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
}


---------------------------------------------------------------------------------------------------------------------
To Generate the JSON object of below formate using Gson.jar

[
  {
    "staf": [
      {
        "emp": [
          {
            "dep1": 130,
            "empid2": 370,
            "sec": 2600
          }
        ]
      },
      {
        "maganer": [
          {
            "dep": 190,
            "empid": 5850,
            "sec": 190
          }
        ]
      }
 
    ]
  }
]




import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;





 //Part 1
    Map<String ,Object> map1 = new HashMap<>();
    map1.put("dep1", 130);
    map1.put("empid2", 370);
    map1.put("sec", 2600);

    List<Map<String ,Object>> inventoriesList = new ArrayList<>();
    inventoriesList.add(map1);

    Map<String,List< Map<String ,Object> > > inventoriesMap = new HashMap<>();
    inventoriesMap.put("match", inventoriesList);

    //Part 2
    Map<String ,Object> map2 = new HashMap<>();
    map2.put("dep", 5850);
    map2.put("empid", 190);
    map2.put("sec", 190);

    List<Map<String ,Object>> highPerformanceList = new ArrayList<>();
    highPerformanceList.add(map2);

    Map<String,List< Map<String ,Object> > > highPerformanceMap = new HashMap<>();
    highPerformanceMap.put("overunder", highPerformanceList);

    
    //Collect
    List<Map<String, List<Map<String, Object>>>> ListMapTermMapList = new ArrayList< Map<String,List< Map<String ,Object> > > >();
    ListMapTermMapList.add(inventoriesMap);
    ListMapTermMapList.add(highPerformanceMap);

    
    Map <String, List<Map<String,List<Map<String,Object>>>>> Od= new HashMap<>();
    Odds.put("odds", ListMapTermMapList);
    
    List<Map <String, List<Map<String,List<Map<String,Object>>>>>> oddsfinal= new ArrayList<Map <String, List<Map<String,List<Map<String,Object>>>>>>();
    oddsfinal.add(Od);
    
    //Format to Json
    System.out.println(new Gson().toJson(oddsfinal));



Sunday, June 14, 2020

Window application automation using Python (pywinauto)

Notepad / excel / Mspaint automation using pywinauto

Pre-requested :- python set-up is required 

1. Installing Pywinauto: 


pip install pywinauto
2. python code : 
from pywinauto import application
import time 
notepad = application.Application(backend='uia').start('notepad.exe')

notepad_window = notepad.window(title='Untitled - Notepad')
notepad_window.type_keys("Hello Python World!", with_spaces=True)

time.sleep(2)

notepad_window.child_window(title='Close', control_type='Button').click_input()
notepad_window.child_window(title='Don\'t Save', control_type='Button').click_input()

3 . same Notepad test with different syntax   

app = application.Application().start("notepad.exe")

//'find available dialogs ,controls of an application in pywinauto?'
# app.Notepad.print_control_identifiers(filename='output.txt')-- > generate the output is added in file output.txt
# below generate output in console
app.Notepad.print_control_identifiers()

 app.child_window(title='Maximize', control_type='Button')

 app.SaveAs.ComboBox5.Select("UTF-8")

time.sleep(2)
app.Notepad.edit1.SetText("This is me typing %r" )
time.sleep(2)

# close the file 
app.Notepad.TypeKeys("^S")
# app.Notepad.MenuSelect("File -> Exit")

time.sleep(2)
app.SaveAs.edit1.SetText("Test_File.txt" )
time.sleep(2)
app.SaveAs.Save.Click()


4. console output generated by identifier function app.Notepad.print_control_identifiers()
# Control Identifiers:
# 
# Notepad - 'Untitled - Notepad'    (L531, T155, R1688, B614)
# ['Untitled - Notepad', 'Notepad', 'Untitled - NotepadNotepad']
# child_window(title="Untitled - Notepad", class_name="Notepad")
#    | 
#    | Edit - 'This is me typing %r'    (L542, T230, R1677, B567)
#    | ['Untitled - NotepadEdit', 'Edit']
#    | child_window(title="This is me typing %r", class_name="Edit")
#    | 
#    | StatusBar - ''    (L542, T567, R1677, B603)
#    | ['StatusBar   Ln 1, Col 21  ', 'StatusBar   Windows (CRLF)', 'StatusBar', 'StatusBar100%', 'Untitled - NotepadStatusBar']
#    | child_window(class_name="msctls_statusbar32")
#    | 
#    | Button - 'Maximize'     (L1664, T623, R1718, B656)
#    | ['MaximizeButton' , 'Button4', 'Maximize']
#    | child_window(title="Maximize", control_type="Button")
5. Other Functions and arguments used to handle the execution  
# class_name: Elements with this window class
# class_name_re: Elements whose class matches this regular expression
# parent: Elements that are children of this
# process: Elements running in this process
# title: Elements with this text
# title_re: Elements whose text matches this regular expression
# top_level_only: Top level elements only (default=**True**)
# visible_only: Visible elements only (default=**True**)
# enabled_only: Enabled elements only (default=False)
# best_match: Elements with a title similar to this
# handle: The handle of the element to return
# ctrl_index: The index of the child element to return
# found_index: The index of the filtered out child element to return
# predicate_func: A user provided hook for a custom element validation
# active_only: Active elements only (default=False)
# control_id: Elements with this control id
# control_type: Elements with this control type (string; for UIAutomation elements)
# auto_id: Elements with this automation id (for UIAutomation elements)
# framework_id: Elements with this framework id (for UIAutomation elements)
# backend: Back-end name to use while searching (default=None means current active backend)
Reference :  

https://www.mbalslow.com/blog/article/how-to-get-started-gui-automation-pywinauto-python/

Tuesday, February 18, 2020

Selenium WebDriver – Singleton DriverFactory Design Pattern Using Java 8

WebApplication Singleton driver Factory Design Pattern :


Mobile Singleton driver Factory Design Pattern :
  • AppiumServerJava : is used to customize the url and desirecapabilities 
  • CreateDriver     : is to create LocalThread instance 


Package Runner;

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import org.apache.log4j.Logger;

import org.apache.log4j.xml.DOMConfigurator;

import org.apache.commons.cli.CommandLine;

import org.apache.log4j.Logger;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.BeforeSuite;

 

import io.appium.java_client.android.AndroidDriver;

import io.appium.java_client.remote.AndroidMobileCapabilityType;

import io.appium.java_client.remote.MobileCapabilityType;

import io.appium.java_client.remote.MobilePlatform;

import io.appium.java_client.service.local.AppiumDriverLocalService;

import io.appium.java_client.service.local.AppiumServiceBuilder;



public class AppiumServerJava {

       private static DesiredCapabilities cap;

       public static AndroidDriver driver;

       public static AppiumServiceBuilder builder = null;

       static AppiumDriverLocalService service = null;

         private static Logger Log = Logger.getLogger(AppiumServerJava.class);

 

//     @BeforeSuite

       public static DesiredCapabilities AppiumServerCapabilities() {

              DOMConfigurator.configure(System.getProperty("user.dir") + File.separator + "log4j.xml");

              Log.debug("This is debug message ");

              Log.info("desire capabilities initized");

              File appDir = new File(System.getProperty("user.dir") + "/src/test/java/appStore/");

              File app = new File(appDir, "Flipkart Online Shopping App_v6.17_apkpure.com.apk");

              Log.info(app + "_____");

              cap = new DesiredCapabilities(); // Cabaliliesties for server

              cap.setCapability("noReset", "false");

//            cap.setCapability(MobileCapabilityType.BROWSER_NAME, "Android");

              cap.setCapability(MobileCapabilityType.UDID, "4200cab8de3b747f"); // Give Device ID of your mobile phone

              cap.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());

              cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Galaxy On Max");

              cap.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID);

              cap.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.flipkart.android");

              cap.setCapability("appActivity", "com.flipkart.android.SplashActivity");

              builder = new AppiumServiceBuilder().withCapabilities(cap);

              DesiredCapabilities capClient = new DesiredCapabilities(); // Capabilities for client

              return cap;

       }


       public static String getURL() {

              AppiumServerCapabilities();

              service = builder.build();

              Log.info("appium service started ");

              service.start();

              Log.error(service.getUrl().toString());

              return service.getUrl().toString();

       }


    }

public class CreateDriver extends AppiumServerJava{

private static Logger Log = Logger.getLogger(CreateDriver.class);




       private static final ThreadLocal<AndroidDriver> mobileDriver = new ThreadLocal<AndroidDriver>();

       private URL serverUrl = null;



/*

        * Method to create local driver

        * @param capabilities

        * @param testBedConfig

        */

      

       public void createLocalDriver(){

//            AndroidDriver driver = null;

              try {

                      serverUrl = new URL(AppiumServerJava.getURL());

                      Log.info("createLocalDriver ::: serverUrl:::"+serverUrl);

              } catch (MalformedURLException e) {

                      e.printStackTrace();

              }

              try{

                      driver = new AndroidDriver(serverUrl, AppiumServerJava.AppiumServerCapabilities());

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

                      setDriver(driver);

              }catch(Exception ex){

                      Log.error("Error while createLocalDriver:::"+ex.getMessage());

                      ex.printStackTrace();

              }

       }

      

       /**

        * Method to get driver

        * @param capabilities

        * @param testBedConfig

        * @return

        */

       @BeforeSuite

       public AndroidDriver getDriverAndroid(){

//            AndroidDriver driver = null;

              if(mobileDriver.get()==null){

                      createLocalDriver();

              }

              return mobileDriver.get();

       }

      

       /**

        * Method to set driver

        * @param localDriver

        */

       public void setDriver(AndroidDriver localDriver){

              mobileDriver.set(localDriver);

       }

      

       /**

        * Method to get driver

        * @return

        */

       public static AndroidDriver getDriver(){

              return driver =mobileDriver.get();

       }

}




2 .  Singleton driver Factory Design Pattern :

//chrome driver supplier
Supplier<WebDriver> chromeDriverSupplier = () -> {
    System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
    return new ChromeDriver();
};
 
//firefox driver supplier
Supplier<WebDriver> firefoxDriverSupplier = () -> {
    System.setProperty("webdriver.gecko.driver", "/Users/username/Downloads/geckodriver");
    return new FirefoxDriver();
};
Copy
You might want to add additional suppliers like Safari, IE etc depends on your requirement.
public enum DriverType {
    CHROME,
    FIREFOX,
    SAFARI,
    IE;
}
Copy
To avoid if-else / switch statements, I create a map as shown here. Once I have all my suppliers, then I add the suppliers into the map.
public class DriverFactory {
 
    private static final Map<DriverType, Supplier<WebDriver>> driverMap = new HashMap<>();
 
    //chrome driver supplier
    private static final Supplier<WebDriver> chromeDriverSupplier = () -> {
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
        return new ChromeDriver();
    };
 
    //firefox driver supplier
    private static final Supplier<WebDriver> firefoxDriverSupplier = () -> {
        System.setProperty("webdriver.gecko.driver", "/Users/username/Downloads/geckodriver");
        return new FirefoxDriver();
    };
 
    //add more suppliers here
 
    //add all the drivers into a map
    static{
        driverMap.put(DriverType.CHROME, chromeDriverSupplier);
        driverMap.put(DriverType.FIREFOX, firefoxDriverSupplier);
    }
 
    //return a new driver from the map
    public static final WebDriver getDriver(DriverType type){
        return driverMap.get(type).get();
    }
 
}
Copy
Now your test should be simply written as shown here to get a new WebDriver.
public class SampleBrowserTest {
 
    private WebDriver driver;
 
    @BeforeTest
    public void setup(){
        driver = DriverFactory.getDriver(DriverType.CHROME);
    }
 
    @Test
    public void test1(){
        driver.get("https://www.google.com");
        //your test using webdriver
    }
 
    @AfterTest
    public void teardown(){
        driver.close();
    }
 
}


3.   Driver Factory using Maven  dependency



 <dependency>
    <groupId>ru.stqa.selenium</groupId>
    <artifactId>webdriver-factory</artifactId>
    <version>4.4</version>
</dependency>
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>
 


The library provides three ways to manage instances:
  • SingleWebDriverPool allows a single managed instance of WebDriver to exist at any given moment,
  • ThreadLocalSingleWebDriverPool allows a single managed instance of WebDriver to exist for each thread,
  • LooseWebDriverPool does not impose any restrictions, it creates a new managed instance on each request.
You can use as many separate pools as you like, but there is also WebDriverPool.DEFAULT that is an instance of ThreadLocalSingleWebDriverPool.



import ru.stqa.selenium.factory.WebDriverPool;
 
 
// adding desirecapabilities;
@BeforeEach public void initDriver() throws Throwable { 
       driver = WebDriverPool.DEFAULT.getDriver(gridHubUrl, capabilities); 
}
 
// Start Browser :
@BeforeMethod public void startBrowser() { 
       driver = WebDriverPool.DEFAULT.getDriver(DesiredCapabilities.firefox());
 }
 
 
@Test
public void testSomething() {
  WebDriver driver = WebDriverPool.DEFAULT.getDriver(new FirefoxOptions());
  // do something with the driver
  driver.get("http://seleniumhq.org/");
}
 
@Test
public void testSomethingElse() {
  WebDriver driver = WebDriverPool.DEFAULT.getDriver(new ChromeOptions());
  // do something with the driver
  driver.get("http://seleniumhq.org/");
}
 
@AfterSuite
public void stopAllDrivers() {
  WebDriverPool.DEFAULT.dismissAll();
}







4.