How to create a temporary directory for a feature in python's behave (cucumber)?

39 Views Asked by At

I'm trying to do a python port of some ruby code that uses Cucumber for testing. I'm attempting to use the exact same feature files in the new port. One of the features looks a bit like:

Feature: <whatever>

@with_tmpdir
Scenario: generating a file
  Given <some setup stuff>
    And file 'test.out' does not exist
   When I call <something> with argument 'test.out'
   Then a file called 'test.out' is created
    And the file called 'test.out' contains:
      """
      <some contents>
      """

To support this, the original code has the following in features/support/hooks.rb:

Around('@with_tmpdir') do |scenario, block|
  old_pwd = Dir.getwd
  Dir.mktmpdir do |dir|
    Dir.chdir(dir)
    block.call
  end
  Dir.chdir(old_pwd)
end

Now, I'd like to figure out how to do this sort of thing in behave, presumably/ideally utilizing with tempfile.TemporaryDirectory as tmpdir in place of ruby's Dir.mktmpdir do |dir|.

Alas, I don't see anything to indicate support for Around hooks. It seems like maybe this is the sort of thing that fixtures are meant to do? Can fixtures do what I'm hoping for? If so, how?

1

There are 1 best solutions below

0
lindes On

Indeed, fixtures can be used to get the behavior you're looking for. To wit, you could add the following code to features/environment.py, and it should do the trick:

from behave import fixture, use_fixture
from tempfile import TemporaryDirectory
from os import getcwd, chdir

@fixture
def with_tmpdir(context, **kwargs):
  old_pwd = getcwd()
  with TemporaryDirectory() as tmpdir:
    chdir(tmpdir)
    yield
  chdir(old_pwd)

# note: maybe re-tag as fixture.with_tmpdir ?
def before_tag(context, tag):
  if tag == 'with_tmpdir':
    use_fixture(with_tmpdir, context)

As a side-note, and indicated in a comment above, the normal convention in behave is for the tags for fixtures to be called fixture.<something>. Per the docs:

Fixture tags should start with "@fixture.*" prefix to improve readability and understandibilty in feature files (Gherkin).

That said, I left the code to react to the feature file as you present it, since you state you're hoping to use the same file, presumably unchanged.