Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass an object like a list or dictionary in python behave .feature file

How can I pass an object like a list or dictionary as an argument in behave .feature file so I can use that argument in my python function step? See an example of what I'm trying to achieve below:

Feature:
Scenario: Given the inputs below
    Given a "<Dictionary>" and  "<List>"
    When we insert "<Dictionary>" and  "<List>"
    Then we confirm the result in the database

    Examples: Input Variables
        |Input1                    |Input2    |
        |Dictionary(json)          |List      |
like image 450
tfalade Avatar asked Oct 03 '18 20:10

tfalade


1 Answers

You can provide the data as json, and parse it using json.loads in the steps.

Note, to use Examples: we need a Scenario Outline instead of a Scenario.

# features/testing_objects.feature
Feature: Testing objects
    Scenario Outline: Given the inputs below
        Given a <Dictionary> and <List>
        When we insert them
        Then we confirm the result in the database

        Examples: Input Variables
            |Dictionary                |List         |
            |{"name": "Fred", "age":2} |[1,2,"three"]|

Parse it using json.loads in the steps:

# features/steps/steps.py
import json
from behave import given, when, then

@given('a {dictionary} and {a_list}')
def given_dict_and_list(context, dictionary, a_list):
    context.dictionary = json.loads(dictionary)
    context.a_list = json.loads(a_list)

@when('we insert them')
def insert_data(context):
    print('inserting dictionary', context.dictionary)
    print('inserting list', context.a_list)

@then('we confirm the result in the database')
def confirm(context):
    print('checking dictionary', context.dictionary)
    print('checking list', context.a_list)

Instead of using Examples: you could also use a multi-line string literal and then access each object in a separate step, via context.text.

Feature: String literal JSON
    Scenario:
        Given a dictionary
        """
        {
            "name": "Fred",
            "age": 2
        }
        """
        And a list
        """
        [1, 2, "three"]
        """
        Then we can check the dictionary
        And check the list
@given('a dictionary')
def given_a_dictionary(context):
    context.dictionary = json.loads(context.text)

@given('a list')
def given_a_list(context):
    context.a_list = json.loads(context.text)

@then('we can check the dictionary')
def check_the_dictionary(context):
    assert context.dictionary == {
        'name': 'Fred',
        'age': 2
    }

@then('check the list')
def check_the_list(context):
    assert context.a_list == [1, 2, 'three']
like image 191
Daniel Golding Avatar answered Oct 28 '22 12:10

Daniel Golding