Appium with Python: In-Depth Guide to App Automation Testing

As mobile applications continue to grow in complexity and usage, having an effective testing strategy is critical for app developers. With over 5 million apps across the major app stores and counting, standing out from the competition requires building high-quality, bug-free apps that delight users. This is where Appium comes in.

Appium is an open-source test automation framework for testing native, hybrid and mobile web apps on iOS, Android, and Windows platforms. With Appium, you can write test scripts in your language of choice to automate interactions with mobile apps like tapping, swiping, entering text and validating UI elements.

One of the popular language bindings available for Appium is Python. Appium‘s Python client library makes it easy to write test scripts in Python to automate mobile apps. If you are familiar with Python and looking for an Appium client, the Python binding is a great choice.

In this comprehensive guide, you will learn:

  • How to set up Appium and the Python client on your system
  • Locating elements in the app using Appium Inspector
  • Writing test scripts in Python to automate app interactions
  • Integrating with BrowserStack to test apps on real devices
  • Best practices for Appium test automation

So let‘s get started!

Setting Up the Environment

We will first install Appium server and the Python client library to allow our test scripts to communicate with the Appium server.

Prerequisites

  • Python 3.6 or higher
  • Pip (Package manager for Python)
  • Appium 1.22.0 or higher
  • Git

Install the Appium Python Client

Run the following command to install the Python client library:

pip install Appium-Python-Client

This will download the package and its dependencies for you to import in your test scripts.

You can confirm it installed successfully by running:

pip show Appium-Python-Client

Install and Start the Appium Server

  1. Download and install Appium Desktop from appium.io. This will install the Appium server and Appium Inspector.

  2. Start the Appium server. You should see the server running on port 4723 by default.

And that‘s it! The Appium server is now ready to accept automation sessions from the Python client.

Next, let‘s look at how to find elements in the app to automate using Appium Inspector.

Locating Elements with Appium Inspector

Appium Inspector is a visual UI inspector that comes bundled with Appium Desktop. It allows you to view and select elements in your app graphically to generate XPath or ID selectors that can be used in test scripts.

Here are the main features of Appium Inspector:

  • Connect to a running emulator/simulator or real device
  • Inspect elements visually
  • Generate XPath, id, class name, accessibility id and other selectors
  • Try out Appium commands like tap and send keys
  • Inspect network requests

Let‘s see how Appium Inspector can help obtain selectors unique to a button on the login screen:

  1. Connect Inspector to your app. You can use a real device connected via USB or use an emulator/simulator session.

  2. On the Elements tab, tap on the login button. This will highlight it.

  3. In the right sidebar, you can see the generated XPath, ID and other selectors for this element.

  4. Copy the ID or XPath to use in your Python test script to locate this element.

And that‘s how you can use Inspector to obtain unique selectors for the app you want to test!

Writing Test Scripts with Python

Now that we have set up Appium server and client, we are ready to write automation test scripts in Python.

Let‘s take an example of logging into a test app and navigating to the settings page.

Test Scenario:

  1. Launch the app
  2. Enter username and password
  3. Tap on Login button
  4. On home screen, open side menu
  5. Tap on Settings option

Here is how this would look in Python:

# import libraries
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
import time

# create driver instance 
caps = {}
caps["platformName"] = "Android" 
caps["deviceName"] = "Galaxy S9"
caps["appPackage"] = "com.test.app"  
caps["appActivity"] = "MainActivity"

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

# wait for app to launch  
time.sleep(5)  

# enter username
username = driver.find_element(AppiumBy.ID, "com.test.app:id/username")
username.send_keys("john123")

# enter password 
password = driver.find_element(AppiumBy.ID, "com.test.app:id/password")
password.send_keys("test123")  

# click login  
login_btn = driver.find_element(AppiumBy.ID, "com.test.app:id/login")
login_btn.click()   

# wait for new activities to load
time.sleep(10)   

# open side menu 
menu_btn = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Open navigation drawer") 
menu_btn.click()

# click on Settings
settings = driver.find_element(AppiumBy.XPATH, "//android.widget.TextView[@text=‘Settings‘]")
settings.click()

