Pytest API自动化:为类内用例复用同一DB随机产品及做法校验
Pytest测试类内复用同一随机产品实例的实现与最佳实践校验
核心提问背景
- 正在开发Pytest API自动化项目,需要从数据库获取随机产品,要求同一个测试类下的所有用例复用同一个随机产品实例
- 最初采用类级setup实现时,单独执行任意一个测试用例都会生成全新的随机产品,无法满足复用要求
- 初始实现代码如下:
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']
当前实现状态
已按照方案采用session作用域的fixture实现了随机产品复用,运行效果符合预期,需要确认该实现是否符合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']
实现存在的优化空间
- 作用域范围不匹配需求
目前使用scope="session"的fixture,只要测试会话启动,不管是否执行当前测试类,都会提前初始化DAO对象、拉取随机产品。而需求仅为当前TestCreateOrdersSmoke类下的用例共享随机产品,session作用域范围过大:- 后续其他测试类不需要该随机产品时,会产生无意义的数据库查询开销
- 测试执行顺序变动时,其他模块提前触发session级fixture初始化,可能打乱原有测试数据准备逻辑
- fixture定义位置灵活性不足
把fixture直接写在测试类内部,会导致该fixture只能被当前类的用例引用,后续其他测试类需要复用DAO对象、随机产品逻辑时,无法跨类调用 - 返回字典的可维护性较差
目前fixture以字典形式返回多个对象,取值时依赖字符串键名,一旦键名拼写错误无法在静态代码检查阶段发现,只能运行时抛出KeyError,长期维护成本较高
符合Pytest最佳实践的调整方向
- 将fixture作用域从
session调整为class级(scope="class"):fixture会在当前测试类的第一个用例执行前初始化,整个类的所有用例共享实例,类执行结束后自动释放,完全匹配需求范围 - 把通用DAO、Helper实例的fixture抽离到公共的
conftest.py文件中,不同测试类可以直接引用,避免重复初始化 - 将随机产品逻辑单独拆为独立fixture,与DAO、Helper的fixture解耦,不要把所有对象打包到单个大的
helpers字典中 - 多对象返回的fixture可以用dataclass或简单的普通对象代替字典,减少取值时的拼写错误
参考实现结构:
# 公共fixture放置在项目根目录的conftest.py中 @pytest.fixture(scope="session") def products_db(): return ProductsDao() @pytest.fixture(scope="session") def orders_db(): return OrdersDao() @pytest.fixture(scope="session") def orders_helper(): return OrdersHelper() # 类级作用域的随机产品fixture,当前测试类所有用例共享 @pytest.fixture(scope="class") def shared_random_product(products_db): return products_db.select_random_product_from_db()# 测试类中直接引用fixture即可 class TestCreateOrdersSmoke: @pytest.mark.tcid48 def test_create_order_as_guest(self, shared_random_product): random_product_id = shared_random_product[0]['ID'] @pytest.mark.tcid88 def test_create_order_with_new_user(self, shared_random_product): random_product_id = shared_random_product[0]['ID']
内容的提问来源于stack exchange,提问作者test_junkie123
相关产品推荐
相关产品推荐

