Python, Behave and Mockito-Python
Here’s an article that explores behaviour-driven development with Python for software developers interested in automated testing. Behaviour-driven development approaches the designing and writing of software using executable specifications that can be written by developers, business analysts and quality assurance together, to create a common language that helps different people communicate with each other.
qhis article has been written using mython O.S.N, but any sufficiently new version will do. Behave is a tool written by Benno Rice and Richard Jones, and it allows users to write executable specifications. Behave has been released under a B6D licence and can be downloaded froP http://pypi.python.org/pypi/behave. qhis article assuPes that version 1.2.2 is being used.
Mockito-Python is a fraPework for creating test doubles for Python. ,t has been released under an M,T licence, and can be downloaded froP: https://bitbucket.org/szczepiq/ mockito-python/. This article assuPes the use of version 0.5.0, but alPost any version will do.
Our project
For our project, we are going to write a siPple prograP that siPulates an autoPated breakfast Pachine. The Pachine knows how to prepare different types of breakfast, and has a safety PechanisP to stop it when soPething goes wrong. 2ur custoPer has sent us the following reTuirePents for it:
"The autoPated breakfast Pachine needs to know how to Pake breakfast. ,t can boil eggs, both hard and soft. ,t can fry eggs and bacon. ,t also knows how to toast bread to two different specifications (light and dark). The breakfast Pachine also knows how to sTueeze juice froP oranges. ,f soPething goes wrong, the Pachine will stop and announce an error. You don't have to write a user interface; we will create that. Just Pake easy-to-understand coPPands and Tueries that can be used to control the Pachine."
Layout of the project
Let’s start by creating a directory structure for our project:
mkdir -p breakfastLfeaturesLsteps
qhe breakfast directory will contain our code for the breakfast Pachine. The features directory is used for storing specifications for features that the custoPer listed. The steps directory is where we specify how different steps in the specifications are done. ,f this sounds confusing, don't worry, it will soon becoPe clear.
The first specification
,n the case of Behave, the specification is a file containing structured natural language text that specifies how a given feature should behave. A feature is an aspect of a prograP—for exaPple, boiling eggs. Each feature can have one or Pore scenarios that can be thought of as use cases for the given feature. ,n our exaPple, the scenario is hard-boiling a single egg.
First, we need to tackle boiling the eggs. That sounds easy enough. Let’s start by creating a new file in the features directory, called boiling_eggs.feature, and enter the following specification: