【发布时间】:2021-02-01 19:17:00
【问题描述】:
我有以下测试用例:
@pytest.mark.parametrize("init_resp", [True, False])
@pytest.mark.parametrize("mechanism", ["login", "plain"])
def test_byclient(self, auth_peeker_controller, client, mechanism, init_resp):
self._ehlo(client)
client.user = "goodlogin"
client.password = "goodpasswd"
auth_meth = getattr(client, "auth_" + mechanism)
try:
client.auth(mechanism, auth_meth, initial_response_ok=init_resp)
except SMTPAuthenticationError:
if (mechanism, init_resp) == ("login", False):
client.docmd("*")
pytest.xfail(reason="smtplib.SMTP.auth_login is buggy (bpo-27820)")
else:
raise
peeker = auth_peeker_controller.handler
assert isinstance(peeker, PeekerHandler)
assert peeker.login == b"goodlogin"
assert peeker.password == b"goodpasswd"
如您所见,对于一种参数组合(即("login", False)),测试预计会失败。
问题是,我仍然有 2 个异常弄乱了 pytest 的输出:
aiosmtpd\tests\test_smtp.py:1054: in test_byclient
client.auth(mechanism, auth_meth, initial_response_ok=init_resp)
C:\Python\36\lib\smtplib.py:642: in auth
raise SMTPAuthenticationError(code, resp)
E smtplib.SMTPAuthenticationError: (334, b'UGFzc3dvcmQA')
During handling of the above exception, another exception occurred:
aiosmtpd\tests\test_smtp.py:1058: in test_byclient
pytest.xfail(reason="smtplib.SMTP.auth_login is buggy (bpo-27820)")
E _pytest.outcomes.XFailed: smtplib.SMTP.auth_login is buggy (bpo-27820)
(pytest 使用--tb=short 运行)
是否可以抑制这些异常仅针对这一测试用例?
编辑 1
其实刚发完这个问题,我就把测试用例改成:
@pytest.mark.parametrize("init_resp", [True, False])
@pytest.mark.parametrize("mechanism", ["login", "plain"])
def test_byclient(self, auth_peeker_controller, client, mechanism, init_resp):
self._ehlo(client)
client.user = "goodlogin"
client.password = "goodpasswd"
auth_meth = getattr(client, "auth_" + mechanism)
if (mechanism, init_resp) == ("login", False):
with pytest.raises(SMTPAuthenticationError):
client.auth(mechanism, auth_meth, initial_response_ok=init_resp)
client.docmd("*")
pytest.xfail(reason="smtplib.SMTP.auth_login is buggy (bpo-27820)")
client.auth(mechanism, auth_meth, initial_response_ok=init_resp)
peeker = auth_peeker_controller.handler
assert isinstance(peeker, PeekerHandler)
assert peeker.login == b"goodlogin"
assert peeker.password == b"goodpasswd"
结果稍微好一点:
aiosmtpd\tests\test_smtp.py:1035: in test_byclient
pytest.xfail(reason="smtplib.SMTP.auth_login is buggy (bpo-27820)")
E _pytest.outcomes.XFailed: smtplib.SMTP.auth_login is buggy (bpo-27820)
不过,如果可能的话,我仍然希望抑制那个单一的“异常”。
上面的代码sn-p来自these lines on GitHub
【问题讨论】:
-
重构它,使其在完全不同的情况下不参数化。那么你的测试中也不需要条件逻辑。
-
@jonrsharpe 这不是“完全不同的情况”。所有情况都相似:我正在检查
smtplib.SMTP和aiosmtpd之间的交互是否符合标准。将来,将添加额外的 AUTH 机制(例如,DIGEST-MD5、CRAM-MD5 等)bpo-27820 有点我,所以我必须 XFAIL 那个。