【问题标题】:Pytest, How to do test against either fixture's value or None?Pytest,如何针对夹具的值或无进行测试?
【发布时间】:2019-10-16 08:50:23
【问题描述】:

我有一个 test-case 和一个 fixture

@pytest.fixture
def user(test_client):
    return User.objects.first()


@pytest.mark.parametrize('content', ['nice post',])
def test_post(test_client, user, content):
    reponse = test_client.post(
        '/api/v1.0/posts', 
        json={
            'content': content,
            'author': user,
        },
        follow_redirects=True
    )

    assert reponse.status_code == 200

但除了针对某些User 对象进行测试之外,我还想针对None 进行测试(我希望测试失败为无)。我想我可以这样做:

@pytest.fixture(params=[True, False])
def User_or_null(test_client, request):
    if request.param:
        return User.objects.first()
    else:
        return None

但我不认为这将允许我用pytest.mark.xfail 标记测试用例None 值?有什么想法吗?

【问题讨论】:

    标签: python integration-testing pytest


    【解决方案1】:

    我认为参数化user 夹具没有问题。您可以通过pytest.param标记单独的参数,例如:

    @pytest.fixture(params=[
        'testuser',
        # wrap None into pytest.param to treat it specially
        pytest.param(None, marks=pytest.mark.xfail)
    ])
    def user(request):
        if request.param is None:
            return None
        return User.objects.filter(name=request.param).first()  # or whatever
    

    但是,这意味着使用user 夹具的所有测试都将在None 上失败/通过 - 这可能不是您想要的所有测试。如果您只想 xfail 选定的测试,请使用间接参数化:

    # user fixture is not parametrized now
    
    @pytest.fixture
    def user(request):
        if request.param is None:
            return None
        return User.objects.filter(name=request.param).first()
    
    # instead, parametrizing is done from the test:
    
    @pytest.mark.parametrize('content', ['nice post',])
    @pytest.mark.parametrize('user', [
        'testuser',
        pytest.param(None, marks=pytest.mark.xfail
    )], indirect=True)
    def test_post(test_client, user, content):
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多