Monday, 31 May 2021

Python Appium - Desired Capabilities - Importance of noReset in Script

 What if you don't include noReset option of desired capabilities?

By default this capability is set to false.

desired_caps = {
'platformName': 'android',
'udid': 'emulator-5554',
'deviceName': 'Pixel 2 API 28',
'platformVersion': '9.0',
'appPackage': 'com.flipkart.android',
'appActivity': 'com.flipkart.android.activity.HomeFragmentHolderActivity'

}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)

So what exactly it does that if noReset is set to false, each time your test select capabilities, it will clear the cache, data for the application under test.

Lets take an actual test scenario of flipkart app. If user want to land on home screen, they have to first select the language, enter number or skip the page and then user is landed on home screen.

Select Language

Enter Number

On HomeScreen

If noReset : true, It will not clear the cache, data and user is landed on home screen. So selecting language and entering contact number would be a one time activity in this case.

desired_caps = {
'platformName': 'android',
'udid': 'emulator-5554',
'deviceName': 'Pixel 2 API 28',
'platformVersion': '9.0',
'noReset': 'true',
'appPackage': 'com.flipkart.android',
'appActivity': 'com.flipkart.android.activity.HomeFragmentHolderActivity'

}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
On Home Screen







Python Appium - Multiple scroll


Difference between single scroll and multiple scroll


Let us implement multiple scroll for flipkart app
For multiple scroll you have to use TouchAction class as below.
import pytest
from appium import webdriver
from utilities.BaseClass import BaseClass
from time import sleep
from appium.webdriver.common.touch_action import TouchAction

def __init__(self, driver):
self.driver = driver

def test_flipkart_homescreen():
desired_caps = {
'platformName': 'android',
'udid': 'emulator-5556',
'deviceName': 'Pixel 3 API 24',
'platformVersion': '7.0',
'noReset': 'true',
'appPackage': 'com.flipkart.android',
'appActivity': 'com.flipkart.android.activity.HomeFragmentHolderActivity'

}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)

log = BaseClass().get_logger()
log.info("-------------- Launching Flipkart App --------------")
sleep(5)
log.info("-------------- User is on Flipkart home screen --------------")
touch = TouchAction(driver)
touch.press(x=41, y=1576).move_to(x=44, y=1453).release().perform()

for i in range(4):
touch = TouchAction(driver)
touch.press(x=41, y=1576).move_to(x=44, y=1453).release().perform()
sleep(5)


So the basic difference is multiple scroll can be done multiple times using for loop. such scenarios arises when you want to scroll the items on page till last element is displayed. Sometime "scroll to top" such text is displayed once user reaches to the end of page.



Thursday, 27 May 2021

Python Appium - How to handle list of Elements

 How to handle list of Elements

There are situations where all the elements on a particular page have same attribute however we have to extract a unique one and click on it.

So let us take a simple example for this SMS a native app on device


Here I want to click on settings So I need to find an unique locator for the same. So let us see how we can capture the it

For this open new session in appium and click on screenshot


So if you see all the elements have same attribute, its a list which have common attribute and here we have to find a unique one

ist_of_values = driver.find_elements_by_xpath(
"//android.widget.TextView[@resource-id='com.google.android.apps.messaging:id/title']")
expected_list =['Archived','Blocked contacts','Messages for web','Settings','Help&feedback']
actual_list = []

print(len(list_of_values))
for values in list_of_values:
ele = values.get_attribute("text")
actual_list.append(ele)

print(actual_list)

So we can identify elements by xpath. Once the element is identified wee can iterate through list of values. Before that we can get the length of list of values. Later append the text in actual_list[].

Let us see what is the output for this.


So from output we can see that length of list is 5 and the actual list is displayed. So let us get back to the point that we want to click on settings now. How to click on that

#Tap on Settings options
driver.find_element_by_xpath("//android.widget.TextView[@text='Settings']").click()

So you need to pass text= Settings

Complete code as below:

import pytest
from appium import webdriver
from pageObject.message.message_app import Message
from utilities.BaseClass import BaseClass
from time import sleep


def __init__(self, driver):
self.driver = driver


