Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write cucumber Step definitions in python

I am new to the Cucumber framework. I am trying to make Cucumber work with Python. I have written the feature file and want to know how to write the step definitions in Python.

I searched over the internet and found the step definitions for Ruby language but nothing for Python. Is it even possible to run Cucumber with Python?

like image 493
vansha Avatar asked Jul 09 '15 12:07

vansha


2 Answers

Check out behave, behaviour-driven development library, Python style.

Behavior-driven development (or BDD) is an agile software development technique that encourages collaboration between developers, QA and non-technical or business participants in a software project. We have a page further describing this philosophy.

behave uses tests written in a natural language style, backed up by Python code.

It doesn't use Cucumber, but you can reuse .feature files because they use the same Gherkin language.

Sample behave's step definition:

from behave import *

@given('we have behave installed')
def step_impl(context):
    pass

@when('we implement a test')
def step_impl(context):
    assert True is not False

@then('behave will test it for us!')
def step_impl(context):
    assert context.failed is False
like image 156
Hendy Irawan Avatar answered Oct 21 '22 07:10

Hendy Irawan


Cucumber supports 14 languages right now, including Python on the JVM also called Jython.

I would start by reading up on Cucumber-JVM, it is an implementation of Cucumber for the JVM. To use the Java 6/7 so you can use the Cucumber API. You need to write Python methods with Java annotations, to tell Cucumber which regexes correlate with each method.

This sounds like a lot of indirection, but it is fairly straight forward:

Gherkin:

Scenario: Some cukes
  Given I have 48 cukes in my belly

Python/Jython:

@Given('^I have (\d+) cukes in my belly')
def i_have_cukes_in_my_belly(self, cukes):
   print "Cukes: " + cukes

This was copied from the cucumber reference page in the corner of each code sample (not gherkin, but step definition), you can select the language of you choice.

The documentation is incomplete, but where it is complete it is useful. It does include the entry for your maven config if you are using that and most of the information needed for basic use. Any documentation you find elsewhere on the web for cucumber in Java should work with Jython as long as you are familiar with calling Java from Jython.

like image 38
Sqeaky Avatar answered Oct 21 '22 05:10

Sqeaky