如何将参数传递到夹具并在测试方法中使用该夹具?

时间:2018-11-15 12:02:14

标签: python automation pytest

我想在此处传递用户名,密码和电子邮件作为固定装置参数:

@pytest.fixture()
def create_user(self):
    try:
        assert self.rbac.put_user(username, password, email).status_code == 200
        yield
    except AssertionError:
        assert self.rbac.get_user(username).status_code == 200
        yield
    finally:
        assert self.rbac.delete_user(username).status_code == 200

稍后我将在测试中使用此灯具:

@pytest.mark.usefixtures("create_user")
def test_assign_delete_user_to_group(self):
"""some code"""

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试工厂固定装置:

@pytest.fixture()
def user_factory(self, request):
    created_users = []

    def create_or_get_user(username):
        try:
            assert self.rbac.put_user(username, password, email).status_code == 200
        except AssertionError:
            assert self.rbac.get_user(username).status_code == 200
        created_users.append(username)

    yield create_or_get_user

    for username in created_users:
        assert self.rbac.delete_user(username).status_code == 200

然后将其与

一起使用
def test_assign_delete_user_to_group(self, user_factory):
    """some code"""
    u = user_factory('foo')
    assert u