Selenium with Behave

Your guide to running Selenium Webdriver tests with Behave on BrowserStack.

Note: Code samples in this guide can be found in the behave-browserstack repo in GitHub

Introduction

BrowserStack gives you instant access to our Selenium Grid of 2000+ real devices and desktop browsers. Running your Selenium tests with Behave on BrowserStack is simple. This guide will help you:

  1. Run your first test
  2. Mark tests as passed or failed
  3. Debug your app

Prerequisites

Before you can start running your Selenium tests with Behave, ensure you have the Behave libraries installed using the following command:

pip install behave

Running your first test

Note: Testing on BrowserStack requires username and access key that can be found in account settings.
If you have not created an account yet, you can sign up for a Free Trial or purchase a plan.

To run Selenium tests with Behave on BrowserSatck Automate, follow the below steps:

  1. Clone the behave-browserstack repo on GitHub with BrowserStack’s sample test, using the following command:

     git clone https://github.com/browserstack/behave-browserstack
     cd behave-browserstack
    
  2. Install the dependencies using the following command:

    pip install -r requirements.txt
    
  3. Update single.json files within the behave-browserstack/config/ directory with your BrowserStack credentials as shown below:

    {
      "user": "YOUR_USERNAME",
      "key": "YOUR_ACCESS_KEY",
    
      "capabilities": {
        "build": "behave-browserstack",
        "name": "single_test",
        "browserstack.debug": true
      },
    
      "environments": [{
        "browser": "chrome"
      }]
    }
    
  4. Now, execute your first test on BrowserStack using the following command:

     paver run single
    
  5. View your test results on the BrowserStack Automate dashboard.

Details of your first test

Following is the sample Behave test case that you ran above. The test searches for “BrowserStack” on Google, and checks if the title of the resulting page is “BrowserStack - Google Search”.

The steps.py file defines the actions to be performed based on the steps in sample test’s feature file.

steps.py
# Google Steps
@when('visit url "{url}"')
def step(context, url):
    context.browser.get(url)

@when('field with name "{selector}" is given "{value}"')
def step(context, selector, value):
    elem = context.browser.find_element_by_name(selector)
    elem.send_keys(value)
    elem.submit()
    time.sleep(5)

@then('title becomes "{title}"')
def step(context, title):
    assert context.browser.title == title

The following single.feature file is the actual sample test file where the test scenario is defined in BDD fashion.

single.feature
# Google Feature
Feature: Google Search Functionality
    Scenario: can find search results
        When visit url "https://www.google.com/ncr"
        When field with name "q" is given "BrowserStack"
        Then title becomes "BrowserStack - Google Search"

Integration of Behave with BrowserStack is made possible by use of following module in environment.py file:

environment.py
from selenium import webdriver
from browserstack.local import Local
import os, json

CONFIG_FILE = os.environ['CONFIG_FILE'] if 'CONFIG_FILE' in os.environ else 'config/single.json'
TASK_ID = int(os.environ['TASK_ID']) if 'TASK_ID' in os.environ else 0

with open(CONFIG_FILE) as data_file:
    CONFIG = json.load(data_file)

bs_local = None

# Your credentials will be read from these environment variables or be read from the single.json config file
BROWSERSTACK_USERNAME = os.environ['BROWSERSTACK_USERNAME'] if 'BROWSERSTACK_USERNAME' in os.environ else CONFIG['user']
BROWSERSTACK_ACCESS_KEY = os.environ['BROWSERSTACK_ACCESS_KEY'] if 'BROWSERSTACK_ACCESS_KEY' in os.environ else CONFIG['key']

# The following code is responsible for starting and stopping BrowserStackLocal binary that is required for testing localhost websites
def start_local():
    """Code to start browserstack local before start of test."""
    global bs_local
    bs_local = Local()
    bs_local_args = { "key": BROWSERSTACK_ACCESS_KEY, "forcelocal": "true" }
    bs_local.start(**bs_local_args)

def stop_local():
    """Code to stop browserstack local after end of test."""
    global bs_local
    if bs_local is not None:
        bs_local.stop()

# The following code reads the capabilities as defined in the config file and sets them while creating a new webdriver instance
def before_feature(context, feature):
    desired_capabilities = CONFIG['environments'][TASK_ID]

    for key in CONFIG["capabilities"]:
        if key not in desired_capabilities:
            desired_capabilities[key] = CONFIG["capabilities"][key]

    if 'BROWSERSTACK_APP_ID' in os.environ:
        desired_capabilities['app'] = os.environ['BROWSERSTACK_APP_ID']

    if "browserstack.local" in desired_capabilities and desired_capabilities["browserstack.local"]:
        start_local()

    context.browser = webdriver.Remote(
        desired_capabilities=desired_capabilities,
        command_executor="https://%s:%s@%s/wd/hub" % (BROWSERSTACK_USERNAME, BROWSERSTACK_ACCESS_KEY, CONFIG['server'])
    )

# The following code is called after the feature is completed. It marks the status of tests and closes the browser connection with BrowserStack
def after_feature(context, feature):
    if context.failed is True:
        context.browser.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "At least 1 assertion failed"}}')
    if context.failed is not True:
        context.browser.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "All assertions passed"}}')
    context.browser.quit()
    stop_local()

Mark tests as passed or failed

BrowserStack does not know whether your test’s assertions have passed or failed because only the test script knows whether the assertions have passed.

Marking the status of test is possible using our custom Javascript executor. Add the following snippet in the after_feature of environment.py and it will mark tests as either passed or failed based on assertions:

def after_feature(context, feature):
    if context.failed is True:
        context.browser.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed", "reason": "At least 1 assertion failed"}}')
    if context.failed is not True:
        context.browser.execute_script('browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed", "reason": "All assertions passed"}}')
Note: The arguments passed in the JavaScript method for setting the status and the corresponding reason for the test are status and reason.
  • status accepts either passed or failed as the value
  • reason accepts a value in string datatype

Marking test as pass/fail is also possible using our REST API at any point in the test or also after the test has concluded. You can read more about marking test using REST API and use it, if it fits your use case.

Debug your app

BrowserStack provides a range of debugging tools to help you quickly identify and fix bugs you discover through your automated tests.

Text logs

Text Logs are a comprehensive record of your test. They are used to identify all the steps executed in the test and troubleshoot errors for the failed step. Text Logs are accessible from the Automate dashboard or via our REST API.

Visual logs

Visual Logs automatically capture the screenshots generated at every Selenium command run through your Python script. Visual logs help with debugging the exact step and the page where failure occurred. They also help identify any layout or design related issues with your web pages on different browsers.

Visual Logs are disabled by default. In order to enable Visual Logs you will need to set browserstack.debug capability to true:

desired_cap['browserstack.debug'] = True

Sample Visual Logs from Automate Dashboard: BrowserStack Automate Visual Logs

Video recording

Every test run on the BrowserStack Selenium grid is recorded exactly as it is executed on our remote machine. This feature is particularly helpful whenever a browser test fails. You can access videos from Automate Dashboard for each session. You can also download the videos from the Dashboard or retrieve a link to download the video using our REST API.

Note: Video recording increases test execution time slightly. You can disable this feature by setting the browserstack.video capability to false.

In addition to these logs BrowserStack also provides Raw logs, Network logs, Console logs, Selenium logs, Appium logs and Interactive session. Complete details to enable all the debugging options can be found here

Next steps

Once you have successfully run your first test on BrowserStack, you might want to do one of the following:

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





Talk to automation expert