def test_send_message_delivery_on():
desired_caps = {
'platformName': 'android',
'udid': 'emulator-5554',
'deviceName': 'Pixel 2 API 28',
'platformVersion': '9.0',
'appPackage': 'com.google.android.apps.messaging',
'appActivity': 'com.google.android.apps.messaging.ui.ConversationListActivity',
'new/commandTimeout': 600
}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
driver.find_element_by_xpath("//android.widget.ImageView"
"[@content-desc='More options']").click()
sleep(7)
list_of_values = driver.find_elements_by_xpath(
"//android.widget.TextView[@resource-id='com.google.android.apps.messaging:id/title']")
expected_list = ['Archived','Blocked contacts',
'Messages for web','Settings','Help & feedback']
actual_list = []
print("\n ")
print(len(list_of_values))
for values in list_of_values:
ele = values.get_attribute("text")
actual_list.append(ele)

print(actual_list)

assert expected_list == actual_list, "List did not matched..."

#Tap on Settings options
driver.find_element_by_xpath("//android.widget.TextView[@text='Settings']").click()

Here Attaching with video of our scenario.




Monday, 24 May 2021

Python Appium - How to automate gestures - Tap, long press and swipes/scroll

So above gestures are the part of TouchAction class of appium. So let us go in details of this class

TouchActions:
TouchAction objects contains chain of actions. TouchAction class have only one method perform and we should always end our touchAction sequence with .perform() method.

MultiTouch:
MultiTouch object are collection of TouchActions. MultiTouch have add() and perform() methods.

So let us see a real time example.

tap(): You need to pass x and y co-ordinates where you want to tap.
You can find the tap co ordinates from appium session. Give the desired capabilities and it will launch the session screen for you.

On top of screen there is an option swipe by co ordinates. Place the mouse over the item for which you want to tap. At top left corner you could see x and y coordinate values.




And we have the code which we implemented for tap and swipe up and down on Settings app
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
import time

def __init__(self, driver):
self.driver = driver

def test_tap_example():
desired_caps = {
'platformName': 'android',
'udid': 'emulator-5554',
'deviceName': 'Pixel_3_API_24',
'platformVersion': '7.0',
'appPackage': 'com.android.settings',
'appActivity': 'com.android.settings.Settings'
}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)

driver.find_element_by_id("android:id/title").get_attribute("text")

# Tap example
# Tap on Notification option given under settings
user_actions = TouchAction(driver)
user_actions.tap(x=253, y=1107).perform()
time.sleep(5)
driver.back()

#Swipe/Scroll up and down example
time.sleep(5)
user_actions.press(x=434, y=872).move_to(x=437, y=656).release().perform()
time.sleep(5)
user_actions.press(x=468, y=1165).move_to(x=465, y=1401).release().perform()
time.sleep(5)

Let us see the implementation for long press on dialer app



So here you can record the actions for swipe and then the co ordinated appear . You can select the programming language as well whatever is required by you.

from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
import time

def __init__(self, driver):
self.driver = driver


def test_long_press_example():
desired_caps = {
'platformName': 'android',
'udid': 'emulator-5554',
'deviceName': 'Pixel_3_API_24',
'platformVersion': '7.0',
'appPackage': 'com.android.dialer',
'appActivity': 'com.android.dialer.DialtactsActivity'
}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
# Long press for sending the number
user_actions = TouchAction(driver)
user_actions.tap(x=543, y=1890).perform()
time.sleep(5)

number = driver.find_element_by_id("com.android.dialer:id/digits")
number.send_keys("810000000")
user_actions.long_press(number)
time.sleep(5)


Thursday, 20 May 2021

Python Appium - Parallel Test execution on mobile devices

 Why there is requirement for Parallel execution of test script on multiple devices?

Having single script and executing them parallel on multiple devices can actually reduce the efforts, resources and mainly the "TIME".

So let us start with parallel test execution script. first we would need below package. For info refer https://pypi.org/project/pytest-xdist/

pip install pytest-xdist

Once the package is installed, we can make sure that our test will run on multiple devices in parallel

