首页 > 解决方案 > Pytest 设置为所有测试生成产品

问题描述

我正在研究 pytest API 自动化项目,我需要从数据库中获取随机产品。有没有一种方法可以让我在课堂上的所有测试用例中使用相同的随机产品?我正在使用设置类方法,但每次测试都会生成不同的产品。谢谢你。

class TestCreateOrdersSmoke:

@classmethod
def setup(cls):
    cls.products_db = ProductsDao()
    cls.orders_db = OrdersDao()
    cls.orders_helper = OrdersHelper()


@pytest.mark.tcid48
def test_create_order_as_guest(self):
    random_product = self.products_db.select_random_product_from_db()
    random_product_id = random_product[0]['ID']

更新:

所以我使用了一个像 seggested 这样的 pytest 会话夹具,它可以工作,所以谢谢!但我想确保这是正确的做法,所以这里是更新的代码:

class TestCreateOrdersSmoke:

@pytest.fixture(scope="session")
def helpers(self):
    products_db = ProductsDao()
    orders_db = OrdersDao()
    orders_helper = OrdersHelper()
    random_product = products_db.select_random_product_from_db()
    yield {'products_db':products_db,
           'orders_db':orders_db,
           'orders_helper':orders_helper,
           'random_product':random_product}

@pytest.mark.tcid48
def test_create_order_as_guest(self, helpers):
    random_product = helpers['random_product']
    random_product_id = random_product[0]['ID']

@pytest.mark.tcid88
def test_create_order_with_new_user(self, helpers):

    random_product = helpers['random_product']
    random_product_id = random_product[0]['ID']

标签: pythonunit-testingautomated-testspytest

解决方案


正如您所说,您需要类中所有方法的夹具,因此您可以使用“类”或“会话”范围夹具@pytest.fixture(scope="class")

这里有一些使用“类”或“会话”固定装置组织代码的方法。

第一种方式:具有"class"范围的夹具可以在 a 内class,示例与您对“会话”夹具所做的相同:

class TestCreateOrdersSmoke:

    @pytest.fixture(scope="class")

第二种方式:具有“类”范围的夹具可以在类之外,因此您可以在不同的类中使用它,例如:

import logging


@pytest.fixture(scope="class")
def h():
    logging.info('h')
 

class TestOne:
    def test_one_one(self, h):
        logging.info('test_one_one')

    def test_one_two(self, h):
        logging.info('test_one_two')


class TestTwo:
    def test_two_one(self, h):
        logging.info('test_two_one')
    

第三种方式:您可以class通过标记使用fixture进行注释,@pytest.mark.usefixtrures('fixture_name')您不需要将fixture传递给类的每个方法,它会自动传递。例子:

import logging


@pytest.fixture(scope="class")
def h():
    logging.info('h')
 

@pytest.mark.usefixtures('h')
class TestOne:
    def test_one_one(self):
        logging.info('test_one_one')

    def test_one_two(self):
        logging.info('test_one_two')

并且您可以尝试使用'autouse'fixture 参数,因此您不需要在方法内部传递fixture,或者用它注释类。例子:

@pytest.fixture(scope="class", autouse=True)
def h():
    logging.info('h')
 

class TestOne:
    def test_one_one(self):
        logging.info('test_one_one')

    def test_one_two(self):
        logging.info('test_one_two')

但我不建议使用autouse,请注意使用它。


推荐阅读