Tag Archives: behave

‘Behave’ functional testing and the context object

Saving data to the context object

When using the behave framework for functional testing it’s often necessary to set some data at the start of the testing and be able to make use of it throughout the test run.

The context object (api of the object) is there to help you however I don’t think the current documentation makes it as it clear as it should be how you do this.

An Example

Within the environment.py (placed in your features directory) you can define an event handler to run before any testing is done, that event handler is called before_all below is an example of using before_all to set an arbitrary value which is then available through out the test run.

#This event runs before any of your tests
def before_all(context):
   #Choose whatever property name you like and assign 
   #a value to it. In this case I have chosen 'colour'
   #and assigned "RED" to it.
   context.colour = "RED"

   #You can assign any python object to one of these
   #properties, here's an example of assigning a dictionary
   #to one
   context.weather = {'temp-centigrade': '21', 'wind-speed-kmh': 5}


The context object is used by behave for other purposes so whatever property you set you need to check that it’s not one that is used by behave internally.

There’s a list of the internally used properties here so you can avoid them.

My opinon

To ensure you don’t accidentally stomp on one of the predefined properties it might be best to use only one top level property (eg context.my_project_name) and assign an empty dictionary to that. You can then store everything you want within the dictionary at context.my_project_name).