Automation QA Testing Course Content

APPIUM Tutorial

 What is APPIUM?

It is a widely used tool for Mobile Testing.

Appium is mobile web,native and hybrid software application test automation tool developed and suppoorted by sauce lab

It is open-source software automation tool which is useful to automate android and IOS platform apps.


Why we need Mobile?

Importance of Moblie:-

I want to pay my electricity bill.

I need to communicate with my manager and submit my reports urgently.

If you want to buy grocerys, clothes, book all tickets can do with mobile.

Now answer yourself. What do you need to perform these  activities in a fraction of seconds

with ->A smartphone,

        ->Internet connectivity 

         ->A mobile app to do the job.

 

 Various  Mobile OS(operating system)

      Operating system                       Developed by                                  Popularity

      Android                                      Google Inc                                          High

       IOS                                             Apple Inc                                            High

        BlackBerry                               BlackBerry Ltd                                    Low

        windows                                   Microsoft Inc                                      Medium

Types of Moblie Apps

 Mobile web Apple:

 

 -Web apps not real applications: they are actually websites that open in your smartphone

 with the help of a web browser.  Mobile websites have the broadest audience of all the primary types of applications.

 

 Native App

- A native app is developed specifically for one platform. It can be installed through an application store (such as Google play store or Apple's App Store).

Example- Whatsapp, Facebook, This app can use all the system application's(the apps which comes by default with your mobile)


Hybrid App

hybrid Apps are a way to expose content from existing websites in App format. They can be well described as a mixture of Web App and Native App

what is Appium?

Appium is mobile web,native and hybrid software application test automation tool developed and suppoorted by sauce lab

It is open-source software automation tool which is useful to automate android and IOS platform apps.

why Appium(Advantages)?

Cross platform:Android&ios:we can test native,hybrid,web app

Allows you to communicate with other apps,Ex:Whatsapp(Majority of tools doesn't support this)

No pre-compilation of your app

support for built-in app:alarm,phone,calendar etc

Any WebDriver compatible language is supported:Java,objective,C,Ruby,php,C#,:we just need language specific libraries to work on


Limitation of Appium:

For Android,No Support for Android API <17(for android v>4.1) if you mobile having less than 17 then we need to go for selendroid.

Script Execution is very slow on ios platform & android virtual devices

No support for Toast messages; we can handle this

no parallel execution directly:we can handle using sauce labs

APK:Android Application package.

IPA:Iphone Application package.


This is similar to .exe file which are used to install programs on windows.

The only difference is .apk file are designed to be used exclusivley on Android  devices

and you may be required to download addtional files before you run the appliacation

in the android.


Why we are using them what is the use?

we are going to test mobile appliacation means once after the application

was developed in android it will be apk file only.So to automate 

we need apk file, generally in real time we can get this apk file from 

the developer and for generic application we can download from playstor too.


What is Real Testing Device?

Testing on real device allows you to run your mobile apllication 

and checks its functionality.Real device Testing assures you that our appliacation

will work smoothly in customer handsets


What is Emulator and simulator?

Emulator and Simulator are virtual devices.A virtual is not the real

phone but software which gives same functionality as the real phone (Except few functionality like the camers


Android virtual devices :Emulator.

IOS virtual device: Simulator.

How Appium work?

  • When we install the Appium, a server is also installed with it on our machine that exposes the REST API.
  • It receives command and connection requests from the client and executes that command on devices like iOS or Android.
  • It replies with the HTTP responses.
  • To execute requests, it uses a mobile test automation framework to run the user interface of the app. For Example -
    • Apple instruments used for iOS
    • Selendroid used for Android API 15 or less
    • UIAutomator used for Android API 16 or higher


What are the locators in appium?

Id, Name, ClassName, XPath, AndroidUIAutomator,  AccessibilityId.

Status:

Retrieve the server’s current status:

driver.getStatus();

Session:

Create New Session:

IOS :
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(MobileCapabilityType.PLATFORM_VERSION, "10.3"); dc.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone Simulator"); dc.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest"); dc.setCapability(MobileCapabilityType.APP, "/path/to/ios/app.zip"); URL url = new URL("http://127.0.0.1:4723/wd/hub");

IOSDriver driver = new IOSDriver(url, dc);

ANDROID:

DesiredCapabilities dc = new DesiredCapabilities();

dc.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UIAutomator2");

dc.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");

dc.setCapability(MobileCapabilityType.PLATFORM_VERSION, "11.0");

dc.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");

URL url = new URL("http://localhost:4723/wd/hub");


AndroidDriver<WebElement> driver = new AndroidDriver<WebElement>(url, dc);

End Session:

End running session:

driver.quit()

Get session capabilities:

Retrieve the capabilities of the specified session

Map<String, Object> caps = driver.getSessionDetails();

Take ScreenShot:

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

Get PageSource:

Get the current application hierarchy XML (app) or page source (web)

String pageSource = driver.getPageSource();

Set TimeOuts:

Configure the amount of time that a particular type of operation can execute for before they are aborted

driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);

Set Impilicit wait:

Set the amount of time the driver should wait when searching for elements

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

SetScriptTimeout:

Set the amount of time, in milliseconds, that asynchronous scripts executed by execute async are permitted to run before they are aborted (Web context only)

driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);


Orientation:

Get Orientation:

Get the current device/browser orientation

ScreenOrientation orientation = driver.getOrientation();

Set Orientation:

Set the current device/browser orientation

driver.rotate(ScreenOrientation.LANDSCAPE);
driver.rotate(ScreenOrientation.PORTRAIT);
GeoLocation:
Get GeoLocation:

Get the current geo location

Location location = driver.location(); // Must be a driver that implements LocationContext

Set GeoLocation:

Set the current geo location

driver.setLocation(new Location(49, 123, 10)); // Must be a driver that implements LocationContext

Logs:
Get All Available Loges Types

Get available log types as a list of strings

Set<String> logTypes = driver.manage().logs().getAvailableLogTypes();

Get the log for a given log type. Log buffer is reset after each request

LogEntries logEntries = driver.manage().logs().get("driver");

LOG Events:

Store a custom event

CustomEvent evt = new CustomEvent(); evt.setEventName("funEvent"); evt.setVendor("appium"); driver.logEvent(evt);


Get Events:

Get events stored in appium server

driver.getEvents();

UPDATE Device SETTINGS:

Update the current setting on the device

driver.setSetting(Setting.WAIT_FOR_IDLE_TIMEOUT, 5000);

Retrive Device Settings:

Map<String, Object> settings = driver.getSettings();

Execute Driver Script:

Run a WebdriverIO script against the current session, allowing execution of many commands in one Appium request.

String script = "const el = await driver.$('~foo');\n" + "await el.click();"
driver.executeDriverScript(script, new ScriptOptions().withTimeout(200));










Robot Framework

 Robot Framework Introduction:

    Robot Framework is a generic automation framework for acceptance Testing.
    
    It has easy to use tabular syntax which utilizes the keyword driven testing approach.
    
    Libraries implemented Either with Python or Java.

    







How to Integrate Your GitHub Repository to Your Jenkins Project

 One of the basic steps of implementing CI/CD is integrating your SCM (Source Control Management) tool with your CI tool. This saves you time and keeps your project updated all the time. One of the most popular and valuable SCM tools is GitHub. In this blog I will explain how to integrate Jenkins with GitHub projects.

 

The integration presented in this blog post will teach you to:

  • Schedule your build
  • Pull your code and data files from your GitHub repository to your Jenkins machine
  • Automatically trigger each build on the Jenkins server, after each Commit on your Git repository

 

But first, let’s configure the GitHUb and Jenkins integration. Let's begin with the GitHub side!

 

Configuring GitHub

 

Step 1: go to your GitHub repository and click on ‘Settings’.



Step 2: Click on Webhooks and then click on ‘Add webhook’.


Step 3: In the ‘Payload URL’ field, paste your Jenkins environment URL. At the end of this URL add /github-webhook/. In the ‘Content type’ select: ‘application/json’ and leave the ‘Secret’ field empty.
Step 4: In the page ‘Which events would you like to trigger this webhook?’ choose ‘Let me select individual events.’ Then, check ‘Pull Requests’ and ‘Pushes’. At the end of this option, make sure that the ‘Active’ option is checked and click on ‘Add webhook’.



We're done with the configuration on GitHub’s side! Now let's move on to Jenkins.

 

Configuring Jenkins

 

Step 5: In Jenkins, click on ‘New Item’ to create a new project.



Step 6: Give your project a name, then choose ‘Freestyle project’ and finally, click on ‘OK’.




Step 7: Click on the ‘Source Code Management’ tab.


Step 8: Click on Git and paste your GitHub repository URL in the ‘Repository URL’ field.


Step 9: Click on the ‘Build Triggers’ tab and then on the ‘GitHub hook trigger for GITScm polling’. Or, choose the trigger of your choice.



That's it! Your GitHub repository is integrated with your Jenkins project. You can now use any of the files found in the GitHub repository and trigger the Jenkins job to run with every code commit.

 

For example, I will show you how to run a Selenium Test script that I uploaded to  GitHub repository from my Jenkins project.

 

Triggering the Jenkins Job to Run with Every Code Commit

 

Step 10: Click on the ‘Build’ tab, then click on ‘Add build step’ and choose ‘Top Level Maven Targets.




Step 11: To run a Selenium test, click on ‘Save’.
Step 12: Go back to your GitHub repository, edit the any test script and commit the changes. We will now see how Jenkins ran the script after the commit.
Step 13: Go back to your Jenkins project and you'll see that a new job was triggered automatically from the commit we made at the previous step. Click on the little arrow next to the job and choose ‘Console Output’.

Congratulations! Every time you publish your changes to Github, GitHub will trigger your new Jenkins job.

 

Once the GitHub plugin is fully installed and integrated into your Jenkins project, you have completed a very crucial step towards the full CI process. Now, you can proceed to the testing phase.













Find longest non-repeating substring from a given string in Java

 

Approach

  1. Traverse the string from position zero till end of length

  2. maintain a hashmap of already visited characters

  3. Maintain current substring with non-repeating characters with the help of a start and end index.

  4. maintain the longest non-repeating substring in result variable

String getNonRepeatingSubstring(String input) { Map<Character, Integer> visited = new HashMap<>(); String result = ""; for (int start = 0, end = 0; end < input.length(); end++) { char currChar = input.charAt(end); if (visited.containsKey(currChar)) { start = Math.max(visited.get(currChar) + 1, start); } if (result.length() < end - start + 1) { result = input.substring(start, end + 1); } visited.put(currChar, end); } return result; }

Get distinct words from a given file in Java

 We will extract distinct words from a given file using Java.

Concepts

  • Set data structure does not allow duplicate elements, so it can be used for filtering out duplicate words.

  • Using regex we can split the given text file into words, Java provides StringTokenizer class that can help splitting each line of file.

  • We need to close any input file so as to avoid file handle leaks inside Java program. try with resource takes care of automatically closing the underlying input stream once block of code is executed.

import java.io.*; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; public class DistinctWords { private static final Logger LOGGER = Logger.getLogger("DistinctWords"); public Set<String> getDistinctWords(String fileName) { Set<String> wordSet = new HashSet<>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) { String line; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, " ,.;:\""); while (st.hasMoreTokens()) { wordSet.add(st.nextToken().toLowerCase()); } } } catch (IOException e) { LOGGER.log(Level.SEVERE, "IOException occurred", e); } return wordSet; } public static void main(String[] args) { DistinctWords distinctFileWords = new DistinctWords(); Set<String> wordList = distinctFileWords.getDistinctWords("<path-to-file>"); for (String str : wordList) { System.out.println(str); } } }

