我正在尝试做一些 ruby 代码的 python 端口,使用 Cucumber 进行测试。我正在尝试在新端口中使用完全相同的功能文件。其中一个功能看起来有点像:
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>
"""
为了支持这一点,原始代码在
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
现在,我想弄清楚如何在 behave 中做这类事情,大概/理想地利用
with tempfile.TemporaryDirectory as tmpdir
代替 ruby 的 Dir.mktmpdir do |dir|
。
唉,我没有看到任何表明支持
Around
钩子的内容。看起来也许这就是 fixtures 应该做的事情?装置能达到我所希望的效果吗?如果是的话,怎么办?
确实,可以使用固定装置来获得您正在寻找的行为。也就是说,您可以将以下代码添加到
features/environment.py
,它应该可以解决问题:
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)
作为旁注,并在上面的评论中指出,行为中的正常约定是灯具的标签被称为
fixture.<something>
。根据文档:
夹具标签应以
前缀开头,以提高功能文件 (Gherkin) 的可读性和可理解性。"@fixture.*"
也就是说,我留下了代码来对您呈现的功能文件做出反应,因为您声明您希望使用相同的文件,大概没有改变。