Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Behave sharing data between features

I'm starting with Python Behave as I want to make an API testing thing.
Currently I stumbled upon something that may not be even valid but the question is: Can I share data between features? I could store some in a DB or files but maybe there is something 'builtin'?

Or is this invalid and I shouldn't share data like that, or maybe it's possible inside a feature?

In practice it looks like:

I have to make a request to an endpoint, in the response I get a number that is required to make another request that's needed to be tested.

like image 560
McAbra Avatar asked Jun 10 '26 17:06

McAbra


1 Answers

Yes, you can, and it is trivial. In the same directory where you have your feature files you can create a file named environment.py. In it, you can put:

def before_all(context):
    context.db = whatever

The before_all hook is run before all the tests and whatever you set there is available to all features. I use this, for instance, to create a new Selenium instance that will be used by all tests in a test suite. context.db above could be a database connection. This kind of sharing is fine.

What you share should be read-only or be resettable to a known state between tests. It is not a good practice to share writable resources between tests. It makes it hard to figure out what went wrong when a test fails and it makes tests dependent on each other. So if you have a failure on test C but it depends on A and B you cannot just ask Behave to run test C. You have to ask it to run A, B and then C.

If you decide to go against the best practices and do it anyway, you should be aware that new values set on context are scoped by feature and scenario. So if your before_all hook sets context.foo = 1 and then feature A sets context.foo = 2. When feature B runs after feature A, it will see the value 1 for context.foo because Behave will have removed the changes made by feature A (the changes made by feature A are "scoped" to feature A.) Now, you have to remember how Python stores values. If the hook sets context.foo = [] and feature A does context.foo.append(1), then feature B will see that context.foo has the value [1] because context.foo contains a reference to the array and calling append changes the array itself. So it is possible to work around the scoping. This is still not advisable, though.

Last I checked, features are run in alphabetical order. You can force the order by specifying features on the command line: behave B.feature A.feature

like image 135
Louis Avatar answered Jun 12 '26 13:06

Louis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!