Create anagram buckets from a given input array of words

 Two strings are called anagrams if they contain same set of characters but in different order. For example,

  • peek and keep are anagrams

  • spar and rasp are anagrams

  • listen and silent are anagrams

For more info:

https://en.wikipedia.org/wiki/Anagram

Here we get an input array of words that contains anagram string, and we need to create buckets for all the anagrams words.

Input:

{"akka", "akak", "baab", "baba", "bbaa"}

Output:

{
    [akka, akak],
    [baab, baba, bbaa]
}

Approach

  1. Create a hashmap that will hold sorted word as the key and list of anagrams as the value. We will use this hashmap to store the results.

  2. For each word in the input array, create a key by sorting the characters and put this word to that list whose key is the sorted word. for example [aakk → akka, akak] If it does not exist then create a new list with the sorted word as key in map.

  3. In the end, traverse the values of hashmap and we get the desired result.


import java.util.*; public class Anagrams { public static void main(String[] args) { String[] input = {"akka", "akak", "baab", "baba", "bbaa"}; Map<String, List<String>> anagramsMap = anagramBuckets(input); System.out.println("anagramsMap = " + anagramsMap); } private static Map<String, List<String>> anagramBuckets(String[] input) { Map<String, List<String>> anagramsMap = new HashMap<>(100); for (String s : input) { char[] word = s.toCharArray(); Arrays.sort(word); String key = String.valueOf(word); if (!anagramsMap.containsKey(key)) { anagramsMap.put(key, new ArrayList<>()); } anagramsMap.get(key).add(s); } return anagramsMap; } }

Reverse position of words in a string using recursion

 In this article, we will write a program to reverse position of words in a given string using recursive approach.

Sample input

I am the best of bests

Output

bests of best the am I

Recursive Approach

  1. We will remove first word from the input string and append it at the end.

  2. Repeat it till all the words are removed and input becomes empty.

public class ReverseWordsInString { public String reverse(String input) { if (input.isEmpty()) { return input; } String[] arr = input.split(" ", 2); String firstWord = arr[0]; String remainingSentence; if (arr.length == 2) remainingSentence = arr[1]; else remainingSentence = ""; return reverse(remainingSentence) + firstWord + " "; } }



1)Base condition in recursion, if the input is empty then we just return (unwind the stack in recursion)
2)We are splitting input string into two parts - first element of array will contain the first word, second element of array will contain the remaining sentence

3)Tail recursion - removes first word and appends it to the last

JUnit testcase

We will write a simple Junit based testcase to assert the correctness of our given program.

JUnit Test
import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;

public class ReverseWordsInStringTest {

    @Test
    public void reverse() {
        ReverseWordsInString utils = new ReverseWordsInString();
        assertThat(utils.reverse("I am the best of bests"), equalTo("bests of best the am I"));
    }
}

Find two numbers of which the product is maximum in an array

 We can easily find two number in an array whose product is maximum using the below approach:

  1. Sort the input integer array in descending order

  2. multiply first and second element of the array, the product will be maximum.Find product of max two elements of an integer array

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class ArrayUtils {
    
        long productMinMax(Integer[] array) {
            Arrays.sort(array, Comparator.reverseOrder());
            int maxNumber = array[0];
            int secondMaxNumber = array[1];
            System.out.println("maxNumber = " + maxNumber);
            System.out.println("secondMaxNumber = " + secondMaxNumber);
            return secondMaxNumber * maxNumber;
        }
    
        public static void main(String[] args) {
            long product = new ArrayUtils().productMinMax(new Integer[]{10, 11, 13, 9, 2, 4});
            System.out.println("Product of min and max element = " + product);
        }
    }
    Program output
    maxNumber = 13
    secondMaxNumber = 11
    Product of min and max element = 143