Python Pytest似乎与单元测试中引发的异常不匹配 上下文
我正在尝试使用加密库进行pytest。在测试中,我使用故意损坏的身份验证标记对一些数据进行解密和身份验证。这样做会引发如下所示的“InvalidTag” 我正在使用声明pytest的异常:Python Pytest似乎与单元测试中引发的异常不匹配 上下文,python,unit-testing,exception,pytest,Python,Unit Testing,Exception,Pytest,我正在尝试使用加密库进行pytest。在测试中,我使用故意损坏的身份验证标记对一些数据进行解密和身份验证。这样做会引发如下所示的“InvalidTag” 我正在使用声明pytest的异常: with pytest.raises(Exception, match='a_string'): myfunc() 我的代码示例 这里真正重要的是函数test_decrypt()。目前,如果我使用前面的代码运行pytest,我会得到以下输出: > ▶ pytest > > ===
with pytest.raises(Exception, match='a_string'):
myfunc()
我的代码示例
这里真正重要的是函数test_decrypt()。目前,如果我使用前面的代码运行pytest,我会得到以下输出:
> ▶ pytest
>
> ============================================== test session starts ===============================================
> platform darwin -- Python 3.8.2, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
> rootdir: somewhere
> collected 2 items
>
> tests/test_pytest_exception.py .F [100%]
>
> ==================================================== FAILURES ====================================================
> __________________________________________________ test_decrypt __________________________________________________
>
> def test_decrypt():
> with pytest.raises(Exception, match='InvalidTag'):
> > decrypt()
>
> tests/test_pytest_exception.py:52:
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
> def decrypt():
> # encrypt
> encryptor = Cipher(
> algorithms.AES(key),
> modes.GCM(iv),
> backend=default_backend()
> ).encryptor()
> encryptor.authenticate_additional_data(aad)
> ct = encryptor.update(pt) + encryptor.finalize()
> tag = encryptor.tag
>
> # let us corrupt the tag
>
> corrupted_tag = bytes.fromhex("55555555555555555555555555555555")
>
> # decrypt
> decryptor = Cipher(
> algorithms.AES(key),
> modes.GCM(iv, corrupted_tag),
> backend=default_backend()
> ).decryptor()
> decryptor.authenticate_additional_data(aad)
>
> > return decryptor.update(ct) + decryptor.finalize()
>
> tests/test_pytest_exception.py:47:
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
> self = <cryptography.hazmat.primitives.ciphers.base._AEADCipherContext object at 0x10d2d53a0>
>
> def finalize(self):
> if self._ctx is None:
> raise AlreadyFinalized("Context was already finalized.")
> > data = self._ctx.finalize()
>
> ../../../.local/share/virtualenvs/a_virtual_env/lib/python3.8/site-packages/cryptography/hazmat/primitives/ciphers/base.py:198:
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
> self = <cryptography.hazmat.backends.openssl.ciphers._CipherContext object at 0x10d2d5040>
>
> def finalize(self):
> # OpenSSL 1.0.1 on Ubuntu 12.04 (and possibly other distributions)
> # appears to have a bug where you must make at least one call to update
> # even if you are only using authenticate_additional_data or the
> # GCM tag will be wrong. An (empty) call to update resolves this
> # and is harmless for all other versions of OpenSSL.
> if isinstance(self._mode, modes.GCM):
> self.update(b"")
>
> if (
> self._operation == self._DECRYPT and
> isinstance(self._mode, modes.ModeWithAuthenticationTag) and
> self.tag is None
> ):
> raise ValueError(
> "Authentication tag must be provided when decrypting."
> )
>
> buf = self._backend._ffi.new("unsigned char[]", self._block_size_bytes)
> outlen = self._backend._ffi.new("int *")
> res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
> if res == 0:
> errors = self._backend._consume_errors()
>
> if not errors and isinstance(self._mode, modes.GCM):
> > raise InvalidTag
> E cryptography.exceptions.InvalidTag
>
> ../../../.local/share/virtualenvs/a_virtual_env/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/ciphers.py:170: InvalidTag
>
> During handling of the above exception, another exception occurred:
>
> def test_decrypt():
> with pytest.raises(Exception, match='InvalidTag'):
> > decrypt()
> E AssertionError: Pattern 'InvalidTag' does not match ''
>
> tests/test_pytest_exception.py:52: AssertionError
> ============================================ short test summary info =============================================
> FAILED tests/test_pytest_exception.py::test_decrypt - AssertionError: Pattern 'InvalidTag' does not match ''
> ========================================== 1 failed, 1 passed in 0.12s ===========================================
>▶ 皮特斯特
>
>======================================================================测试会话开始===============================================
>平台darwin——Python 3.8.2、pytest-5.4.2、py-1.8.1、Plugy-0.13.1
>某处
>收集2项
>
>测试/test_pytest_exception.py.F[100%]
>
>===========================================================================故障====================================================
>_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu解密__________________________________________________
>
>def test_decrypt():
>使用pytest.raises(异常,match='InvalidTag'):
>>解密()
>
>测试/测试-测试-测试-异常。py:52:
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
>def decrypt():
>#加密
>加密器=密码(
>算法。AES(密钥),
>模式。GCM(iv),
>backend=默认值_backend()
>)。加密机()
>加密机。验证附加数据(aad)
>ct=encryptor.update(pt)+encryptor.finalize()
>tag=encryptor.tag
>
>#让我们破坏标签
>
>损坏的_标记=bytes.fromhex(“5555555555555555”)
>
>#解密
>解密器=密码(
>算法。AES(密钥),
>模式。GCM(iv,损坏的标签),
>backend=默认值_backend()
>)。解密程序()
>解密程序。验证附加数据(aad)
>
>>返回decryptor.update(ct)+decryptor.finalize()
>
>测试/test_pytest_异常。py:47:
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
>自我=
>
>def最终确定(自我):
>如果self.\u ctx为无:
>raise AlreadyFinalized(“上下文已最终确定”)
>>数据=self.\u ctx.finalize()
>
>../../...local/share/virtualenvs/a_virtual_env/lib/python3.8/site packages/cryptography/hazmat/primitives/ciphers/base.py:198:
> _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>
>自我=
>
>def最终确定(自我):
>#Ubuntu 12.04(可能还有其他发行版)上的OpenSSL 1.0.1
>#似乎有一个bug,您必须至少调用一次才能更新
>#即使您仅使用其他数据或
>#GCM标签将是错误的。对update的(空)调用可解决此问题
>#并且对所有其他版本的OpenSSL无害。
>如果存在(自模式,模式.GCM):
>自我更新(b“”)
>
>如果(
>self.\u操作==self.\u解密和
>isinstance(自模式、模式、带AuthenticationTag的模式)和
>self.tag是None
> ):
>升值误差(
>“解密时必须提供身份验证标记。”
> )
>
>buf=self.\u backend.\u ffi.new(“unsigned char[]”,self.\u block\u size\u bytes)
>outlen=self.\u后端.\u ffi.new(“int*”)
>res=自成体系。后端。自成体系。执行副总裁。密码最终。ex(自成体系。ctx,buf,outlen)
>如果res==0:
>errors=self.\u backend.\u consume\u errors()
>
>如果不是错误和不稳定(自模式、模式.GCM):
>>提出无效标签
>E.exceptions.InvalidTag
>
>../../...local/share/virtualenvs/a_virtual_env/lib/python3.8/site packages/cryptography/hazmat/backends/openssl/ciphers.py:170:InvalidTag
>
>在处理上述异常期间,发生了另一个异常:
>
>def test_decrypt():
>使用pytest.raises(异常,match='InvalidTag'):
>>解密()
>E AssertionError:模式“InvalidTag”不匹配“”
>
>tests/test_pytest_exception.py:52:AssertionError
>==============================================================================简短测试摘要信息=============================================
>失败的测试/test_pytest_异常。py::test_decrypt-断言错误:模式“InvalidTag”不匹配“”
>=============================================================1失败,1在0.12秒内通过===========================================
从这个输出来看,似乎引发了“InvalidTag”异常,但第二个异常也是出于我不理解的原因。
如果我不运行测试,但只运行函数decrypt(),则会得到以下输出:
> python3 tests/test_pytest_exception.py
> Traceback (most recent call last):
> File "tests/test_pytest_exception.py", line 54, in <module>
> decrypt()
> File "tests/test_pytest_exception.py", line 47, in decrypt
> return decryptor.update(ct) + decryptor.finalize()
> File "somewhere/a_virtual_env/lib/python3.8/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 198, in finalize
> data = self._ctx.finalize()
> File "somewhere/a_virtual_env/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/ciphers.py", line 170, in finalize
> raise InvalidTag
> cryptography.exceptions.InvalidTag
>python3测试/test\u pytest\u exception.py
>回溯(最近一次呼叫最后一次):
>文件“tests/test_pytest_exception.py”,第54行,在
>解密()
>文件“tests/test\u pytest\u exception.py”,第47行,解密
>返回decryptor.update(ct)+decryptor.finalize()
>文件“某处/a_virtual_env/lib/python3.8/site packages/cryptography/hazmat/primitives/ciphers/base.py”,第198行,最终确定
>data=self.\u ctx.finalize()
>文件“某处/a_virtual_env/lib/python3.8/site packages/cryptography/hazmat/backends/openssl/ciphers.py”,第170行,最后定稿
>提出无效标签
>cryptography.exceptions.InvalidTag
从这个输出中,我毫不怀疑会引发“InvalidTag”异常
问题:
我想用pytest检查单元测试中引发的“InvalidTag”异常,以通过测试。
A.
> python3 tests/test_pytest_exception.py
> Traceback (most recent call last):
> File "tests/test_pytest_exception.py", line 54, in <module>
> decrypt()
> File "tests/test_pytest_exception.py", line 47, in decrypt
> return decryptor.update(ct) + decryptor.finalize()
> File "somewhere/a_virtual_env/lib/python3.8/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 198, in finalize
> data = self._ctx.finalize()
> File "somewhere/a_virtual_env/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/ciphers.py", line 170, in finalize
> raise InvalidTag
> cryptography.exceptions.InvalidTag