【问题标题】:Pytest setup generate product for all testPytest 设置为所有测试生成产品
【发布时间】:2020-12-16 20:24:10
【问题描述】:

我正在开发 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']

【问题讨论】:

标签: python unit-testing automated-tests pytest


【解决方案1】:

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

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

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

class TestCreateOrdersSmoke:

    @pytest.fixture(scope="class")

第二种方式:“class”作用域的fixture可以在class之外,所以你可以在不同的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')
    

第三种方法:你可以通过标记@pytest.mark.usefixtrures('fixture_name')来用fixture注解class,并且你不需要将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,请注意使用它。

【讨论】:

  • @test_junkie123 希望对您有所帮助。如果夹具在类内,则无需使用“会话”范围夹具,“类”范围将足够且更清晰。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多