Skip to content

Commit 6f822dc

Browse files
Sh4pehynek
andauthored
Make sure locals_max_{length,string} work as expected in case they are None (hynek#675)
* Make sure locals_max_{length,string} work as expected in case they are None * Update tests/test_tracebacks.py --------- Co-authored-by: Hynek Schlawack <hs@ox.cx>
1 parent e51f347 commit 6f822dc

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

src/structlog/tracebacks.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -382,10 +382,10 @@ def __init__(
382382
max_frames: int = MAX_FRAMES,
383383
use_rich: bool = True,
384384
) -> None:
385-
if locals_max_length < 0:
385+
if locals_max_length is not None and locals_max_length < 0:
386386
msg = f'"locals_max_length" must be >= 0: {locals_max_length}'
387387
raise ValueError(msg)
388-
if locals_max_string < 0:
388+
if locals_max_string is not None and locals_max_string < 0:
389389
msg = f'"locals_max_string" must be >= 0: {locals_max_string}'
390390
raise ValueError(msg)
391391
if max_frames < 2:

tests/test_tracebacks.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,46 @@ def bar(n):
531531
]
532532

533533

534+
@pytest.mark.parametrize(
535+
("kwargs", "local_variable"),
536+
[
537+
(
538+
{"locals_max_string": None},
539+
"x" * (tracebacks.LOCALS_MAX_STRING + 10),
540+
),
541+
(
542+
{"locals_max_length": None},
543+
list(range(tracebacks.LOCALS_MAX_LENGTH + 10)),
544+
),
545+
],
546+
)
547+
def test_exception_dict_transformer_locals_max_accept_none_argument(
548+
kwargs, local_variable
549+
):
550+
"""
551+
ExceptionDictTransformer works when either locals_max_string or
552+
locals_max_length is set to None.
553+
"""
554+
555+
try:
556+
my_local = local_variable
557+
1 / 0
558+
except Exception as e:
559+
format_json = tracebacks.ExceptionDictTransformer(
560+
show_locals=True, **kwargs
561+
)
562+
result = format_json((type(e), e, e.__traceback__))
563+
564+
_ = my_local
565+
566+
assert len(result) == 1
567+
assert len(result[0]["frames"]) == 1
568+
569+
frame = result[0]["frames"][0]
570+
571+
assert frame["locals"]["my_local"].strip("'") == str(local_variable)
572+
573+
534574
def test_json_traceback():
535575
"""
536576
Tracebacks are formatted to JSON with all information.

0 commit comments

Comments
 (0)