【问题标题】:pytest: parametrize class based tests with fixtures (pytest-django)pytest:使用夹具参数化基于类的测试(pytest-django)
【发布时间】:2020-01-30 21:17:48
【问题描述】:

我正在尝试像这样对我的班级测试进行参数化:

@pytest.mark.parametrize('current_user', ["test_profile_premium", "test_profile_free"], indirect=True)
class TestFeedItemsType:

    @pytest.fixture(autouse=True)
    def setup(self, current_user, logged_in_client, dummy_object):
        self.client = logged_in_client
        self.test_profile = current_user
        self.object = dummy_object

但是,我收到了错误:

找不到夹具“当前用户”

test_profile_premiumtest_profile_free 都是 conftest.py 中现有的有效装置。我需要这个基于类的套件中的所有函数(测试)来针对test_profile_premiumtest_profile_free 运行。

【问题讨论】:

    标签: python pytest pytest-django


    【解决方案1】:

    您不能将固定装置作为参数化参数传递,有关详细信息,请参阅open issue #349。作为一种解决方法,在您的示例中,您可以引入一个 current_user 夹具,该夹具根据夹具名称执行夹具选择:

    import pytest
    
    
    @pytest.fixture
    def current_user(request):
        return request.getfixturevalue(request.param)
    
    
    @pytest.fixture
    def test_profile_premium():
        return "premiumfizz"
    
    
    @pytest.fixture
    def test_profile_free():
        return "freefizz"
    
    
    @pytest.mark.parametrize('current_user', ["test_profile_premium", "test_profile_free"], indirect=True)
    class TestFeedItemsType:
    
        @pytest.fixture(autouse=True)
        def setup(self, current_user):
            self.test_profile = current_user
    
        def test_spam(self):
            assert self.test_profile in ("premiumfizz", "freefizz")
    
        def test_eggs(self):
            assert self.test_profile in ("premiumfizz", "freefizz")
    

    运行此示例将产生四个测试:

    test_spam.py::TestFeedItemsType::test_spam[test_profile_premium] PASSED
    test_spam.py::TestFeedItemsType::test_spam[test_profile_free] PASSED
    test_spam.py::TestFeedItemsType::test_eggs[test_profile_premium] PASSED
    test_spam.py::TestFeedItemsType::test_eggs[test_profile_free] PASSED
    

    【讨论】:

    • 谢谢。这与我最终所做的非常接近。我需要在参数化中定义expected 结果,所以我使用元组,然后使用indirect=["profile"]
    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2015-11-23
    相关资源
    最近更新 更多