【问题标题】:how to pass parameter into setup_method for pytest如何将参数传递给pytest的setup_method
【发布时间】:2017-05-10 20:58:10
【问题描述】:

我需要编写一些测试用例来测试用户的权限。在每个测试用例中,UserA 具有不同的权限并进行检查。我想使用管理员角色在 setup_method 中为 userA 提供不同的权限。如何将参数传递给 setup_method 以便在每个测试用例开始之前,我可以有不同的测试用例?我有类似以下的内容,但不确定如何将参数传递给 setup_method。

class TestPermission():

    @classmethod
    class setup_method(self, permission):
        login as amdin
        provide permission to userA
        logout
        login as userA

    @classmethod
    class teardown_method(self):
        logout as userA

    @fixure(permission1)
    class test_permissionA(self):
        assert drive.find_element_by_xpath('//div[@id="permission1"]') is True
        assert drive.find_element_by_xpath('//div[@id="permission2"]') is False
        assert drive.find_element_by_xpath('//div[@id="permission3"]') is False

    @fixure(permission2)
    class test_permissionB(self):
        assert drive.find_element_by_xpath('//div[@id="permission1"]') is False
        assert drive.find_element_by_xpath('//div[@id="permission2"]') is True
        assert drive.find_element_by_xpath('//div[@id="permission3"]') is False

【问题讨论】:

    标签: python-3.x selenium selenium-webdriver pytest pytest-django


    【解决方案1】:

    您应该在这里使用参数化的固定装置:https://docs.pytest.org/en/latest/fixture.html#fixture-parametrize

    所以最终的代码看起来像这样:

    @pytest.fixture(scope="function", params=[{'permission': 'permission1', 'expected_result': {'perm1': True, 'perm2': False, 'perm3': False}}, {'permission': 'permission2', 'expected_result': {'perm1': False, 'perm2': True, 'perm3': False}}])
    def test_cases(request):
      admin_user.set_permission_to_userA(request.param.get('permission'))
      return request.param
    
    def test_userA_permissions(test_cases):
      login_with_userA()
      assert drive.find_element_by_xpath('//div[@id="permission1"]') is test_cases.get('expected_result').get('perm1')
      assert drive.find_element_by_xpath('//div[@id="permission2"]') is test_cases.get('expected_result').get('perm2')
      assert drive.find_element_by_xpath('//div[@id="permission3"]') is test_cases.get('expected_result').get('perm3')
    

    因此,您只有一个数据驱动的测试。

    【讨论】:

    • 如果我需要根据不同的权限自定义断言结果怎么办。无论如何,我可以指定要为每个测试用例传递的参数吗?像 userA_permission 一样,我需要验证 a、b、c。 userB_permission,我需要验证 d,e,f.
    • 在这种情况下,您可以使用列表而不是字典作为预期结果。或任何其他适合您需求的复杂对象。
    • 如果它对您不起作用,那么您可能对每个权限都有单独的测试,但在测试中首先调用 userA 的设置权限(不使用固定装置):` def set_permission_to_userA(permission) : login_with_admin() set_permission(permission) def test_premission_one(): set_permission_to_userA(permission1) login_with_userA() verifys_here() def test_premission_two(): set_permission_to_userA(permission2) login_with_userA() verifys_here() `
    • 明白了,谢谢。我只是将单独的测试用例作为方法
    猜你喜欢
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多