# add asserts to validate if on settings screen   
title = driver.find_element(AppiumBy.ID,  "com.test.app:id/title")
assert title.text == "Settings"

driver.quit()  

Let‘s understand what‘s happening here:

  1. We import Appium and Time libraries

  2. Desired capabilities are set – platformName, deviceName, appPackage, appActivity etc.

  3. The driver is initialized by passing remote Appium server URL and desired capabilities

  4. Added waits for app to launch before finding elements

  5. Located elements using ID and other selectors obtained from Inspector

  6. Performed actions like enter text, tap and validate elements

And that‘s it! With just a few lines of code, we automated logging in and navigating to the Settings screen.

Similarly, you can write test cases to automate any flow in your app.

Some best practices while writing Appium Python tests:

  • Use explicit waits instead of fixed time.sleep
  • Break tests into smaller reusable methods
  • Parameterize selectors and test data
  • Validate elements on screen after major actions
  • Keep selectors scoped to a page or component
  • Use Python unittest library for better test reports

This covers the basics of using Python and Appium for test automation. Next, let‘s look at running these tests on real devices using BrowserStack.

Automated Testing with BrowserStack

While Appium allows you to automate tests locally on an emulator or connected device, running tests on a variety of real mobile devices and OS versions is important to cover all user scenarios.

This would normally require procuring and maintaining a large device lab which can be very expensive.

A better approach is to leverage cloud-based services like BrowserStack App Automate that provides access to 1000+ real Android and iOS devices to run Appium tests.

Here are some key advantages of using BrowserStack for app testing:

1. Wide Range of Devices

BrowserStack provides instant access to popular phones like iPhone 14 Pro, Samsung Galaxy S22, OnePlus 10T and 1000+ devices across various price ranges. This coverage is hard to replicate with an in-house device lab.

2. Real Time Debugging

Live video streaming of test execution makes debugging easier. You can see exactly where tests fail rather than just getting logs.

3. Smart Analytics

Get historical test reports on execution times, steps breakdown, device performance and logs – all integrated in a single dashboard.

4. Easy Parallel Testing

Runautomated tests in parallel across different devices, OS versions and locales to cut down total execution time.

5. Integrations

Seamless integration with CI/CD workflows in Jenkins, Azure DevOps and other tools for continuous testing.

Let‘s look at how we can run our Appium Python test from earlier on BrowserStack using their sample project.

Steps to Run on BrowserStack

  1. Sign up for a BrowserStack account to get your username and access key.

  2. Clone the Python sample project:

git clone https://github.com/browserstack/python-appium-app-browserstack.git
  1. Update username and access_key in the Python test script:
"browserstack.user" : "YOUR_USER",  
"browserstack.key" : "YOUR_KEY",
  1. Configure desired capabilities for device and app settings

  2. Run the test using pytest and you will see tests execute on BrowserStack!

pytest test_notes_app.py

Refer to the BrowserStack App Automate documentation for more details on integrating Python Appium with their platform.

Analyzing Test Results

The BrowserStack dashboard shows detailed reporting for test runs:

BrowserStack sample report

Here you can analyze:

  • Total tests passed/failed across devices
  • Breakdown of execution times for each step
  • Videos and device logs to debug failures
  • Performance metrics like CPU, memory, network usage
  • Historical trends across test runs

This information can be invaluable for developers to optimize their apps.

Conclusion

Appium opens up an entire range of possibilities for automating complex mobile apps beyond what manual testing can accomplish. Combined with the simplicity yet flexibility of Python scripts, you can build robust test automation for your iOS, Android or Windows mobile apps.

This guide covered end-to-end – installing Appium server and Python client, using Inspector to find elements, writing test cases and integrating BrowserStack to run those tests on real devices.

We just scratched the surface of everything possible with Appium and Python. You can build on these capabilities to:

  • Create framework with page objects, utility functions
  • Integrate with CI/CD pipelines
  • Run cross browser/device testing
  • Leverage advanced Appium features like webviews, gestures etc.

Hopefully this gives you a solid foundation to start your Appium and Python test automation journey! Many resources are available including the Appium documentation, Appium discussions forum and community channels to help you advance your skills further.

Good luck with building awesome test automation!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts