What is the use of __traceback_hide__

I saw this line of code in some functions

__traceback_hide__ = True 

What is he doing? It looks like he's trying to suppress error tracing. In what situations should the trace be hidden?

+5
source share
4 answers

__tracebackhide__can be set to hide the function from the trace when using PyTest. __traceback_hide__seems to be used in the Python Paste package for the same purpose.

This is what paste.exceptions.collector documentation says :

If set and true, this means that the frame should be hidden from the reduced traces. Thus, you can hide some of the complexity of a larger structure and allow the user to focus on their own mistakes.

"", . "", , "reset". , , "_and_this" (, "before_and_this" ).

, formatters , , , .

PyTest __tracebackhide__:

, , pytest.fail . , __tracebackhide__ - .

, , , , , .

+6

, - (Sentry, werkzeug, Paste, Django), , .

, , , , Paste , :

, , . , .

"", . "", , "reset". , , "_and_this" (, "before_and_this" ).

, formatters , , , .

, Python .

+3

Googling "python __traceback_hide__", , , , , .

+1
source

Hiding the trace may give you a more understandable test result.

Try to verify that the /runningweb API endpoint returns a JSON response {"running": true}:

import pytest
import json

def test_running(client):
    action_response = client.get('/running')
    assert parse_as_json(action_response) == {'running': True}

def parse_as_json(response):
    __tracebackhide__ = True  # <---- Point of interest
    try:
        return json.loads(response.data)
    except json.decoder.JSONDecodeError:
        pass
    pytest.fail(f'Expected JSON, but got {response.data}')

If the test fails (because the JSON is distorted), then the error will be displayed as

__________________________ test_running _________________________

client = <FlaskClient <Flask 'webapi'>>

    def test_running(client):
        action_res = client.get('/running')
>       assert parse_as_json(action_res) == {'running': True}
E       Failed: Expected JSON, but got b'ok'

webapi_test.py:22: Failed
=============== 1 failed, 1 passed in 0.15 seconds ===============

whereas without a __tracebackhide__ = Trueconclusion there will be

__________________________ test_running _________________________

client = <FlaskClient <Flask 'webapi'>>

    def test_running(client):
        action_res = client.get('/running')
>       assert parse_as_json(action_res) == {'running': True}

webapi_test.py:22: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

client = <FlaskClient <Flask 'webapi'>>

    def test_running(client):
        action_res = client.get('/running')
>       assert parse_as_json(action_res) == {'running': True}
E       Failed: Expected JSON, but got b'ok'

webapi_test.py:22: Failed
=============== 1 failed, 1 passed in 0.17 seconds ===============
0
source

Source: https://habr.com/ru/post/1653857/


All Articles