繁体   English   中英

pytest-bdd:如何从@given获取当前方案?

[英]pytest-bdd: how to get current scenario from @given?

我需要获取场景名称或有关@given方法中当前正在运行的测试的其他唯一信息。

在测试中,我声明自己有一些资源。 该资源是从Web API中提取/创建的,如下所示:

@given('I have a new article')
def new_article(vcr_fixture):
    with vcr_fixture.use_cassette('new_article'):  # I need to use different cassette name for different scenarios 
        return create_new_article()

这里的问题是我可以有多个具有不同参数的方案,并且我想多次使用相同的资源。 在这种情况下,我需要为每种情况使用不同的纸盒。 而且我不能使用这些参数来区分录像带,因为它们可以在创建资源后应用(例如,添加注释)。 我试图将请求添加到@given固定装置,但是找不到任何唯一信息。

要检查方案名称,可以使用解析器。

from pytest_bdd import parsers
...

@given(parsers.parse('I have a {article_name}')
def new_article(vcr_fixture, article_name):
    with vcr_fixture.use_cassette(article_name):        
        return create_new_article()

不知道这是否可以回答您的问题。

n尽管user2292262提出的建议有效,但它并不像开始学习pytest-bdd时所期望的那样有效(至少是我期望的)。

AIUI解决方案正在为测试中的每篇文章创建一个夹具,而没有自动性(即为您动态创建所需数据的功能)。

在测试上下文中,这应该是合理可行的,因为您拥有的数据集不是真实的数据集,但是您拥有的子集和作为先决条件(给定动词)的数据应该更少。 您可以考虑使用脚本来填充灯具,方法是查询数据库并相应地编写模板文件。

@given(parsers.parse('I have an article called foo')
def article_foo(vcr_fixture):
    with vcr_fixture.use_cassette('foo'):
         return create_new_article()

@given(parsers.parse('I have an article called bar')
def article_bar(vcr_fixture):
    with vcr_fixture.use_cassette('bar'):
         return create_new_article()


etc.

另一个解决方案的“工厂”代码中的问题

@given(parsers.parse('I have a {article_name}')
def new_article(vcr_fixture, article_name):
    with vcr_fixture.use_cassette(article_name):        
         return create_new_article()

是您仍然很想将其用作

Given I have an article called Foo
And I have an article called Bar
When I edit Foo
Then Bar is untouched

但这种情况不会起作用,因为您实际上是在窗帘下两次使用相同的灯具,但是使用了不同的“内容”

换句话说,有了该代码,有人将为两个“数据”实例提供“ new_article”。 这违背了pytest喜欢的东西。

同样,从纯粹主义者的角度来看,BDD中的给定动词应该是事实,而不是创造事实的事物。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM