python如何写测试程序,Python - 使用pytest来测试用子类编写的测试方法

在使用 Pytest 进行测试时,如果测试类从包含初始化构造器(__init__)的超类继承,会遇到无法收集测试类的错误。该文探讨了这个问题,并提出了通过使用 fixtures 的 autouse 特性来执行预初始化步骤的解决方案,允许在不违反 Pytest 对类层级限制的情况下进行测试。
摘要由CSDN通过智能技术生成

I am a novice to pytest. I have a scenario wherein i wanted to test some test methods written in a subclass.

Assume that the following is my code structure

class Superclass:

def __init__(self, a):

self.a = a

def dummy_print():

print("This is a dummy function")

class TestSubClass(Superclass):

def test_1_eq_1():

assert 1 == 1

Upon executing the following command

py.test -s -v test_filename.py

I get the following error messgae:

cannot collect test class 'Test_Super' because it has a init constructor

The same is mentioned in the pytest documentation as well.

Is there a workaround for this?

I need the superclass' __init__() method because all my test files would need to inherit from the super class.

解决方案

Pytest is different beast than, say unittests. It prohibits class hierarchies, which you can see in the warning message.

If you need some pre-initialization steps, do them using fixtures:

@pytest.fixture(autouse=True)

def pre_run_initialization():

# do before test

yield

# do after test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值