在py.test中捕获异常并引发错误时抑制第一个异常

时间:2018-10-18 19:23:21

标签: python exception pytest

我有一个简单的py.test,它尝试访问某个域,如果无法访问该域,则会失败。我不想看到整个urllib堆栈跟踪。

例如:

import py.test
import requests
import sys

def test_failure():
    url = 'https://www.nosuchdomain.com'
    try:
        r = requests.post(url=url, timeout=1)
    except Exception as ex:
        print("Can't reach "+url,file=sys.stdout)
        assert False

但是我得到的输出太长了!

[Dance ~/tests 15:21:57]$ py.test connect_test.py
======================================= test session starts =======================================
platform darwin -- Python 3.6.0, pytest-3.0.5, py-1.4.32, pluggy-0.4.0
rootdir: /Users/simsong/tests, inifile:
collected 1 items

connect_test.py F

============================================ FAILURES =============================================
__________________________________________ test_failure ___________________________________________

self = <requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x10d672c50>

    def _new_conn(self):
        """ Establish a socket connection and set nodelay settings on it.

            :return: New socket connection.
            """
        extra_kw = {}
        if self.source_address:
            extra_kw['source_address'] = self.source_address

        if self.socket_options:
            extra_kw['socket_options'] = self.socket_options

        try:
            conn = connection.create_connection(
>               (self.host, self.port), self.timeout, **extra_kw)

../anaconda3/lib/python3.6/site-packages/requests/packages/urllib3/connection.py:138:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
... 1000 lines removed ...
During handling of the above exception, another exception occurred:

    def test_failure():
        url = 'https://www.nosuchdomain.com'
        try:
            r = requests.post(url=url, timeout=1)
        except Exception as ex:
            print("Can't reach "+url,file=sys.stdout)
>           assert False
E           assert False

connect_test.py:11: AssertionError
-------------------------------------- Captured stdout call ---------------------------------------
Can't reach https://www.nosuchdomain.com
==================================== 1 failed in 1.63 seconds =====================================
[Dance ~/tests 15:22:01]$

如何消除所有不需要的输出?

0 个答案:

没有答案