For that I have considered pytest framework. Lets start the code

@pytest.mark.parametrize("udid,platformVersion,deviceName,systemPort,",[('emulator-5554','7.0','Pixel API 24','8201'),('emulator-5556','7.0','Pixel 3 API 24','8202')]) 

Basically you have to use parameterize annotation here to pass multiple device info, which it will pick at the time of creation of thread. Two parameters means two threads will be created for parallel execution.

import pytest
from appium import webdriver
from pageObject.calculator.calculator_app import Calculator
from utilities.BaseClass import BaseClass


def __init__(self, driver):
self.driver = driver


@pytest.mark.parametrize("udid,platformVersion,deviceName,systemPort,",[('emulator-5554',
'7.0','Pixel API 24','8201'),('emulator-5556','7.0','Pixel 3 API 24','8202')])
def test_calculator_add_number(udid, platformVersion, deviceName, systemPort):
desired_caps = {
'platformName': 'android',
'udid': udid,
'deviceName': deviceName,
'platformVersion': platformVersion,
'appPackage': 'com.android.calculator2',
'appActivity': 'com.android.calculator2.Calculator',
'systemPort': int(systemPort)
}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
cal = Calculator(driver)
cal.add_numbers(2, 2)

In above code you can pass as many as device details that will run in parallel. But make sure you pass unique system port.

To run this you have to give below command




Python Appium - Step by step procedure for capturing screenshot

 Why To capture screenshot?

It is as important as your logs. If there is any failure for any test scenario, we can provide screenshot for the same. Its part of good practice to include in your test framework for each scenarios. Later point of time we will discuss about how to accommodate same in your framework.

Let us see how we can capture screenshot

1. Get the current activity name

2. Get the current time stamp

3. capture and save the screenshot at specified location

import pytest
from appium import webdriver
from login import Login
import time
import os
import base64
from calculator_app import Calculator


def __init__(self, driver):
self.driver = driver

def test_calculator_add_number():
desired_caps = {
'platformName': 'android',
'udid': 'emulator-5556',
'deviceName': 'Pixel 2 API 28',
'platformVersion': '9.0',
'appPackage': 'com.android.calculator2',
'appActivity': 'com.android.calculator2.Calculator'
}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
cal = Calculator(driver)
cal.add_numbers(2, 2)
file_name = driver.current_activity + time.strftime("%Y_%m_%d_%H%M%S")
filepath = os.path.join("C:/Data/2021/May/Sample/", file_name + ".png")
driver.save_screenshot(filepath)


This the result from above script.






Python Appium - Procedure for Video/Screen Recording

 Why Screen/Video recording is required?

When there are complex test scenarios and if there is any failure it becomes easy to identify where exactly is the failure. As a tester point of view, it is always necessary to provide logs, video recording and screenshots (This may vary project to project). 

So let us start how to accommodate video recording in your appium framework.

Basically you would need three steps here,

1. start video recording

2. stop video recording

3. convert the captured video to mp3or mp4 format

So to record video you would need

driver.start_recording_screen()

To Stop video you would need to call

driver.start_recording_screen()

So here I will explain you with calculator example,

from appium import webdriver
from login import Login
import time
import os
import base64


def __init__(self, driver):
self.driver = driver

def test_calculator_click_number():
desired_caps = {
'platformName': 'android',
'udid': 'emulator-5556',
'deviceName': 'Pixel 2 API 28',
'platformVersion': '9.0',
'appPackage': 'com.android.calculator2',
'appActivity': 'com.android.calculator2.Calculator'
}
driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
driver.start_recording_screen()
login = Login(driver)
login.login_in_to_app()
video_rawdata = driver.stop_recording_screen()
video_name = driver.current_activity + time.strftime("%Y_%m_%d_%H%M%S")
filepath = os.path.join("C:/Data/2021/May/Sample/", video_name+".mp4")


with open(filepath,"wb+") as vd:
vd.write(base64.b64decode(video_rawdata))


Here whatever video has been recorded is stored in video_rawdata variable. Later at this point

with open(filepath,"wb+") as vd:
vd.write(base64.b64decode(video_rawdata))

