Skip to content

Commit

Permalink
Fix pprint of combined enum flags
Browse files Browse the repository at this point in the history
  • Loading branch information
Zac-HD committed Aug 5, 2023
1 parent 54fab2c commit 5a4a591
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 4 deletions.
4 changes: 4 additions & 0 deletions hypothesis-python/RELEASE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
RELEASE_TYPE: patch

This patch fixes pretty-printing of combinations of :class:`enum.Flag`
values, which was previously an error (:issue:`3709`).
7 changes: 6 additions & 1 deletion hypothesis-python/src/hypothesis/vendor/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ def _repr_pretty_(self, p, cycle):
import warnings
from collections import defaultdict, deque
from contextlib import contextmanager
from enum import Flag
from io import StringIO
from math import copysign, isnan

Expand Down Expand Up @@ -801,7 +802,11 @@ def _repr_dataframe(obj, p, cycle): # pragma: no cover


def _repr_enum(obj, p, cycle):
p.text(type(obj).__name__ + "." + obj.name)
tname = type(obj).__name__
if isinstance(obj, Flag):
p.text(" | ".join(f"{tname}.{x.name}" for x in type(obj) if x & obj == x))
else:
p.text(f"{tname}.{obj.name}")


for_type_by_name("collections", "defaultdict", _defaultdict_pprint)
Expand Down
41 changes: 38 additions & 3 deletions hypothesis-python/tests/cover/test_pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
import re
import warnings
from collections import Counter, OrderedDict, defaultdict, deque
from enum import Enum
from enum import Enum, Flag

import pytest

Expand Down Expand Up @@ -628,5 +628,40 @@ class AnEnum(Enum):
SOME_MEMBER = 1


def test_pretty_prints_enums_as_code():
assert pretty.pretty(AnEnum.SOME_MEMBER) == "AnEnum.SOME_MEMBER"
class Options(Flag):
A = 1
B = 2
C = 4


class EvilReprOptions(Flag):
A = 1
B = 2

def __repr__(self):
return "can't parse this nonsense"


class LyingReprOptions(Flag):
A = 1
B = 2

def __repr__(self):
return "LyingReprOptions.A|B|C"


@pytest.mark.parametrize(
"rep",
[
"AnEnum.SOME_MEMBER",
"Options.A",
"Options.A | Options.B",
"Options.A | Options.B | Options.C",
"EvilReprOptions.A",
"LyingReprOptions.A",
"EvilReprOptions.A | EvilReprOptions.B",
"LyingReprOptions.A | LyingReprOptions.B",
],
)
def test_pretty_prints_enums_as_code(rep):
assert pretty.pretty(eval(rep)) == rep

0 comments on commit 5a4a591

Please sign in to comment.