Search code examples
pythontestinglettuce

pass in multiple arguments in lettuce test step


generally each lettuce test step takes 1 parameter, is there a way to pass in multiple arguments in a single step ?

like, can I have this:

@step('I have the number (\d+) and character (\w+)')
def have_the_number(step, number, character ):
    world.number = int(number)
    world.character = str(character)

Solution

  • Your code is perfectly valid. You can both positional arguments (like *args, just like in your example) as well as named ones (like **kwargs).

    Consider you have the following math.feature:

    Feature: Basic computations
        In order to play with Lettuce
        As beginners
        We will implement addition and subtraction
    
        Scenario: Sum of 0 and 1
            Given I have to add the numbers 0 and 1
            When I compute its factorial
            Then I see the number 1
    
        Scenario: Difference of 3 and 5
            Given I have to substract 5 from 3
            When I compute their difference
            Then I see the number -2
    

    and such steps.py:

    from lettuce import *
    
    @step('I have to add the numbers (\d+) and (\d+)')
    def have_to_add(step, number1, number2):
        world.number1 = int(number1)
        world.number2 = int(number2)
    
    @step('I have to substract (?P<subtrahend>) from (?P<minuend>)')
    def have_to_substract(step, minuend, subtrahend):
        world.minuend = int(minuend)
        world.subtrahend = int(subtrahend)
    
    @step('I compute their difference')
    def compute_difference(step):
        world.number = world.minuend - world.subtrahend
    
    @step('I compute their sum')
    def compute_sum(step):
        world.number = world.number1 + world.number2
    
    @step('I see the number (\d+)')
    def check_number(step, expected):
        expected = int(expected)
        assert world.number == expected, "Got %d" % world.number
    

    Take a closer look at the subtraction example, it shows how you can refer to captured variables by name rather then by position.