It is been converted. In below code, video_name is the variable with current activity name and current time of video recording

video_name = driver.current_activity + time.strftime("%Y_%m_%d_%H%M%S")

In below code snippet we have stored the video at specified location

filepath = os.path.join("C:/Data/2021/May/Sample/", video_name+".mp4")


Tuesday, 27 April 2021

UiAutomator Watchers

 What are watchers? 

Watchers are basically used for capturing the ANRs and other UI related issues. We will discuss in detail which issues are been captured using these watchers. It Provides auxiliary support for running your test cases. 

There could be a situation when a UI Selector could not find a match for a particular action. At this point of time we can register watchers.

Register watchers

When a selector can not find a match, uiautomator will run all registered watchers.

Click target when conditions match

Let us understand what the above line means

d.watcher("WATCHER_NAME") : This will create a new watcher.

.when(condition) : condition for the watcher

.click() : The action to be perofomed once the target uiselector has been found

Next question arises that whatever watcher we have registered has been called or not.

watchers triggered

A watcher is triggered, which means the watcher was run and all its conditions matched.

Returns true if specified watcher triggered, else returns false

Remove watchers

Let us remove named watchers


List all watchers


Check all triggered watchers

Reset triggered watchers

Remove all watchers


Force run all registered watchers


Monday, 18 November 2019

Data Driven Testing Framework in Selenium Webdriver with python scripting

What is Data-driven Testing Framework?

In a data-driven testing framework, a set of data is created in an excel sheet, and those set of data are imported from an excel sheet to testing tool for testing.

For example, I have taken the www.myntra.com as my demo site for which I will be performing some data-driven test for sign in.

To Sign in a manual user have to follow below steps:
1. Enter www.myntra.com
2. Click on Profiles
3. Click on LOG IN
4. Enter Email address and password
5. Click on LOG IN button





Same we will do using selenium data-driven test framework. For repetitive login we will use excel sheet with email address and passwords.


So first step will create a XLUtil.py file which will import data from excel to automation framework ie. it will put on the website

import openpyxl

def getRowCount(file,sheetName):
    workbook = openpyxl.load_workbook(file)
    sheet = workbook.get_sheet_by_name(sheetName)
    return(sheet.max_row)

def getColumnCount(file,sheetName):
    workbook = openpyxl.load_workbook(file)
    sheet = workbook.get_sheet_by_name(sheetName)
    return(sheet.max_column)

def readData(file,sheetName,rownum,colnum):
    workbook = openpyxl.load_workbook(file)
    sheet = workbook.get_sheet_by_name(sheetName)
    return sheet.cell(row=rownum,column=colnum).value

def writeData(file,sheetName,rownum,colnum,data):
    workbook = openpyxl.load_workbook(file)
    sheet = workbook.get_sheet_by_name(sheetName)
    sheet.cell(row=rownum,column=colnum).value = data
    workbook.save(file)

So in XLUtil.py,
1. getRowCount method will get the max row count
2. getColoumnCount method will get the max column count
3. readData method would read the data from the particular cell
4. writeData method would write the data to a particular cell

Below is the snippet for the login.py

import XLUtils

from selenium import webdriver
from time import sleep
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys

# For pop up alerts of webpage
option = Options()
option.add_argument("--disable-infobars")
option.add_argument("start-maximized")
option.add_argument("--disable-extensions")

# Pass the argument 1 to allow and 2 to block
option.add_experimental_option("prefs", {
    "profile.default_content_setting_values.notifications": 1})

driver = webdriver.Chrome(chrome_options=option, executable_path=
                          'chromedriver.exe')
driver.maximize_window()

driver.get('https://www.myntra.com')
assert 'Online Shopping for Women, Men, Kids Fashion & Lifestyle - Myntra' in 
            driver.title

search_box = driver.find_element_by_class_name("desktop-searchBar")

# Login to the website
profile = driver.find_element_by_class_name("desktop-userTitle").get_attribute
                                           ("data-reactid")
print profile
driver.find_element_by_class_name("desktop-userTitle").click()
sleep(1)
print driver.find_element_by_link_text("LOG IN").get_attribute("text")
login = driver.find_element_by_link_text("LOG IN").click()
sleep(1)
assert 'Login' in driver.title

path = "C:\Data\Roshni\selenium_Framework\Myntra_app_automate\details.xlsx"
rows = XLUtils.getRowCount(path,'Sheet1')

for r in range(2,rows+1):
    username = XLUtils.readData(path,'Sheet1',r,1)
    password = XLUtils.readData(path,'Sheet1',r,2)

    # On login page use email and password to login
    # Enter email text field
    print driver.find_element_by_class_name("login-user-input-email")
                                            .get_attribute("name")
    driver.find_element_by_class_name("login-user-input-email")
                                            .clear()
    driver.find_element_by_class_name("login-user-input-email")
                                            .send_keys(username)
    driver.find_element_by_class_name("login-user-input-email")
                                            .send_keys(Keys.TAB)
    sleep(2)

    # Enter Password text field    
    print driver.find_element_by_class_name("login-user-input-password")
                                                     .get_attribute("name")
    driver.find_element_by_class_name("login-user-input-password")
                                                     .clear()
    driver.find_element_by_class_name("login-user-input-password")
                                                     .send_keys(password)
    sleep(1)

    # Press Log In button    
    print driver.find_element_by_class_name("login-login-button-container")
                                             .get_attribute("text")
    driver.find_element_by_class_name("login-login-button-container")
                                             .click()
    sleep(2)
    if driver.title == "Online Shopping for Women, Men, Kids Fashion & 
             Lifestyle - Myntra":
        print("Test Passed")
        XLUtils.writeData(path,'Sheet1',r,3,"Test Passed")

        # For logout
        profile = driver.find_element_by_class_name("desktop-userTitle")
                                   .get_attribute("data-reactid")
        print profile
        driver.find_element_by_class_name("desktop-userTitle").click()
        sleep(1)
        driver.find_element_by_xpath(
            "/html/body/div[1]/div/div/header/div[2]
                  /div[2]/div/div[2]/div[2]/div[2]/div[3]/div/div").click()
        sleep(5)

        # Login to the website
        profile = driver.find_element_by_class_name("desktop-userTitle")
                         .get_attribute("data-reactid")
        print profile
        driver.find_element_by_class_name("desktop-userTitle").click()
        sleep(1)
         print driver.find_element_by_link_text("LOG IN").get_attribute("text")
        login = driver.find_element_by_link_text("LOG IN").click()
        sleep(1)
        assert 'Login' in driver.title

    else:
        print("Test Failed")
        XLUtils.writeData(path, 'Sheet1', r, 3,"Test Failed")

sleep(5)
driver.quit()

So in login.py,
1. We import the XLUtil.py as we are going to call the methods related to Excel
2. Launch the www.myntra.com.
3. Click on profile
4. Click on login
5. Enter email address and password
6. Click on login

So far email address and password, we are importing those values from excel and then writing on website, if user login, then the test is pass which is written in excel sheet with writeData(). If the login fails then Test failed is written in excel sheet as a test result of the test.

Test Automation Frameworks

What is the Test Automation Framework?

It is a set of guidelines used for designing and creating the test scripts. These guidelines include the coding standards, concepts, processes, practices, project hierarchies, modularity, reporting mechanism, test data injections etc. to pillar automation testing. A framework should be scalable and maintainable.

Advantages of Framework:

  1. Reusability of code
  2. Maximum Coverage
  3. Easy Reporting mechanism
  4. Minimal manual intervention
  5. Low-cost maintenance
Types of Test Automation Framework
  1. Linear Scripting Framework
  2. Modular Testing Framework
  3. Data-Driven Testing Framework
  4. Keyword Driven Testing Framework
  5. Hybrid Testing Framework
  6. Behaviour Driven Testing Framework


Let us start with Data-driven testing framework in detail with selenium + python as scripting language

Tuesday, 10 September 2019

Framework Using APPIUM with Python scripting

Why Mobile automation?

As the world is moving towards the more use of Mobile rather than using the desktop or laptop for any stuff like shopping, banking etc. For more information about mobile automation check here

How to automate Mobile app?

In today's world we need everything on mobile and the apps installed on device should be much more efficient to help us. Like you want to do shopping, so in this case the app should be responsive, with interactive UI's and should be able to handle the load of multiple users at same time. There are so many things which need to be taken care when you are automating an application. So in this we will consider functionality testing. We will consider dialer app of a smartphone, which is considered to be mostly used by user.

Basic concepts required for automation:

Before jumping directly to coding let us understand few concepts. I have considered Dialer app using page object model

So what exactly is Page Object in automation world? It is nothing but modulating our code page by page instead of writing everything in a single code. This way representation of code is easy to manage and easy to understand.

Appium basic concepts are required to be understood before moving further. You can go through here

Pre-requisite:

You need to install below setups on your system

  1. Python 2.7 (stable version)
  2. PyCharm Community Edition 
  3. Appium standalone server
  4. Selenium
  5. Appium Client

Installation documents are available here

App for Automation:

We have choose Dialer app for the automation. We will basically automate an android platform app.
To automate any app in appium we have to first find appPackage and appActivity
So the question here is how to find the appPackage and appActivity of an application. There are two methods to figure out this
1. By using adb command

adb shell
shell@LS-5016:/ $dumpsys window windows | grep -E mCurrentFocus|mFocusedApp'

2. By using aapt dump badging command

Detail about this could be found here

Inspecting element:

Once we have decided which app to test and automate, lets see how to automate same using appium. First thing is to launch the appium server which you halve already installed on your machine.There are two ways which you can inspect UI element
1. Using uiautomator
2. Using UI inspector available in appium

Inspecting element using uiautomator detail information is available here

Here we will see in detail about inspecting element using appium inspector.
First step is to launch the appium server

Then we have to start the server

 Step 2 is to start a new session. We need to click on file-> New session window
It will display a new window where we have to set the desired capabilities like as below

And click on Start session button
So here we could see different properties of UI element. For example
If if wish to click on highlighted area it will display
com.android.dialer:id/floating_action_button_container

various actions performed on the element could be found here and various ways to identify elements could be found here

Automation code goes here:

So finally how to put them all together in a code.

webdriver.py
from appium import webdriver

class Driver:

    def __init__(self):

        desired_caps = {
            'platformName': 'android',
            'deviceName': 'LYF WIND7i',
            'appPackage': 'com.android.dialer',
            'appActivity': 'com.android.dialer.DialtactsActivity',
}
self.instance = webdriver.Remote("http://localhost:4723/wd/hub",desired_caps)
 

In this .py file we are mentioning the desired capabilities required for our test.

dialer_screen.py


from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as e

class DialerScreen:

    def __init__(self, driver):
        self.driver = driver
        self.floating_action_button = WebDriverWait(self.driver.instance, 5).
                                     until(e.visibility_of_element_located
                                     ((MobileBy.ID, "com.android.dialer:id/
                                     floating_action_button")))

    def dial_number(self):
        # Dial a number        
        dial_digit_buttons = self.driver.instance.find_element(MobileBy.ID , 
                                  "com.android.dialer:id/digits")
        dial_digit_buttons.send_keys('number')

    def click_call_button(self):
        press_call_button = self.driver.instance.find_element(MobileBy.ID,
                        "com.android.dialer:id/dialpad_floating_action_button")
        press_call_button.click()

    def click_floating_action_button(self):
        floating_action_button = self.driver.instance.find_element(MobileBy.ID,
                                "com.android.dialer:id/floating_action_button")
        floating_action_button.click()

    def click_end_call_button(self):
        press_end_call_button = self.driver.instance.find_element(MobileBy.ID,
                      "com.android.dialer:id/floating_end_call_action_button")

        press_end_call_button.click()


So here we have written code for the dialer screen as per page object model.

And finally comes our test execution script. Call_from_dialer.py
import unittest
from webdriver.webdriver import Driver
from apps.dialer.dialer_screen import DialerScreen

class DialerTestCases(unittest.TestCase):

    def setUp(self):
        self.driver = Driver()

    def test_dialer_launches(self):
        dialer = DialerScreen(self.driver)
        dialer.click_floating_action_button()
        dialer.dial_number()
        dialer.click_call_button()
        from time import sleep
        sleep(10)
        dialer.click_end_call_button()

     def tearDown(self):
        self.driver.instance.quit()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(DialerTestCases)
    unittest.TextTestRunner(verbosity=2).run(suite)

So here you could see that,

  • def setUp(self) this method invokes the desired capabilities before we could run the actual test script.
  • test_dialer_launches(self) this method actual have the test steps which need to be carried on in order to execute it.
  • Finally the tearDown(self) method is to quit from the test.

 The file structure would look like

The test result would be as below
To run test simply right click and select run unittest for Call_from_dialer.py


Tuesday, 9 July 2019

Ways to identify App Package name and App Activity

app package name and App activity
Why there is need of App Package name and App Activity?

App Package name & App Activity name is required when we are doing automation for a particular app.

For example, if we want to automate dialer app using APPIUM (which I will be covering in upcoming posts) , then you need to have app package name & app activity.

Method 1: By using adb command

This is how we can have app package name and app activity

Dialer App
Fig 1. Select the Dialer app and launch


Dialer app
Fig 2. Dialer App launched
To get the package name & activity name run below command after launching the dialer app
adb shell 
shell@LS-5016:/ $dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'
Below will be output on the command prompt

Fig 3. Run above command from cmd prompt
Method 2 : By Using aapt dump badging command

For this method, I have considered Amazon app. First we have to place the apk at given path C:\Users\Administrator\AppData\Local\Android\Sdk\build-tools\28.0.3

Later we can run below command at command prompt
C:\..\AppData\Local\Android\Sdk\build-tools\28.0.3>aapt dump badging "C:\Users\Administrator\AppData\Local\Android\Sdk\build-tools\28.0.3\Amazon Shopping_v18.12.0.100_apkpure.com.apk"
Fig 4. Package name using aapt

Fig 5. App Activity using aapt



Friday, 14 June 2019

All about adb shell dumpsys

adb shell dumpsys
What is dumpsys?

This was the word always ticking my head whenever I use to talk to vendors. They always needed this one. So I started reading about it and how it benefited them to resolve the android related issues.
dumpsys : It is nothing but a tool which gives the status of services running on device.

Below is the command which shows the list of all services along with the package name
adb shell service list
Output will be as below

adb shell service list
Fig 1 shell service list

So next question is how to identify the services. So below commands give you list of service
adb shell dumpsys -l
Output will be as below

adb shell dumpsys -l
Fig 2 dumpsys -l
There are many filters which you can use for analyzing the dumpsys data

1. dumpsys activity

It shows the list of activities running at that moment on device
adb shell dumpsys  activity
adb shell dumpsys activity
Fig 3 dumpsys activity


2. dumpsys batterystats

This generates the statistical data for battery usage on device.
adb shell dumpsys batterystats

adb shell dumpsys batterystats
Fig 4 dumpsys batterystats

3. dumpsys cpuinfo

This adb command display the CPU information utilized by device
adb shell dumpsys cpuinfo
adb shell dumpsys cpuinfo
Fig 5 dumpsys cpuinfo

Above output you can see that gaana app have utilized 17% of CPU as it was used last.

4. dumpsys wifi

This command displays the status of wifi
adb shell dumpsys wifi
adb shell dumpsys wifi
Fig 6 dumpsys wifi


5. dumpsys meminfo

This command displays the memory information of the device
adb shell dumpsys meminfo
adb shell dumpsys meminfo
Fig 7 dumpsys meminfo

6. dumpsys procstats

This command displays the process stats
adb shell dumpsys procstats --hours 3
adb shell dumpsys procstats
Fig 8 dumpsys procstats
For more on dumpsys refer to https://developer.android.com/studio/command-line/dumpsys

Feature Posts

Python Appium - Step by step procedure for capturing screenshot

 Why To capture screenshot? It is as important as your logs. If there is any failure for any test scenario, we can provide screenshot for th...