HomeBlogPython and Behave: A Perfect Match for BDD

Python and Behave: A Perfect Match for BDD

Author

Date

Category

Behavior Driven Development (BDD) is a method of software development that emphasizes understanding and enhancing the interaction between programmers, stakeholders, and testers. It is an extension of Test Driven Development (TDD) that strives to make the expectations and needs of business stakeholders more understandable, precise, and unambiguous.

Using BDD has the benefit of encouraging better collaboration between multiple divisions, like development, testing, and product management. This helps to make sure that everyone is aware of the purpose of the software and that the final result satisfies the needs of all stakeholders.

This is a simple demonstration of BDD and how it works:

The utilization of BDD offers an extra benefit of making software testing and verification more straightforward. Tests can be written in a plain, understandable language for everybody involved in the development process, which makes it simpler to identify and mend flaws as well as to adjust the software as necessary.

Python and BDD

In the Python environment, there are several frameworks available for BDD testing, one of which is behave. Behave is a popular BDD testing framework that uses the Gherkin language to create tests in a natural, easy-to-read format. It is user-friendly, and supports various features including tags, tables and hooks.

Here’s a sample code snippet of how to use behave in Python:

Feature: Addition
  In order to avoid silly mistakes
  As a math idiot
  I want to be told the sum of two numbers

  Scenario: Add two numbers
    Given I have entered 50 into the calculator
    And I have entered 70 into the calculator
    When I press add
    Then the result should be 120 on the screen

This code specifies a function of a calculator that adds two numbers. It outlines the instructions for testing the feature and the expected result. This code can be implemented through behave, which will execute the tests and give a report on the results.

Getting Started to use Behave

To install the behave package in Python, you can use the pip package manager. Simply run the following command in your terminal or command prompt:

$ pip install behave

After the installation, you can use the following code to run the BDD example that was shown in the previous section:

from behave import *

@given("I have entered {number1:d} into the calculator")
def step_impl(context, number1):
    context.number1 = number1

@given("I have entered {number2:d} into the calculator")
def step_impl(context, number2):
    context.number2 = number2

@when("I press add")
def step_impl(context):
    context.sum = context.number1 + context.number2

@then("the result should be {result:d} on the screen")
def step_impl(context, result):
    assert context.sum == result, f"Expected {result}, but got {context.sum}"

This code defines the implementation of the steps in the BDD scenario. The @given, @when, and @then decorators are used to mark the functions as step implementations. The code uses the context object to store intermediate data, such as the numbers being added, and the sum. The assert statement is used to validate the expected result.

To run the tests, simply run:

$ behave

This will run the tests defined in your feature file, and produce a report on the results.

Recommended directory structure for a Behave project:

The recommended directory structure for a project using the behave framework is as follows:

project_root/
    features/
        feature_file.feature
    steps/
        step_definitions.py
    environment.py (optional)
    behave.ini (optional)
  • The features directory contains the feature files written in Gherkin syntax. A feature file describes a feature or behavior of the software being tested.
  • The steps directory contains the step definitions, which are the implementation of the steps described in the feature file. The step definitions are written in Python.
  • The environment.py file is an optional file that can be used to define setup and teardown actions that are performed before and after each scenario.
  • The behave.ini file is an optional configuration file that can be used to specify settings for the behave command.

This directory structure provides a clear separation of the feature descriptions and the step definitions, making it easier to maintain and scale the project over time.

Using of Tags in features:

A section of a feature file can be tagged so that the Behave is capable of verifying only a certain section of the feature file. A Scenario, Feature, Scenario Outline can only be tagged.

Also, a tag which is used for a feature shall be inherited by all its Scenarios and the Scenario Outlines. Tags are placed before a Scenario or a Feature that we want to tag. We can also have multiple tags which are separated by spaces within a line.

A tag begins with @ and is followed by the tag name. To run tests with specifying the tags you can run:

$ behave file_name.feature --tags=tag1 --tags=tag2

Do more with BehaveX

BehaveX is an enhancement of the Python Behave platform, offering additional features for pipeline testing. It is possible to begin using BehaveX from the outset with the common Behave principles, or to add it to existing Behave projects. In essence, this wrapper takes the existing Behave capabilities and enhances them to include the following:

  • Perform parallel test executions (multi-process executions): By feature and By scenario
  • Get additional test execution reports: HTML and JSON report
  • Provide additional evidence as part of execution reports
  • Generate test logs per scenario
    • Whatever you log in test steps using the logging library, it will generate an individual log report for each scenario
  • Mute test scenarios in build servers
    • By adding @MUTE tag to test scenarios, they will be executed, but they will not be part of the JUnit reports
  • Generate metrics in HTML report for the executed test suite
    • Automation Rate, Pass Rate and Steps executions & duration
  • Execute dry runs and see the full list of scenarios into the HTML report
    • This is an override of the existing Behave dry run implementation
  • Re-execute failing test scenarios
    • By adding @AUTORETRY tag to test scenarios, so when the first execution fails the scenario is immediately re-executed

After installing BehaveX: pip install behavex you can run the tests with more flags and params:

$ behavex -t @TAG –parallel-processes 4 –parallel-scheme scenario

$ behavex -t @TAG –parallel-processes 3 –parallel-scheme feature

For more info on BehaveX see its Github repository:

https://github.com/hrcorval/behavex

Mehdi Shokoohi

Software Quality Engineer

Recent posts

Recent comments