【问题标题】:Pytest: Using fixtures in setup_methodPytest:在 setup_method 中使用固定装置
【发布时间】:2019-03-08 17:33:22
【问题描述】:

遵循此模式:https://docs.pytest.org/en/latest/xunit_setup.html

我如何使用/注入fixture_foosetup_method

class TestClassX:
    def setup_method(self, method):
        # I need `fixture_foo` here

    def teardown_method(self, method):
        # N/A

    def test_cool(self, fixture_foo):
        # Why can `fixture_foo` be injected here and not in `setup_method`?

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    您必须切换到pytest 风格的灯具才能访问灯具。 setup_method 的等价物可以实现如下:

    @pytest.fixture
    def f():
        return 'ohai'
    
    
    class Test:
        @pytest.fixture(autouse=True)
        def setup_method_fixture(self, request, f):
            self.f = f
            self.method_name = request.function.__name__
    
        def test(self):
            assert self.method_name == 'test'
            assert self.f == 'ohai'
    

    这个autouse 夹具将在类内的每个测试方法中调用一次

    【讨论】:

    • “您必须切换到 pytest 风格的夹具才能访问夹具”。你能举一个这种风格的例子来访问测试类中的夹具吗?
    • @Keto 我回答中的代码块
    • 谢谢,我误解了你的回答,认为这个例子是 xunit 和 pytest 的混合体。
    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多