Skip to content

Commit a6f4b9e

Browse files
committed
Add extensive tests to read from pipes
1 parent a2430de commit a6f4b9e

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

src/xopen/__init__.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -721,7 +721,11 @@ def _filepath_from_path_or_filelike(fileorpath: FileOrPath) -> str:
721721
except TypeError:
722722
pass
723723
if hasattr(fileorpath, "name"):
724-
return fileorpath.name
724+
name = fileorpath.name
725+
if isinstance(name, str):
726+
return name
727+
elif isinstance(name, bytes):
728+
return name.decode()
725729
return ""
726730

727731

@@ -831,7 +835,7 @@ def xopen( # noqa: C901
831835
if filename == "-":
832836
filename = _open_stdin_or_out(binary_mode)
833837
elif _file_is_a_socket_or_pipe(filename):
834-
filename = open(filename, binary_mode)
838+
filename = open(filename, binary_mode) # type: ignore
835839

836840
if format not in (None, "gz", "xz", "bz2", "zst"):
837841
raise ValueError(

tests/test_xopen.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Tests for the xopen.xopen function
33
"""
44
import bz2
5+
import subprocess
56
import sys
67
import tempfile
78
from contextlib import contextmanager
@@ -656,3 +657,32 @@ def test_xopen_stdout(monkeypatch):
656657
raw.seek(0)
657658
data = raw.read()
658659
assert data == "Hello world!"
660+
661+
662+
@pytest.mark.parametrize("threads", (0, 1))
663+
def test_xopen_read_from_pipe(ext, threads):
664+
if ext == ".zst" and zstandard is None:
665+
return
666+
in_file = TEST_DIR / f"file.txt{ext}"
667+
process = subprocess.Popen(("cat", str(in_file)), stdout=subprocess.PIPE)
668+
with xopen(process.stdout, "rt", threads=threads) as f:
669+
data = f.read()
670+
process.wait()
671+
assert data == CONTENT
672+
673+
674+
@pytest.mark.parametrize("threads", (0, 1))
675+
def test_xopen_write_to_pipe(threads, ext):
676+
if ext == ".zst" and zstandard is None:
677+
return
678+
format = ext.lstrip(".")
679+
if format == "":
680+
format = None
681+
process = subprocess.Popen(("cat",), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
682+
with xopen(process.stdin, "wt", threads=threads, format=format) as f:
683+
f.write(CONTENT)
684+
process.stdin.close()
685+
with xopen(process.stdout, "rt", threads=threads) as f:
686+
data = f.read()
687+
process.wait()
688+
assert data == CONTENT

0 commit comments

Comments
 (0)