BDD With Python

Introduction

BDD (Behaviour driven development) adapted features of TDD(Test Driven Development) and extended a few little syntax, which made the Product Owner (PO Role of Scrum Process) or Business Analyst job easy to convert requirements into standard scripts, by analysing the behaviour of features required by customers. And the developer's job will be easy with this behaviour, scripts drive the development.

Pre-requisite

  • A Developer should know python
  • Recommend reading about TDD first.

We will see this BDD with an example of calci. BDD is following Gherkin syntax's. an example will be illustrated below Gherkin syntax's

  • Feature:
  • Scenario:
  • Given
  • When
  • Then

Requirement from the customer: Build a calculator app, for 2 numbers addition and substraction

For BDD, we will a "behave" package, which is available in python. Install the package with the following command

pip install behave

Convert requirements into feature file like below using Gherkin syntax, File name: calci.feature

Feature: Test Calci
  Scenario: Add 2 numbers
    Given Calci app is running
    When Provided input "2" and "2" with add
    Then get result "4"
  Scenario: Substract 2 numbers
    Given Calci app is running
    When Provided input "5" and "2" with sub
    Then get result "3"

For Gherkin syntax keywords, write steps like below

File name: calci_steps.py

from behave import given, when, then
from calci import add, sub

@given(u'Calci app is running')
def step_impl(context):
    print(u'Calci app is running')

@when(u'Provided input "{a}" and "{b}" with add')
def step_impl(context, a, b):
    context.result = add(int(a), int(b))

@when(u'Provided input "{a}" and "{b}" with sub')
def step_impl(context, a, b):
    context.result = sub(int(a), int(b))

@then(u'get result "{out}"')
def step_impl(context, out):
    print("context.result: ", context.result)
    assert context.result == int(out), 'Expected {}, got {}'.format(out, context.result)

Below is the calci.py file which actually contains business logic. Actually, here to develop this calci.py, we need to follow TDD. As the article is to know about BDD. I am putting code directly.

def add(a, b):
    return a + b;

def sub(a, b):
    if a > b:
        return a - b;
    return b - a;

Normally, a file/folder structure should look like the one below.

Now execute the feature file with a behave command,

behave features/calci.feature 

If you are creating a virtual environment, execute with the below command. 

Switch to virtual env using command,

pipenv shell

Run test with command,

pipenv run behave features/calci.feature

Below is the output window,

Summary

In this article, we understood about BDD execution. FYR I attached a source code zip file to this article.


Recommended Free Ebook
Similar Articles