Local Testing with App Automate

Local Testing is a BrowserStack feature that helps you test mobile apps that access resources hosted in development or testing environments during automated test execution. This page will guide you through enabling Local Testing for App Automate sessions, and then using it to test apps that retrieve data from servers on your local machine, CI/CD machines or nodes, and other private network configurations. In this guide you will learn how to:

  1. Setup your environment
  2. Upload your app
  3. Configure and run your Local test
  4. View test execution results

1. Setup your environment

  • You will need a BrowserStack username and access_key. If you haven’t created an account yet, sign up for a free trial or purchase a paid plan. After signup, you can obtain your access credentials from account settings
  • Ensure you have Python 2.7+ installed on your system. You can download updated Python versions from Python.org. Please note that Lettuce framework doesn’t support Python 3 yet
  • Ensure you have the package manager pip installed on your system. To install pip, follow steps outlined in the installation guide
  • You will need access to your Android app (.apk or .aab file) or iOS app (.ipa file)
Note: If you do not have an .apk or .ipa file and are looking to simply try App Automate Local Testing, you can download and test using our sample Android Local app or sample iOS Local app.

2. Upload your app

Upload your Android app (.apk or .aab file) or iOS app (.ipa file) to BrowserStack servers using our REST API. Here is an example cURL request to upload app on App Automate :

curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" \
-X POST "https://api-cloud.browserstack.com/app-automate/upload" \
-F "file=@/path/to/apk/file"
curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" ^
-X POST "https://api-cloud.browserstack.com/app-automate/upload" ^
-F "file=@/path/to/apk/file"

Ensure that @ symbol is prepended to the file path in the above request. A sample response for the above request is shown below:

{
    "app_url" : "bs://j3c874f21852ba57957a3fdc33f47514288c4ba4"
}

