Skip to content

Fix serialization of Enum and Path #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/pytest_subtests/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from contextlib import contextmanager
from contextlib import ExitStack
from contextlib import nullcontext
from enum import Enum
from pathlib import Path
from typing import Any
from typing import Callable
from typing import ContextManager
Expand Down Expand Up @@ -77,8 +79,14 @@ def sub_test_description(self) -> str:
def _to_json(self) -> dict:
data = super()._to_json()
del data["context"]

def serialize(inst: type, field: attr.Attribute, value: Any) -> Any:
if isinstance(value, (Enum, Path)):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should not special-case Enum and Path, seems subTest parameters are reported as::

  • The msg parameter is always converted to string using str().
  • The dict contents are converted to string using repr().

The example below uses a custom class to demonstrate that.

import unittest
from enum import StrEnum, auto, Enum


class MyEnum(Enum):
    A = 1
    B = 2

class C:
    def __str__(self):
        return "C:str"
    def __repr__(self):
        return "C:repr"


class MyUnitTest(unittest.TestCase):

    def test_enum_values(self):
        for value in (C(), MyEnum.B):
            with self.subTest(value, p=value):
                assert False

if __name__ == '__main__':
    unittest.main()
test_enum_values (__main__.MyUnitTest.test_enum_values) ...
  test_enum_values (__main__.MyUnitTest.test_enum_values) [C:str] (p=C:repr) ... FAIL
  test_enum_values (__main__.MyUnitTest.test_enum_values) [MyEnum.B] (p=<MyEnum.B: 2>) ... FAIL

Ideally, we should find a way to perform the same conversions (str for msg and repr for the rest) during serialization.

return str(value)
return value

data["_report_type"] = "SubTestReport"
data["_subtest.context"] = attr.asdict(self.context)
data["_subtest.context"] = attr.asdict(self.context, value_serializer=serialize)
return data

@classmethod
Expand Down
70 changes: 70 additions & 0 deletions tests/test_subtests.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,76 @@ def test_simple_terminal_verbose(
]
)

@pytest.mark.parametrize("runner", ["unittest", "pytest-normal", "pytest-xdist"])
def test_serialization(
self,
pytester: pytest.Pytester,
runner: Literal["unittest", "pytest-normal", "pytest-xdist"],
) -> None:
p = pytester.makepyfile(
"""
import sys
from unittest import TestCase, main
from pathlib import Path

if sys.version_info[:2] < (3, 11):
from enum import Enum

class MyEnum(str, Enum):
CUSTOM = "custom"

def __str__(self) -> str:
return self.value
else:
from enum import StrEnum

class MyEnum(StrEnum):
CUSTOM = "custom"

class T(TestCase):

def test_foo(self):
for i in range(5):
with self.subTest(msg=MyEnum.CUSTOM, i=i, p=Path("test")):
Comment on lines +301 to +304
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for being pedantic what happens if msg is dict of name to enum

Although i wouldn't expect people to use that people are always in for horrible surprises

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems to work - probably because attr.asdict() handles dicts per default by converting their elements: https://github.com/python-attrs/attrs/blob/a296a129c60f5c736165086621f03c10a4d14065/src/attr/_funcs.py#L104-L126

self.assertEqual(i % 2, 0)

if __name__ == '__main__':
main()
"""
)
suffix = ".test_foo" if IS_PY311 else ""
if runner == "unittest":
result = pytester.run(sys.executable, p)
result.stderr.fnmatch_lines(
[
f"FAIL: test_foo (__main__.T{suffix}) [[]custom[]] (i=1, p=*)",
"AssertionError: 1 != 0",
f"FAIL: test_foo (__main__.T{suffix}) [[]custom[]] (i=3, p=*)",
"AssertionError: 1 != 0",
"Ran 1 test in *",
"FAILED (failures=2)",
]
)
else:
if runner == "pytest-normal":
result = pytester.runpytest(p)
expected_lines = ["collected 1 item"]
else:
assert runner == "pytest-xdist"
pytest.importorskip("xdist")
result = pytester.runpytest(p, "-n1")
expected_lines = ["1 worker [1 item]"]
result.stdout.fnmatch_lines(
expected_lines
+ [
"* T.test_foo [[]custom[]] (i=1, p=*) *",
"E * AssertionError: 1 != 0",
"* T.test_foo [[]custom[]] (i=3, p=*) *",
"E * AssertionError: 1 != 0",
"* 2 failed, 1 passed, 3 subtests passed in *",
]
)

@pytest.mark.parametrize("runner", ["unittest", "pytest-normal", "pytest-xdist"])
def test_skip(
self,
Expand Down
Loading