Search code examples
pythonflaskbddpython-behave

Behaviour Driven Development - Undefined steps in Behave using Python with Flask


I'm following a Flask tutorial and currently looking at Behaviour Driven Development using Behave.

My task is to build a very basic blog application that allows a single user to log in, log out and create blog posts, using BDD.

I've written the feature file, the steps file and the environment file. I've then written code to enable a user to log in and out.

When I run the application locally and manually test, it works as expected allowing the user to log in and out and displays the required text ("You were logged in" or "You were logged out"), so I'm assuming the problem is with the feature file or steps file rather than the application code.

When I run Behave, the final step appears to be "undefined".

The relevant part of the feature file is:

Feature: flaskr is secure in that users must log in and log out to access certain features

Scenario: successful login
  Given flaskr is setup
    When we log in with "admin" and "admin"
    Then we should see the alert "You were logged in"

Scenario: successful logout
    Given flaskr is setup
    and we log in with "admin" and "admin"
      When we log out
      Then we should see the alert "You were logged out"

And my steps file is:

from behave import *

@given(u'flaskr is setup')
def flask_is_setup(context):
    assert context.client

@given(u'we log in with "{username}" and "{password}"')
@when(u'we log in with "{username}" and "{password}"')
def login(context, username, password):
    context.page = context.client.post('/login', 
                                        data=dict(username=username,
                                            password=password),
                                        follow_redirects=True
                                    )
    assert context.page

@when(u'we log out')
def logout(context):
    context.page = context.client.get('/logout', follow_redirects=True)
    assert context.page

@then(u'we should see the alert "{message.encode("utf-8")}"')
def message(context, message):
    assert message in context.page.data

From the environment file:

def before_feature(context, feature):
    context.client = app.test_client()

It is the final "then" step that seems to be the problem. I've tried checking the tutorial solutions and searching elsewhere but I can't seem to solve this part of the code. I've had to encode the message as I am using Python version 3.5 (the tutorial was using version 2.7 if this is relevant).

Any pointers would be very much appreciated.


Solution

  • Moving the encode solved the problem. I now have

    @then(u'we should see the alert "{message}"')
    def message(context, message):
        assert message.encode("utf-8") in context.page.data