Please note the app_url value returned in the API response (bs://j3c874..... in the above example). We will use this value to set the application under test while configuring the test later on.

Note:
  1. App upload will take a few seconds to about a minute depending on the size of your app. Do not interrupt the cURL command until you get the response back.
  2. If you upload an iOS app, we will re-sign the app with our own provisioning profile to be able to install your app on our devices during test execution.

3. Configure and run your Local test

Setup your project

Clone the Lettuce sample integration code from our GitHub repository.

git clone https://github.com/browserstack/lettuce-appium-app-browserstack.git

Next, execute the following command from the project’s base directory to install required dependencies:

# Test an android app
pip install -r android/requirements.txt

# Test an iOS app
pip install -r ios/requirements.txt

This will install requisite dependencies including Appium’s Python client library and Python binding for BrowserStack Local :

lettuce==0.2.23
lettuce_webdriver==0.3.5
selenium==3.141.0
Appium-Python-Client==0.52
browserstack-local==1.2.2
nose==1.3.7
paver==1.3.4
psutil==5.7.2

Configure Appium’s desired capabilities

Desired capabilities are a series of key-value pairs that allow you to configure your Appium tests on BrowserStack. The following capabilities are required for Local Testing :

  • browserstack.user capability : Its used to specify your Browserstack username credential
  • browserstack.key capability : Its used to specify your Browserstack access_key credential
  • app capability : Its used to specify your uploaded app that will be installed on the device during test execution. Use the app_url obtained in Upload your App section to set its value.
  • device capability : Its used to specify the BrowserStack device you want to run the test on.
  • browserstack.local capability : Its used to enable BrowserStack Local feature for your test execution.

In the Lettuce sample integration code, Appium’s desired capabilities are defined in the config.json file located in the examples/run-local-test directory :

{
    "capabilities": {
      "browserstack.user" : "YOUR_USERNAME",
      "browserstack.key" : "YOUR_ACCESS_KEY",
      "project": "First Lettuce Android Project",
      "build": "Lettuce Android Local",
      "name": "local_test",
      "browserstack.debug": true,
      "app": "bs://<app-id>",
      "device": "Google Pixel 3",
      "os_version": "9.0",
      "browserstack.local": true
    }
}

{
    "capabilities": {
      "browserstack.user" : "YOUR_USERNAME",
      "browserstack.key" : "YOUR_ACCESS_KEY",
      "project": "First Lettuce iOS Project",
      "build": "Lettuce  iOS Local",
      "name": "local_test",
      "browserstack.debug": true,
      "app": "bs://<app-id>",
      "device": "iPhone 11 Pro",
      "os_version": "13",
      "browserstack.local": true
    }
}
Note:
  • You can also provide BrowserStack access credentials by setting BROWSERSTACK_USERNAME & BROWSERSTACK_ACCESS_KEY environment variables
  • You can explore other Appium capabilities using our Capabilities Builder

Establish a Local Testing connection

In addition to using the browserstack.local capability, you also need to establish a Local Testing connection from your local or CI/CD machine to BrowserStack servers. Within your test scripts, you can add a code snippet that will automatically start and stop Local Testing connection using BrowserStack’s Python binding for BrowserStack Local.

In the Lettuce sample integration code, the Local Testing connection is initialised in the terrain.py file located in the examples/run-local-test/features directory as shown below :


#...

def start_local():
    """Starts BrowserStack local"""
    global bs_local
    #creates an instance of Local
    bs_local = Local()
    #replace <browserstack-accesskey> with your key. You can also set the environment variable - "BROWSERSTACK_ACCESS_KEY"
    bs_local_args = { "key": BROWSERSTACK_ACCESS_KEY, "forcelocal": "true" }
    #starts the Local instance with the required arguments
    bs_local.start(**bs_local_args)

def stop_local():
    """Stops BrowserStack Local"""
    global bs_local
    #stops the Local instance
    if bs_local is not None:
        bs_local.stop()

@before.all
def before_all():
    # Start BrowserStack Local before start of the test suite
    start_local()

@after.all
def after_all(totalResult):
    # Stop BrowserStack Local after end of the test suite
    stop_local()

Create remote Webdriver

Once you have configured desired capabilities and established Local Testing connection, you can initialize an Appium webdriver to test remotely on BrowserStack. In order to do so, you need to use a remote BrowserStack URL along with desired capabilities.

In the Lettuce sample integration code, the remote Webdriver is initialised in the terrain.py file located in the examples/run-local-test/features directory as shown below :

#...

# Initialize the remote Webdriver using BrowserStack remote URL
# and desired capabilities defined above
 context.browser = webdriver.Remote (
        desired_capabilities=desired_capabilities,
        command_executor="http://hub-cloud.browserstack.com/wd/hub"
 )

#...

Setup your test-case

This step will help you setup your first Local Testing test case with Lettuce framework. In the Lettuce sample integration code, we have provided a sample test-case in examples/run-local-test/features directory for BrowserStack’s sample apps. If you are testing your own app, please modify the test case accordingly.

Define the scenario you want to test in the app in local_test.feature file:

Feature: BrowserStack Local Testing
    Scenario: can check tunnel working
        Given I open app and click on button
        Then page contains "Up and running"

Provide the implementation for the steps used in the scenario in steps.py file:

import time
from lettuce import *
from nose.tools import assert_equals
from lettuce_webdriver.util import AssertContextManager
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


@step(u'I open app and click on button')
def click_on_button(step):
    with AssertContextManager(step):
        element = WebDriverWait(world.browser, 30).until(
            EC.presence_of_element_located((
                MobileBy.ID, "com.example.android.basicnetworking:id/test_action"))
        )
        element.click()
        WebDriverWait(world.browser, 30).until(
            EC.presence_of_element_located((
                MobileBy.CLASS_NAME, "android.widget.TextView"))
        )

@step(u'Then page contains "([^"]*)"')
def then_page_contains(step, regex):
    test_element = None
    search_results = world.browser.find_elements_by_class_name(
        "android.widget.TextView")
    for result in search_results:
        if result.text.__contains__("The active connection is"):
            test_element = result

    if test_element is None:
        raise Exception("Cannot find the needed TextView element from app")

    matched_string = test_element.text
    print matched_string
    assert matched_string.__contains__("The active connection is wifi"), "Incorrect Text"
    assert matched_string.__contains__("Up and running"), "Incorrect Text"

Define the scenario you want to test in the app in local_test.feature file:

Feature: BrowserStack Local Testing
    Scenario: can check tunnel working
        Given I open app and click on button
        Then page contains "Up and running"

Provide the implementation for the steps used in the scenario in steps.py file:

import time
from lettuce import *
from nose.tools import assert_equals
from lettuce_webdriver.util import AssertContextManager
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def existence_lambda(s):
    result = s.find_element_by_accessibility_id("ResultBrowserStackLocal")
    .get_attribute("value")
    return result and len(result) > 0

@step(u'I open app and click on button')
def click_on_button(step):
    with AssertContextManager(step):
        test_button = WebDriverWait(world.browser, 30).until(
            EC.element_to_be_clickable((
                MobileBy.ACCESSIBILITY_ID, "TestBrowserStackLocal"))
        )
        test_button.click()

@step(u'Then page contains "([^"]*)"')
def then_page_contains(step, regex):
    WebDriverWait(world.browser, 30).until(existence_lambda)
    result_element = world.browser
    .find_element_by_accessibility_id("ResultBrowserStackLocal")

    result_string = result_element.text.lower()

    if result_string.__contains__("not working"):
        screenshot_file = "%s/screenshot.png" % os.getcwd()
        driver.save_screenshot(screenshot_file)
        print "Screenshot stored at %s" % screenshot_file
        raise Exception("Unexpected BrowserStackLocal test result")
    else:
        assert(result_string.__contains__(regex.lower()))

Run the test

You are ready to run your first Local test on BrowserStack. In the Lettuce sample integration code, switch to examples/run-local-test directory, and run the test using the command :

# Run using paver
paver run local_test

4. View test execution results

You can access the test execution results, and debugging information such as video recording, network and device logs on App Automate dashboard or using our REST APIs.

What’s next

Congratulations! You just ran your first local test on App Automate. Next, you can learn to :

  • Run tests in parallel - Speed up test execution by running tests simultaneously across multiple BrowserStack devices

Need some help?

If you have any queries, please get in touch with us.

We're sorry to hear that. Please share your feedback so we can do better







Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better







Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback!

Talk to an Expert
Talk to an Expert