简体   繁体   English

如何让 httpretty 在测试期间停止打印异常?

[英]How can I get httpretty to stop printing exceptions during testing?

I have a test which simulates a request from a remote server which does not exist:我有一个模拟来自不存在的远程服务器的请求的测试:

    @httpretty.activate
    def test_no_such_host(self):

        def no_such_host(request, uri, headers):
            raise requests.ConnectionError()

        httpretty.register_uri(
                'GET',
                EXAMPLE_WEBFINGER_URL,
                status=200,
                headers = {
                    'Content-Type': 'application/jrd+json',
                    },
                body = no_such_host,
                )

        webfinger = get_webfinger(
                EXAMPLE_USERNAME,
                EXAMPLE_HOSTNAME,
                )

        self.assertEqual(
                webfinger.url,
                None,
                )

get_webfinger does in fact catch ConnectionError . get_webfinger实际上确实捕获了ConnectionError When it runs, the test passes-- but it also reports the ConnectionError exception as coming from an httpretty thread:当它运行时,测试通过了——但它也报告了来自 httpretty 线程的ConnectionError异常:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/marnanel/alpha/lib/python3.6/site-packages/httpretty/core.py", line 781, in fill_filekind
    status, headers, self.body = self.callable_body(self.request, self.info.full_url(), headers)
  File "/home/marnanel/proj/kepi/kepi/sombrero_sendpub/tests/test_webfinger.py", line 183, in no_such_host
    raise requests.ConnectionError()
requests.exceptions.ConnectionError

.
----------------------------------------------------------------------
Ran 1 test in 0.117s

OK
Destroying test database for alias 'default'...

There is no threading in the unit test or in the code being tested.单元测试或正在测试的代码中没有线程。 This is one of many similar tests.这是许多类似测试之一。 The ones which don't involve exceptions all run perfectly.那些不涉及异常的都运行得很好。

How can I get it to stop printing the exception?我怎样才能让它停止打印异常?

HTTPretty uses a thread to simulate socket timeouts but are not handling exceptions correctly, see issue #334 . HTTPretty 使用线程来模拟套接字超时,但没有正确处理异常,请参阅问题 #334 The latter proposes a method for handling exceptions, but that hasn't been picked up by the maintainers (yet).后者提出了一种处理异常的方法,但维护者(目前)还没有采纳。

However, the message you see is printed by the default threading.excepthook() implementation .但是,您看到的消息是由默认的threading.excepthook()实现打印的。 You can set your own hook;您可以设置自己的钩子; a no-op lambda would silence the errors:无操作 lambda 将使错误静音:

threading.excepthook = lambda a: None

You could use a context manager to disable the hook temporarily:您可以使用上下文管理器暂时禁用钩子:

import threading
from contextlib import contextmanager

@contextmanager
def suppress_thread_exceptions():
    orig = threading.excepthook
    threading.excepthook = lambda a: None
    try:
        yield
    finally:
        threading.excepthook = orig

then use the above in your tests:然后在您的测试中使用上述内容:

with suppress_thread_exceptions():
    # use HTTPretty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让 locust 根据来自另一个 API 的响应停止负载测试? - How can I get locust to stop load testing based on response from another API? 如何在测试期间让Travis-CI识别并打开外部文件 - How can I get Travis-CI to recognize and open external files during testing 在for循环中打印时,如何反转列表结果? - How can I reverse the list outcome while printing during a for loop? pytest:如何在单元测试期间强制提​​高异常? - pytest: How to force raising Exceptions during unit-testing? 如何单击按钮停止打印数字 - How can I stop printing numbers clicking on a pushbutton 未使用HTTPretty请求如何声明URL - How to assert a URL was not requested with HTTPretty 所以,基本上我的代码在打印我希望它打印的语句后打印 None 。 我怎样才能阻止这个 None 打印 - So, basically my code is printing None after printing the statement I want it to print. How can I stop this None from printing 如何让Python的unittest不捕获异常? - How can I get Python's unittest to not catch exceptions? Python在捕获异常时,如何获取行号? - Python when catching exceptions, how I can get the line number? 如何在 python 异常中取出错误行文本? - How can i get out the error line text in python exceptions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM