PyTest参数化装置?如何将一个大型测试函数拆分为几个

2024-10-01 05:03:12 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有这个代码:

import create_account2
import functions as f

#Import create_account2
@pytest.fixture(scope="module", autouse=True)
def create_account():
    create = create_account2.hook
    return create

@pytest.mark.usertest
class CreateAccountLoginCUpdateDetailsAndVerify

    @pytest.mark.parametrize('country', ['US', 'UK', "CA"])
    def test_CreateAccountUpdateDetailsAndVerify(self, create_account, country):

        ##Create account
        data = create_account(country)

        ##Login with account
        f.go_to_site(country)
        f.user_login(data['Mail'], data['Password'])
        assert "buttonLogOut" in f.get_driver().page_source, "No logout button so login failed"

        ##Get the original object, before updates..
        OriginalCustomerObject = f.GetDetails(data)

        f.update_details(data)  

        UpdatedCustomerObject = f.GetDetails(data)

        ##Compare objects
        f.CompareData(OriginalCustomerObject, UpdatedCustomerObject)

        ##Quit
        f.quit()    

因此,它所做的是使用Selenium在美国/英国/CA网站上创建一个帐户,从API获取客户对象,通过Selenium更新客户详细信息(地址、电话等),然后检索另一个客户对象,并比较原始和更新的客户对象,以确保通过该网站更新用户详细信息确实有效

所以这一切都很好。问题是,我不得不将帐户创建、帐户更新和两个对象的验证放在同一个测试中。使用country=[US,UK,CA]参数化函数似乎是个好主意,因为我不必重复代码。但我不能用夹具,对吗?您似乎不能用这种方式参数化装置

因此,理想情况下,账户创建、账户细节更新和两个对象不同的验证将是三个不同的测试?问题只是我如何正确地传递数据。从我的初学者对PyTest的理解来看,这应该通过固定装置来完成,但在这种情况下,这似乎不起作用

那么我应该进行三次测试吗?TestUS,TestCA,TestUK


Tags: 对象代码importdata客户pytestdefcreate
1条回答
网友
1楼 · 发布于 2024-10-01 05:03:12

如果我理解错了你的问题,我向你道歉

就我的理解而言,不能像常规函数那样将值传递给pytest fixture。话虽如此,您可以使用pytest fixture factory模式来实现您想要的实现

https://docs.pytest.org/en/latest/fixture.html#factories-as-fixtures

import pytest

@pytest.fixture
def create_account():
    def _create_account(country):
        return country

    return _create_account


class TestCreateAccountLoginCUpdateDetailsAndVerify:
    @pytest.mark.parametrize('country', ['US', 'UK', 'CA'])
    def test_create_account_update_details_and_verify(self, create_account, country):
        data = create_account(country)
        print(data)

# output
================================================== 3 passed in 0.01s ==================================================
collected 3 items
.US
.UK
.CA

相关问题 更多 >