Skip to content

Commit

Permalink
test: capture stderr in subprocess test
Browse files Browse the repository at this point in the history
  • Loading branch information
XuehaiPan committed Nov 8, 2024
1 parent cb4c04d commit 50188a0
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 24 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ repos:
hooks:
- id: clang-format
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.2
rev: v0.7.3
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ ban-relative-imports = "all"

[tool.pytest.ini_options]
verbosity_assertions = 3
faulthandler_timeout = 60
filterwarnings = [
"error",
"always",
Expand Down
60 changes: 37 additions & 23 deletions tests/test_treespec.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import contextlib
import itertools
import pickle
import platform
import re
import subprocess
import sys
Expand Down Expand Up @@ -458,37 +459,50 @@ def test_treespec_pickle_missing_registration():
optree.register_pytree_node(
Foo,
lambda foo: ((foo.x, foo.y), None),
lambda _, children: Foo(children[0], children[1]),
lambda _, children: Foo(*children),
namespace='foo',
)

treespec = optree.tree_structure(Foo(0, 1), namespace='foo')
serialized = pickle.dumps(treespec)

error = subprocess.check_output(
[
sys.executable,
'-c',
textwrap.dedent(
f"""
import pickle
import sys
try:
treespec = pickle.loads({serialized!r})
except Exception as ex:
print(ex)
else:
sys.exit(1)
""",
).strip(),
],
stderr=subprocess.STDOUT,
text=True,
).strip()
try:
output = subprocess.run(
[
sys.executable,
'-c',
textwrap.dedent(
f"""
import pickle
import sys
try:
treespec = pickle.loads({serialized!r})
except Exception as ex:
print(ex)
else:
print('No exception was raised.', file=sys.stderr)
sys.exit(1)
""",
).strip(),
],
capture_output=True,
check=True,
text=True,
)
message = output.stdout.strip()
except subprocess.CalledProcessError as ex:
if not (
sys.version_info[:2] == (3, 11)
and platform.system() == 'Windows'
and 'time.struct_time' in ex.stderr.lower()
):
raise RuntimeError(ex.stderr) from ex
message = ex.stdout.strip()

assert re.match(
r"^Unknown custom type in pickled PyTreeSpec: <class '.*'> in namespace 'foo'\.$",
string=error,
string=message,
)

optree.unregister_pytree_node(Foo, namespace='foo')
Expand Down

0 comments on commit 50188a0

Please sign in to comment.