From bc250f292319653fe89971d94c7505ab021a428c Mon Sep 17 00:00:00 2001 From: Kushal Dave Date: Thu, 19 Nov 2026 12:03:17 -0500 Subject: [PATCH 1/6] fix: support bytes paths in native operations --- README.md | 8 ++++ sshfs/spec.py | 36 +++++++++++++++--- tests/test_sshfs.py | 92 ++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 130 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 0a3921c..7e22b6e 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,14 @@ fs = SSHFileSystem( Note: you can also pass `client_keys` as an argument to `fsspec.open`. +To pass remote filenames as bytes, set +`sftp_client_kwargs={"path_encoding": None}` when creating the filesystem. +Use bytes for remote paths with this setting. Metadata, listing, removal, +uploads, copies, and checksums preserve these paths through SFTP. Checksums +of byte paths stream the file over SFTP, so they require transferring its data. +Inherited fsspec traversal and bulk methods such as `walk`, `find`, `glob`, +`get`, `put`, and `copy` still require string paths. + All operations and their descriptions are specified [here](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem). Here are a few example calls you can make, starting with `info()` which allows you to retrieve the metadata about given path; diff --git a/sshfs/spec.py b/sshfs/spec.py index 2338040..98f73b2 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -1,4 +1,5 @@ import asyncio +import hashlib import posixpath import shlex import stat @@ -128,6 +129,15 @@ def _get_kwargs_from_urls(urlpath): out.pop("protocol", None) return out + @classmethod + def _parent(cls, path): + path = cls._strip_protocol(path) + if isinstance(path, bytes): + return posixpath.dirname(path.rstrip(b"/")) or ( + b"/" if path.startswith(b"/") else b"" + ) + return super()._parent(path) + @wrap_exceptions async def _connect( self, @@ -215,9 +225,10 @@ async def _info(self, path, **kwargs): attributes = await channel.stat(path) info = self._decode_attributes(attributes) - path = path.rstrip("/") + separator = b"/" if isinstance(path, bytes) else "/" + path = path.rstrip(separator) if info["type"] == "directory": - path += "/" + path += separator info["name"] = path return info @@ -254,7 +265,9 @@ async def _put_file( **kwargs, ): rpath = self._strip_protocol(rpath) - await self._makedirs(self._parent(rpath), exist_ok=True) + parent = self._parent(rpath) + if parent: + await self._makedirs(parent, exist_ok=True) async with self._pool.get() as channel: await channel.put( lpath, @@ -280,6 +293,10 @@ async def _get_file( async def _cp_file(self, lpath, rpath, **kwargs): lpath = self._strip_protocol(lpath) rpath = self._strip_protocol(rpath) + if isinstance(lpath, bytes) or isinstance(rpath, bytes): + async with self._pool.get() as channel: + await channel.copy(lpath, rpath, follow_symlinks=True) + return cmd = f"cp {shlex.quote(lpath)} {shlex.quote(rpath)}" await self._execute(cmd) @@ -291,7 +308,7 @@ async def _ls(self, path, detail=True, **kwargs): infos = [] for file_attr in file_attrs: - if file_attr.filename in ["", ".", ".."]: + if file_attr.filename in ("", ".", "..", b"", b".", b".."): continue info = self._decode_attributes(file_attr.attrs) info["name"] = posixpath.join(path, file_attr.filename) @@ -369,6 +386,13 @@ async def _rm(self, path, recursive=False, **kwargs): @wrap_exceptions async def _checksum(self, path): path = self._strip_protocol(path) + if isinstance(path, bytes): + digest = hashlib.md5(usedforsecurity=False) + async with self._pool.get() as channel: + async with channel.open(path, "rb") as file: + while chunk := await file.read(READ_BLOCK_SIZE): + digest.update(chunk) + return digest.hexdigest() system = await self._get_system() if system == "Linux": command = "md5sum" @@ -422,7 +446,9 @@ async def _cat_file(self, path, **kwargs): async def _pipe_file(self, path, data, chunksize=50 * 2**20, **kwargs): """Asynchronously writes the given data to a remote file in chunks.""" path = self._strip_protocol(path) - await self._makedirs(self._parent(path), exist_ok=True) + parent = self._parent(path) + if parent: + await self._makedirs(parent, exist_ok=True) async with self._pool.get() as channel: async with channel.open(path, "wb") as f: diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index 494f523..cd913d5 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -11,7 +11,13 @@ import fsspec import pytest -from asyncssh.sftp import SFTPAttrs, SFTPClient, SFTPFailure, SFTPOpUnsupported +from asyncssh.sftp import ( + SFTPAttrs, + SFTPClient, + SFTPFailure, + SFTPName, + SFTPOpUnsupported, +) from sshfs import SSHFileSystem from sshfs.file import SSHFile @@ -76,6 +82,17 @@ def fs_hard_queue(ssh_server, user="user"): ) +@pytest.fixture +def fs_bytes(ssh_server): + return SSHFileSystem( + host=ssh_server.host, + port=ssh_server.port, + username="user", + client_keys=[USERS["user"]], + sftp_client_kwargs={"path_encoding": None}, + ) + + def strip_keys(info): for key in ["name", "time", "mtime", "atime"]: info.pop(key, None) @@ -156,6 +173,79 @@ def test_sftp_client_kwargs_path_encoding(ssh_server, tmp_path, user="user"): assert fs.cat_file(encoded + b"/data.txt") == b"data" +def test_bytes_metadata_and_remove(fs_bytes, tmp_path): + directory = tmp_path / "byte-paths" + directory.mkdir() + file = directory / "data.txt" + file.write_bytes(b"data") + path = os.fsencode(file) + parent = os.fsencode(directory) + assert fs_bytes.info(path)["name"] == path + assert fs_bytes.info(parent + b"/")["name"] == parent + b"/" + assert fs_bytes.exists(path) and fs_bytes.isfile(path) + assert fs_bytes.isdir(parent) and fs_bytes.size(path) == 4 + assert fs_bytes.modified(path).tzinfo == UTC + fs_bytes.rm(path) + assert not file.exists() + fs_bytes.rm(parent, recursive=True) + assert not directory.exists() + + +def test_bytes_relative_upload_and_download(fs_bytes, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + source = tmp_path / "local-source" + source.write_bytes(b"relative data") + fs_bytes.put_file(str(source), b"remote-file") + assert fs_bytes.info(b"remote-file")["name"] == b"remote-file" + destination = tmp_path / "local-copy" + fs_bytes.get_file(b"remote-file", str(destination)) + assert destination.read_bytes() == b"relative data" + fs_bytes.pipe_file(b"piped-file", b"piped data") + assert fs_bytes.cat_file(b"piped-file") == b"piped data" + + +@pytest.mark.parametrize("operation", ["put", "pipe", "copy", "checksum"]) +def test_bytes_file_operations(fs_bytes, tmp_path, operation): + local = tmp_path / "source" + data = b"file data" * 10000 + local.write_bytes(data) + destination = tmp_path / "nested" / "a file ' $name" + path = os.fsencode(destination) + if operation == "put": + fs_bytes.put_file(str(local), path) + elif operation == "pipe": + fs_bytes.pipe_file(path, data) + elif operation == "copy": + destination.parent.mkdir() + fs_bytes.cp_file(os.fsencode(local), path) + else: + assert ( + fs_bytes.checksum(os.fsencode(local)) + == hashlib.md5(data).hexdigest() + ) + return + assert destination.read_bytes() == data + + +@pytest.mark.parametrize("detail", [True, False]) +def test_bytes_ls_omits_dot_entries(fs_bytes, tmp_path, monkeypatch, detail): + (tmp_path / "data").write_bytes(b"data") + path = os.fsencode(tmp_path) + original = SFTPClient.readdir + + async def readdir(channel, path): + entries = await original(channel, path) + attrs = await channel.stat(path) + return entries + [ + SFTPName(name, attrs=attrs) for name in (b"", b".", b"..") + ] + + monkeypatch.setattr(SFTPClient, "readdir", readdir) + listing = fs_bytes.ls(path, detail=detail) + names = [info["name"] for info in listing] if detail else listing + assert names == [path + b"/data"] + + def test_info(fs, remote_dir, plain_remote_dir): fs.touch(remote_dir + "/a.txt") details = fs.info(remote_dir + "/a.txt") From 73a99adeb913813a83db18c6ff263a4ad71141ab Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 09:28:09 -0800 Subject: [PATCH 2/6] refactor: run cp and md5sum on the server for bytes paths Build the cp and md5sum commands as bytes, so bytes paths run on the server the same way str paths do, instead of copying over SFTP (through the client when the server lacks copy-data) or downloading the whole file to hash it. Command output is decoded with errors="replace": a file name in it that isn't valid UTF-8 otherwise makes asyncssh close the SSH connection. _parent now handles str and bytes with the same code and returns "/" for a top-level path, since "" is the home directory in sshfs. Also test relative str paths in put_file and pipe_file, which failed before this branch, and list the methods that accept bytes paths in the README. Co-Authored-By: Claude Opus 5.5 --- README.md | 14 +++++------ sshfs/spec.py | 59 +++++++++++++++++++++------------------------ tests/test_sshfs.py | 42 ++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 7e22b6e..2e8a2dc 100644 --- a/README.md +++ b/README.md @@ -58,13 +58,13 @@ fs = SSHFileSystem( Note: you can also pass `client_keys` as an argument to `fsspec.open`. -To pass remote filenames as bytes, set -`sftp_client_kwargs={"path_encoding": None}` when creating the filesystem. -Use bytes for remote paths with this setting. Metadata, listing, removal, -uploads, copies, and checksums preserve these paths through SFTP. Checksums -of byte paths stream the file over SFTP, so they require transferring its data. -Inherited fsspec traversal and bulk methods such as `walk`, `find`, `glob`, -`get`, `put`, and `copy` still require string paths. +For servers with file names that aren't valid UTF-8, set +`sftp_client_kwargs={"path_encoding": None}` and pass remote paths as bytes. +These methods accept bytes paths: `info`, `exists`, `isdir`, `isfile`, `size`, +`modified`, `ls`, `open`, `cat_file`, `pipe_file`, `put_file`, `get_file`, +`cp_file`, `mv`, `mkdir`, `makedirs`, `rm`, `rm_file`, and `checksum`. +fsspec's generic methods, such as `walk`, `find`, `glob`, `cat`, `pipe`, +`get`, `put`, and `copy`, need str paths. All operations and their descriptions are specified [here](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem). Here are a few example calls you can make, starting with `info()` which allows you to retrieve the metadata about given path; diff --git a/sshfs/spec.py b/sshfs/spec.py index 98f73b2..57a7c5d 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -1,7 +1,5 @@ import asyncio -import hashlib import posixpath -import shlex import stat import weakref from contextlib import AsyncExitStack, suppress @@ -35,6 +33,17 @@ _DEFAULT_MAX_SESSIONS = 10 +def _sep(path): + return b"/" if isinstance(path, bytes) else "/" + + +def _quote(path): + """Quote a str or bytes path for a POSIX shell, as bytes.""" + if isinstance(path, str): + path = path.encode() + return b"'" + path.replace(b"'", b"'\\''") + b"'" + + class SSHFileSystem(AsyncFileSystem): def __init__( self, @@ -132,11 +141,7 @@ def _get_kwargs_from_urls(urlpath): @classmethod def _parent(cls, path): path = cls._strip_protocol(path) - if isinstance(path, bytes): - return posixpath.dirname(path.rstrip(b"/")) or ( - b"/" if path.startswith(b"/") else b"" - ) - return super()._parent(path) + return posixpath.dirname(path.rstrip(_sep(path)) or path) @wrap_exceptions async def _connect( @@ -225,10 +230,10 @@ async def _info(self, path, **kwargs): attributes = await channel.stat(path) info = self._decode_attributes(attributes) - separator = b"/" if isinstance(path, bytes) else "/" - path = path.rstrip(separator) + sep = _sep(path) + path = path.rstrip(sep) if info["type"] == "directory": - path += separator + path += sep info["name"] = path return info @@ -265,8 +270,7 @@ async def _put_file( **kwargs, ): rpath = self._strip_protocol(rpath) - parent = self._parent(rpath) - if parent: + if parent := self._parent(rpath): await self._makedirs(parent, exist_ok=True) async with self._pool.get() as channel: await channel.put( @@ -293,12 +297,7 @@ async def _get_file( async def _cp_file(self, lpath, rpath, **kwargs): lpath = self._strip_protocol(lpath) rpath = self._strip_protocol(rpath) - if isinstance(lpath, bytes) or isinstance(rpath, bytes): - async with self._pool.get() as channel: - await channel.copy(lpath, rpath, follow_symlinks=True) - return - cmd = f"cp {shlex.quote(lpath)} {shlex.quote(rpath)}" - await self._execute(cmd) + await self._execute_with_paths(b"cp %s %s", lpath, rpath) @wrap_exceptions async def _ls(self, path, detail=True, **kwargs): @@ -386,25 +385,17 @@ async def _rm(self, path, recursive=False, **kwargs): @wrap_exceptions async def _checksum(self, path): path = self._strip_protocol(path) - if isinstance(path, bytes): - digest = hashlib.md5(usedforsecurity=False) - async with self._pool.get() as channel: - async with channel.open(path, "rb") as file: - while chunk := await file.read(READ_BLOCK_SIZE): - digest.update(chunk) - return digest.hexdigest() system = await self._get_system() if system == "Linux": - command = "md5sum" + command = b"md5sum %s" part = 0 elif system == "Darwin": - command = "md5" + command = b"md5 %s" part = -1 else: raise ValueError(f"{system!r} doesn't support checksum operation") - cmd = f"{command} {shlex.quote(path)}" - result = await self._execute(cmd) + result = await self._execute_with_paths(command, path) parts = result.stdout.strip().split() assert len(parts) >= 1 @@ -430,6 +421,13 @@ async def _execute(self, *args, **kwargs): execute = sync_wrapper(_execute) + async def _execute_with_paths(self, command, *paths): + """Execute a shell command with str or bytes paths quoted into it.""" + command %= tuple(map(_quote, paths)) + # Output can include file names that aren't valid UTF-8, and + # failing to decode it strictly closes the SSH connection. + return await self._execute(command, errors="replace") + def _open(self, path, *args, **kwargs): path = self._strip_protocol(path) return SSHFile(self, path, *args, **kwargs) @@ -446,8 +444,7 @@ async def _cat_file(self, path, **kwargs): async def _pipe_file(self, path, data, chunksize=50 * 2**20, **kwargs): """Asynchronously writes the given data to a remote file in chunks.""" path = self._strip_protocol(path) - parent = self._parent(path) - if parent: + if parent := self._parent(path): await self._makedirs(parent, exist_ok=True) async with self._pool.get() as channel: diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index cd913d5..86fa333 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -191,6 +191,48 @@ def test_bytes_metadata_and_remove(fs_bytes, tmp_path): assert not directory.exists() +@pytest.mark.parametrize( + "path, parent", + [ + ("ssh://host/a/b", "/a"), + ("/a", "/"), + ("/", "/"), + ("a/b", "a"), + ("a", ""), + (b"/a/b/", b"/a"), + (b"/a", b"/"), + (b"/", b"/"), + (b"a/b", b"a"), + (b"a", b""), + ], +) +def test_parent(path, parent): + # "" is the home directory, so the parent of a top-level path is "/" + assert SSHFileSystem._parent(path) == parent + + +def test_relative_put_and_pipe(fs, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + source = tmp_path / "local-source" + source.write_bytes(b"relative data") + fs.put_file(str(source), "remote-file") + assert (tmp_path / "remote-file").read_bytes() == b"relative data" + fs.pipe_file("piped-file", b"piped data") + assert (tmp_path / "piped-file").read_bytes() == b"piped data" + + +@pytest.mark.parametrize("operation", ["copy", "checksum"]) +def test_bytes_shell_error_with_non_utf8_name(fs_bytes, tmp_path, operation): + path = os.fsencode(tmp_path) + b"/missing-caf\xe9" + with pytest.raises(FileNotFoundError): + if operation == "copy": + fs_bytes.cp_file(path, path + b"-copy") + else: + fs_bytes.checksum(path) + # The error must not close the connection + assert fs_bytes.ls(os.fsencode(tmp_path)) == [] + + def test_bytes_relative_upload_and_download(fs_bytes, tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) source = tmp_path / "local-source" From 91158b1ff5b0a16670a95c65662289ab3e88d5db Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 10:43:46 -0800 Subject: [PATCH 3/6] docs: drop the bytes-path paragraph from the README The class docstring already says that bytes paths are sent to the server unchanged and must be used with path_encoding=None. fsspec's generic methods taking only str paths is fsspec's behavior, not something sshfs needs to document. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/README.md b/README.md index 2e8a2dc..0a3921c 100644 --- a/README.md +++ b/README.md @@ -58,14 +58,6 @@ fs = SSHFileSystem( Note: you can also pass `client_keys` as an argument to `fsspec.open`. -For servers with file names that aren't valid UTF-8, set -`sftp_client_kwargs={"path_encoding": None}` and pass remote paths as bytes. -These methods accept bytes paths: `info`, `exists`, `isdir`, `isfile`, `size`, -`modified`, `ls`, `open`, `cat_file`, `pipe_file`, `put_file`, `get_file`, -`cp_file`, `mv`, `mkdir`, `makedirs`, `rm`, `rm_file`, and `checksum`. -fsspec's generic methods, such as `walk`, `find`, `glob`, `cat`, `pipe`, -`get`, `put`, and `copy`, need str paths. - All operations and their descriptions are specified [here](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem). Here are a few example calls you can make, starting with `info()` which allows you to retrieve the metadata about given path; From 3c02c5528793e6e9a2fb752ae7136ff841960c77 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 14:12:07 -0800 Subject: [PATCH 4/6] fix: skip makedirs for the root and pass -- to shell commands put_file and pipe_file skip creating the parent directory when it's the root as well as the home directory. asyncssh's makedirs("/") sends mkdir("/") twice and raises when the server denies it, as chrooted servers can, so uploads to a top-level path such as "/file" failed there. cp, md5sum and md5 get "--" before the paths, so a name starting with "-" isn't parsed as an option. Tests now cover checksum of a name with spaces, quotes and "$", cp_file and checksum of an existing file whose name isn't valid UTF-8 (skipped where the filesystem rejects such names), names starting with "-", an upload to "/" on a server that denies mkdir, and the mv copy fallback with bytes paths. Co-Authored-By: Claude Opus 5.5 --- sshfs/spec.py | 27 ++++++++++++------- tests/test_sshfs.py | 64 ++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 75 insertions(+), 16 deletions(-) diff --git a/sshfs/spec.py b/sshfs/spec.py index 57a7c5d..9abfbb2 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -238,7 +238,7 @@ async def _info(self, path, **kwargs): return info @wrap_exceptions - async def _modified(self, path: str, **kwargs) -> datetime: + async def _modified(self, path: str | bytes, **kwargs) -> datetime: path_info = await self._info(path) return path_info["mtime"] @@ -270,8 +270,7 @@ async def _put_file( **kwargs, ): rpath = self._strip_protocol(rpath) - if parent := self._parent(rpath): - await self._makedirs(parent, exist_ok=True) + await self._makedirs_parent(rpath) async with self._pool.get() as channel: await channel.put( lpath, @@ -297,7 +296,7 @@ async def _get_file( async def _cp_file(self, lpath, rpath, **kwargs): lpath = self._strip_protocol(lpath) rpath = self._strip_protocol(rpath) - await self._execute_with_paths(b"cp %s %s", lpath, rpath) + await self._execute_with_paths(b"cp -- %s %s", lpath, rpath) @wrap_exceptions async def _ls(self, path, detail=True, **kwargs): @@ -340,6 +339,13 @@ async def _makedirs( async with self._pool.get() as channel: await channel.makedirs(path, exist_ok=exist_ok, attrs=attrs) + async def _makedirs_parent(self, path): + parent = self._parent(path) + # The home directory ("") and the root ("/") always exist, and some + # servers deny mkdir("/"), which makes makedirs("/") fail. + if parent.rstrip(_sep(parent)): + await self._makedirs(parent, exist_ok=True) + mkdir = sync_wrapper(_mkdir) makedirs = sync_wrapper(_makedirs) @@ -387,10 +393,10 @@ async def _checksum(self, path): path = self._strip_protocol(path) system = await self._get_system() if system == "Linux": - command = b"md5sum %s" + command = b"md5sum -- %s" part = 0 elif system == "Darwin": - command = b"md5 %s" + command = b"md5 -- %s" part = -1 else: raise ValueError(f"{system!r} doesn't support checksum operation") @@ -423,9 +429,11 @@ async def _execute(self, *args, **kwargs): async def _execute_with_paths(self, command, *paths): """Execute a shell command with str or bytes paths quoted into it.""" + # asyncssh sends a bytes command as is, so paths that aren't valid + # UTF-8 reach the shell unchanged. command %= tuple(map(_quote, paths)) - # Output can include file names that aren't valid UTF-8, and - # failing to decode it strictly closes the SSH connection. + # Output can include those paths, and failing to decode it strictly + # closes the SSH connection. return await self._execute(command, errors="replace") def _open(self, path, *args, **kwargs): @@ -444,8 +452,7 @@ async def _cat_file(self, path, **kwargs): async def _pipe_file(self, path, data, chunksize=50 * 2**20, **kwargs): """Asynchronously writes the given data to a remote file in chunks.""" path = self._strip_protocol(path) - if parent := self._parent(path): - await self._makedirs(parent, exist_ok=True) + await self._makedirs_parent(path) async with self._pool.get() as channel: async with channel.open(path, "wb") as f: diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index 86fa333..ca1daba 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -17,6 +17,7 @@ SFTPFailure, SFTPName, SFTPOpUnsupported, + SFTPPermissionDenied, ) from sshfs import SSHFileSystem @@ -223,7 +224,7 @@ def test_relative_put_and_pipe(fs, tmp_path, monkeypatch): @pytest.mark.parametrize("operation", ["copy", "checksum"]) def test_bytes_shell_error_with_non_utf8_name(fs_bytes, tmp_path, operation): - path = os.fsencode(tmp_path) + b"/missing-caf\xe9" + path = os.fsencode(tmp_path) + b"/missing-\xff" with pytest.raises(FileNotFoundError): if operation == "copy": fs_bytes.cp_file(path, path + b"-copy") @@ -233,6 +234,49 @@ def test_bytes_shell_error_with_non_utf8_name(fs_bytes, tmp_path, operation): assert fs_bytes.ls(os.fsencode(tmp_path)) == [] +def test_bytes_shell_commands_with_non_utf8_name(fs_bytes, tmp_path): + # mock-ssh-server decodes SFTP paths as UTF-8, so only the methods that + # run shell commands can be tested with a name that isn't valid UTF-8 + path = os.fsencode(tmp_path) + b"/name-\xff" + try: + with open(path, "wb") as file: + file.write(b"data") + except OSError: + pytest.skip("the filesystem rejects names that aren't valid UTF-8") + assert fs_bytes.checksum(path) == hashlib.md5(b"data").hexdigest() + fs_bytes.cp_file(path, path + b"-copy") + with open(path + b"-copy", "rb") as file: + assert file.read() == b"data" + + +def test_shell_commands_with_leading_dash(fs, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + (tmp_path / "-r").write_bytes(b"data") + fs.cp_file("-r", "-r-copy") + assert (tmp_path / "-r-copy").read_bytes() == b"data" + assert fs.checksum("-r") == hashlib.md5(b"data").hexdigest() + + +@pytest.mark.parametrize("path", ["/file", b"/file"]) +def test_put_file_at_root_with_mkdir_denied(fs, tmp_path, monkeypatch, path): + # Some servers, such as chrooted ones, deny mkdir("/"). The upload itself + # is stubbed out, since the tests can't write to "/". + async def mkdir(self, path, *args, **kwargs): + raise SFTPPermissionDenied("Permission denied") + + uploads = [] + + async def put(self, lpath, rpath, **kwargs): + uploads.append(rpath) + + monkeypatch.setattr(SFTPClient, "mkdir", mkdir) + monkeypatch.setattr(SFTPClient, "put", put) + source = tmp_path / "source" + source.write_bytes(b"data") + fs.put_file(str(source), path) + assert uploads == [path] + + def test_bytes_relative_upload_and_download(fs_bytes, tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) source = tmp_path / "local-source" @@ -261,11 +305,9 @@ def test_bytes_file_operations(fs_bytes, tmp_path, operation): destination.parent.mkdir() fs_bytes.cp_file(os.fsencode(local), path) else: - assert ( - fs_bytes.checksum(os.fsencode(local)) - == hashlib.md5(data).hexdigest() - ) - return + destination.parent.mkdir() + destination.write_bytes(data) + assert fs_bytes.checksum(path) == hashlib.md5(data).hexdigest() assert destination.read_bytes() == data @@ -373,6 +415,16 @@ def test_move_copy_fallback_failure_keeps_source( assert fs.cat_file(remote_dir + "/a.txt") == b"data" +def test_bytes_move_copy_fallback(fs_bytes, tmp_path, no_posix_rename): + source = tmp_path / "a file ' $name" + source.write_bytes(b"data") + + fs_bytes.mv(os.fsencode(source), os.fsencode(tmp_path / "moved")) + + assert not source.exists() + assert (tmp_path / "moved").read_bytes() == b"data" + + def test_copy(fs, remote_dir): fs.touch(remote_dir + "/a.txt") initial_info = fs.info(remote_dir + "/a.txt") From 0ea6edae1f2158459f4484d5fd27a7b9fdadaa72 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 15:11:02 -0800 Subject: [PATCH 5/6] refactor: move the parent and "--" fixes out to #91 and #92 Leave put_file and pipe_file as they are on main, and give bytes paths in _parent the parents fsspec gives str paths, so str behavior doesn't change. Uploads to relative and top-level paths are fixed in #91, and "--" before paths in shell commands is added in #92. The upload test uses absolute paths, since relative uploads depend on #91. Co-Authored-By: Claude Opus 5.5 --- sshfs/spec.py | 29 ++++++++------------ tests/test_sshfs.py | 67 ++++++++++----------------------------------- 2 files changed, 25 insertions(+), 71 deletions(-) diff --git a/sshfs/spec.py b/sshfs/spec.py index 9abfbb2..f59cd67 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -33,10 +33,6 @@ _DEFAULT_MAX_SESSIONS = 10 -def _sep(path): - return b"/" if isinstance(path, bytes) else "/" - - def _quote(path): """Quote a str or bytes path for a POSIX shell, as bytes.""" if isinstance(path, str): @@ -141,7 +137,11 @@ def _get_kwargs_from_urls(urlpath): @classmethod def _parent(cls, path): path = cls._strip_protocol(path) - return posixpath.dirname(path.rstrip(_sep(path)) or path) + if isinstance(path, bytes): + # The same result as fsspec's _parent gives for the str path, + # whose trailing slashes _strip_protocol removes + return path.rstrip(b"/").rpartition(b"/")[0] + return super()._parent(path) @wrap_exceptions async def _connect( @@ -230,7 +230,7 @@ async def _info(self, path, **kwargs): attributes = await channel.stat(path) info = self._decode_attributes(attributes) - sep = _sep(path) + sep = b"/" if isinstance(path, bytes) else "/" path = path.rstrip(sep) if info["type"] == "directory": path += sep @@ -270,7 +270,7 @@ async def _put_file( **kwargs, ): rpath = self._strip_protocol(rpath) - await self._makedirs_parent(rpath) + await self._makedirs(self._parent(rpath), exist_ok=True) async with self._pool.get() as channel: await channel.put( lpath, @@ -296,7 +296,7 @@ async def _get_file( async def _cp_file(self, lpath, rpath, **kwargs): lpath = self._strip_protocol(lpath) rpath = self._strip_protocol(rpath) - await self._execute_with_paths(b"cp -- %s %s", lpath, rpath) + await self._execute_with_paths(b"cp %s %s", lpath, rpath) @wrap_exceptions async def _ls(self, path, detail=True, **kwargs): @@ -339,13 +339,6 @@ async def _makedirs( async with self._pool.get() as channel: await channel.makedirs(path, exist_ok=exist_ok, attrs=attrs) - async def _makedirs_parent(self, path): - parent = self._parent(path) - # The home directory ("") and the root ("/") always exist, and some - # servers deny mkdir("/"), which makes makedirs("/") fail. - if parent.rstrip(_sep(parent)): - await self._makedirs(parent, exist_ok=True) - mkdir = sync_wrapper(_mkdir) makedirs = sync_wrapper(_makedirs) @@ -393,10 +386,10 @@ async def _checksum(self, path): path = self._strip_protocol(path) system = await self._get_system() if system == "Linux": - command = b"md5sum -- %s" + command = b"md5sum %s" part = 0 elif system == "Darwin": - command = b"md5 -- %s" + command = b"md5 %s" part = -1 else: raise ValueError(f"{system!r} doesn't support checksum operation") @@ -452,7 +445,7 @@ async def _cat_file(self, path, **kwargs): async def _pipe_file(self, path, data, chunksize=50 * 2**20, **kwargs): """Asynchronously writes the given data to a remote file in chunks.""" path = self._strip_protocol(path) - await self._makedirs_parent(path) + await self._makedirs(self._parent(path), exist_ok=True) async with self._pool.get() as channel: async with channel.open(path, "wb") as f: diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index ca1daba..e7b01fe 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -17,7 +17,6 @@ SFTPFailure, SFTPName, SFTPOpUnsupported, - SFTPPermissionDenied, ) from sshfs import SSHFileSystem @@ -196,32 +195,22 @@ def test_bytes_metadata_and_remove(fs_bytes, tmp_path): "path, parent", [ ("ssh://host/a/b", "/a"), - ("/a", "/"), - ("/", "/"), + ("/a", ""), + ("/", ""), ("a/b", "a"), ("a", ""), (b"/a/b/", b"/a"), - (b"/a", b"/"), - (b"/", b"/"), + (b"/a", b""), + (b"/", b""), (b"a/b", b"a"), (b"a", b""), ], ) def test_parent(path, parent): - # "" is the home directory, so the parent of a top-level path is "/" + # Bytes paths get the same parents as str paths assert SSHFileSystem._parent(path) == parent -def test_relative_put_and_pipe(fs, tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - source = tmp_path / "local-source" - source.write_bytes(b"relative data") - fs.put_file(str(source), "remote-file") - assert (tmp_path / "remote-file").read_bytes() == b"relative data" - fs.pipe_file("piped-file", b"piped data") - assert (tmp_path / "piped-file").read_bytes() == b"piped data" - - @pytest.mark.parametrize("operation", ["copy", "checksum"]) def test_bytes_shell_error_with_non_utf8_name(fs_bytes, tmp_path, operation): path = os.fsencode(tmp_path) + b"/missing-\xff" @@ -249,45 +238,17 @@ def test_bytes_shell_commands_with_non_utf8_name(fs_bytes, tmp_path): assert file.read() == b"data" -def test_shell_commands_with_leading_dash(fs, tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - (tmp_path / "-r").write_bytes(b"data") - fs.cp_file("-r", "-r-copy") - assert (tmp_path / "-r-copy").read_bytes() == b"data" - assert fs.checksum("-r") == hashlib.md5(b"data").hexdigest() - - -@pytest.mark.parametrize("path", ["/file", b"/file"]) -def test_put_file_at_root_with_mkdir_denied(fs, tmp_path, monkeypatch, path): - # Some servers, such as chrooted ones, deny mkdir("/"). The upload itself - # is stubbed out, since the tests can't write to "/". - async def mkdir(self, path, *args, **kwargs): - raise SFTPPermissionDenied("Permission denied") - - uploads = [] - - async def put(self, lpath, rpath, **kwargs): - uploads.append(rpath) - - monkeypatch.setattr(SFTPClient, "mkdir", mkdir) - monkeypatch.setattr(SFTPClient, "put", put) - source = tmp_path / "source" - source.write_bytes(b"data") - fs.put_file(str(source), path) - assert uploads == [path] - - -def test_bytes_relative_upload_and_download(fs_bytes, tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) +def test_bytes_upload_and_download(fs_bytes, tmp_path): source = tmp_path / "local-source" - source.write_bytes(b"relative data") - fs_bytes.put_file(str(source), b"remote-file") - assert fs_bytes.info(b"remote-file")["name"] == b"remote-file" + source.write_bytes(b"data") + remote = os.fsencode(tmp_path) + b"/remote-file" + fs_bytes.put_file(str(source), remote) + assert fs_bytes.info(remote)["name"] == remote destination = tmp_path / "local-copy" - fs_bytes.get_file(b"remote-file", str(destination)) - assert destination.read_bytes() == b"relative data" - fs_bytes.pipe_file(b"piped-file", b"piped data") - assert fs_bytes.cat_file(b"piped-file") == b"piped data" + fs_bytes.get_file(remote, str(destination)) + assert destination.read_bytes() == b"data" + fs_bytes.pipe_file(remote, b"piped data") + assert fs_bytes.cat_file(remote) == b"piped data" @pytest.mark.parametrize("operation", ["put", "pipe", "copy", "checksum"]) From cc789578c5d001f32cddccd43013ef31828536a6 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 17:03:05 -0800 Subject: [PATCH 6/6] refactor: simplify the command helper and split the bytes tests - _execute_with_paths takes the program and joins the quoted paths to it instead of formatting them into a command string. - _parent strips the protocol once and handles str and bytes with the same expression. The str results are unchanged. - The bytes tests are split into one test per operation, each next to its str counterpart, without branches on the operation. - test_bytes_info also checks a directory path without a trailing slash and the root. - test_sftp_client_kwargs_path_encoding uses the fs_bytes fixture. Co-Authored-By: Claude Opus 5.5 --- sshfs/spec.py | 23 ++-- tests/test_sshfs.py | 286 ++++++++++++++++++++++++-------------------- 2 files changed, 168 insertions(+), 141 deletions(-) diff --git a/sshfs/spec.py b/sshfs/spec.py index f59cd67..3a94c2d 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -137,11 +137,10 @@ def _get_kwargs_from_urls(urlpath): @classmethod def _parent(cls, path): path = cls._strip_protocol(path) - if isinstance(path, bytes): - # The same result as fsspec's _parent gives for the str path, - # whose trailing slashes _strip_protocol removes - return path.rstrip(b"/").rpartition(b"/")[0] - return super()._parent(path) + # The same parents as fsspec's _parent gives. _strip_protocol keeps + # trailing slashes in bytes paths, so they are removed here. + sep = b"/" if isinstance(path, bytes) else "/" + return path.rstrip(sep).rpartition(sep)[0] @wrap_exceptions async def _connect( @@ -296,7 +295,7 @@ async def _get_file( async def _cp_file(self, lpath, rpath, **kwargs): lpath = self._strip_protocol(lpath) rpath = self._strip_protocol(rpath) - await self._execute_with_paths(b"cp %s %s", lpath, rpath) + await self._execute_with_paths(b"cp", lpath, rpath) @wrap_exceptions async def _ls(self, path, detail=True, **kwargs): @@ -386,15 +385,15 @@ async def _checksum(self, path): path = self._strip_protocol(path) system = await self._get_system() if system == "Linux": - command = b"md5sum %s" + program = b"md5sum" part = 0 elif system == "Darwin": - command = b"md5 %s" + program = b"md5" part = -1 else: raise ValueError(f"{system!r} doesn't support checksum operation") - result = await self._execute_with_paths(command, path) + result = await self._execute_with_paths(program, path) parts = result.stdout.strip().split() assert len(parts) >= 1 @@ -420,11 +419,11 @@ async def _execute(self, *args, **kwargs): execute = sync_wrapper(_execute) - async def _execute_with_paths(self, command, *paths): - """Execute a shell command with str or bytes paths quoted into it.""" + async def _execute_with_paths(self, program, *paths): + """Run a program with str or bytes paths as its arguments.""" # asyncssh sends a bytes command as is, so paths that aren't valid # UTF-8 reach the shell unchanged. - command %= tuple(map(_quote, paths)) + command = b" ".join((program, *map(_quote, paths))) # Output can include those paths, and failing to decode it strictly # closes the SSH connection. return await self._execute(command, errors="replace") diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index e7b01fe..0b7863d 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -93,6 +93,19 @@ def fs_bytes(ssh_server): ) +@pytest.fixture +def non_utf8_file(tmp_path): + # mock-ssh-server decodes SFTP paths as UTF-8, so only the methods that + # run shell commands can be tested with a name that isn't valid UTF-8 + path = os.fsencode(tmp_path) + b"/name-\xff" + try: + with open(path, "wb") as file: + file.write(b"data") + except OSError: + pytest.skip("the filesystem rejects names that aren't valid UTF-8") + return path + + def strip_keys(info): for key in ["name", "time", "mtime", "atime"]: info.pop(key, None) @@ -153,142 +166,16 @@ def test_sftp_client_kwargs(ssh_server, tmp_path, user="user"): assert fs.exists(file) -def test_sftp_client_kwargs_path_encoding(ssh_server, tmp_path, user="user"): +def test_sftp_client_kwargs_path_encoding(fs_bytes, tmp_path): # path_encoding=None makes asyncssh deliver remote paths as raw # bytes instead of str, for servers with non-UTF-8 file names (#39). - fs = SSHFileSystem( - host=ssh_server.host, - port=ssh_server.port, - username=user, - client_keys=[USERS[user]], - sftp_client_kwargs={"path_encoding": None}, - ) - directory = tmp_path / "path_encoding_probe" directory.mkdir() (directory / "data.txt").write_bytes(b"data") encoded = str(directory).encode() - assert fs.ls(encoded, detail=False) == [encoded + b"/data.txt"] - assert fs.cat_file(encoded + b"/data.txt") == b"data" - - -def test_bytes_metadata_and_remove(fs_bytes, tmp_path): - directory = tmp_path / "byte-paths" - directory.mkdir() - file = directory / "data.txt" - file.write_bytes(b"data") - path = os.fsencode(file) - parent = os.fsencode(directory) - assert fs_bytes.info(path)["name"] == path - assert fs_bytes.info(parent + b"/")["name"] == parent + b"/" - assert fs_bytes.exists(path) and fs_bytes.isfile(path) - assert fs_bytes.isdir(parent) and fs_bytes.size(path) == 4 - assert fs_bytes.modified(path).tzinfo == UTC - fs_bytes.rm(path) - assert not file.exists() - fs_bytes.rm(parent, recursive=True) - assert not directory.exists() - - -@pytest.mark.parametrize( - "path, parent", - [ - ("ssh://host/a/b", "/a"), - ("/a", ""), - ("/", ""), - ("a/b", "a"), - ("a", ""), - (b"/a/b/", b"/a"), - (b"/a", b""), - (b"/", b""), - (b"a/b", b"a"), - (b"a", b""), - ], -) -def test_parent(path, parent): - # Bytes paths get the same parents as str paths - assert SSHFileSystem._parent(path) == parent - - -@pytest.mark.parametrize("operation", ["copy", "checksum"]) -def test_bytes_shell_error_with_non_utf8_name(fs_bytes, tmp_path, operation): - path = os.fsencode(tmp_path) + b"/missing-\xff" - with pytest.raises(FileNotFoundError): - if operation == "copy": - fs_bytes.cp_file(path, path + b"-copy") - else: - fs_bytes.checksum(path) - # The error must not close the connection - assert fs_bytes.ls(os.fsencode(tmp_path)) == [] - - -def test_bytes_shell_commands_with_non_utf8_name(fs_bytes, tmp_path): - # mock-ssh-server decodes SFTP paths as UTF-8, so only the methods that - # run shell commands can be tested with a name that isn't valid UTF-8 - path = os.fsencode(tmp_path) + b"/name-\xff" - try: - with open(path, "wb") as file: - file.write(b"data") - except OSError: - pytest.skip("the filesystem rejects names that aren't valid UTF-8") - assert fs_bytes.checksum(path) == hashlib.md5(b"data").hexdigest() - fs_bytes.cp_file(path, path + b"-copy") - with open(path + b"-copy", "rb") as file: - assert file.read() == b"data" - - -def test_bytes_upload_and_download(fs_bytes, tmp_path): - source = tmp_path / "local-source" - source.write_bytes(b"data") - remote = os.fsencode(tmp_path) + b"/remote-file" - fs_bytes.put_file(str(source), remote) - assert fs_bytes.info(remote)["name"] == remote - destination = tmp_path / "local-copy" - fs_bytes.get_file(remote, str(destination)) - assert destination.read_bytes() == b"data" - fs_bytes.pipe_file(remote, b"piped data") - assert fs_bytes.cat_file(remote) == b"piped data" - - -@pytest.mark.parametrize("operation", ["put", "pipe", "copy", "checksum"]) -def test_bytes_file_operations(fs_bytes, tmp_path, operation): - local = tmp_path / "source" - data = b"file data" * 10000 - local.write_bytes(data) - destination = tmp_path / "nested" / "a file ' $name" - path = os.fsencode(destination) - if operation == "put": - fs_bytes.put_file(str(local), path) - elif operation == "pipe": - fs_bytes.pipe_file(path, data) - elif operation == "copy": - destination.parent.mkdir() - fs_bytes.cp_file(os.fsencode(local), path) - else: - destination.parent.mkdir() - destination.write_bytes(data) - assert fs_bytes.checksum(path) == hashlib.md5(data).hexdigest() - assert destination.read_bytes() == data - - -@pytest.mark.parametrize("detail", [True, False]) -def test_bytes_ls_omits_dot_entries(fs_bytes, tmp_path, monkeypatch, detail): - (tmp_path / "data").write_bytes(b"data") - path = os.fsencode(tmp_path) - original = SFTPClient.readdir - - async def readdir(channel, path): - entries = await original(channel, path) - attrs = await channel.stat(path) - return entries + [ - SFTPName(name, attrs=attrs) for name in (b"", b".", b"..") - ] - - monkeypatch.setattr(SFTPClient, "readdir", readdir) - listing = fs_bytes.ls(path, detail=detail) - names = [info["name"] for info in listing] if detail else listing - assert names == [path + b"/data"] + assert fs_bytes.ls(encoded, detail=False) == [encoded + b"/data.txt"] + assert fs_bytes.cat_file(encoded + b"/data.txt") == b"data" def test_info(fs, remote_dir, plain_remote_dir): @@ -307,6 +194,30 @@ def test_info(fs, remote_dir, plain_remote_dir): assert details["name"] == plain_remote_dir + "/dir/" +def test_bytes_info(fs_bytes, tmp_path): + (tmp_path / "dir").mkdir() + (tmp_path / "dir" / "a.txt").write_bytes(b"data") + directory = os.fsencode(tmp_path / "dir") + file = directory + b"/a.txt" + + details = fs_bytes.info(file) + assert details["type"] == "file" + assert details["name"] == file + assert details["size"] == 4 + assert fs_bytes.exists(file) + assert fs_bytes.isfile(file) + assert fs_bytes.size(file) == 4 + assert fs_bytes.modified(file) == details["mtime"] + + details = fs_bytes.info(directory) + assert details["type"] == "directory" + assert details["name"] == directory + b"/" + assert fs_bytes.isdir(directory) + + assert fs_bytes.info(directory + b"/")["name"] == directory + b"/" + assert fs_bytes.info(b"/")["name"] == b"/" + + def test_info_timestamps_are_tz_aware_utc(fs, remote_dir): fs.touch(remote_dir + "/a.txt") details = fs.info(remote_dir + "/a.txt") @@ -399,6 +310,29 @@ def test_copy(fs, remote_dir): assert strip_keys(initial_info) == strip_keys(secondary_info) +def test_bytes_cp_file(fs_bytes, tmp_path): + (tmp_path / "a file ' $name").write_bytes(b"data") + fs_bytes.cp_file( + os.fsencode(tmp_path / "a file ' $name"), + os.fsencode(tmp_path / "copy ' $name"), + ) + assert (tmp_path / "copy ' $name").read_bytes() == b"data" + + +def test_bytes_cp_file_non_utf8_name(fs_bytes, non_utf8_file): + fs_bytes.cp_file(non_utf8_file, non_utf8_file + b"-copy") + with open(non_utf8_file + b"-copy", "rb") as file: + assert file.read() == b"data" + + +def test_bytes_cp_file_missing_non_utf8_name(fs_bytes, tmp_path): + path = os.fsencode(tmp_path) + b"/missing-\xff" + with pytest.raises(FileNotFoundError): + fs_bytes.cp_file(path, path + b"-copy") + # The error output must not close the connection + assert fs_bytes.ls(os.fsencode(tmp_path)) == [] + + def test_rm(fs, remote_dir): fs.touch(remote_dir + "/a.txt") fs.rm(remote_dir + "/a.txt") @@ -417,6 +351,17 @@ def test_rm(fs, remote_dir): assert not fs.exists(remote_dir + "/dir") +def test_bytes_rm(fs_bytes, tmp_path): + (tmp_path / "a.txt").write_bytes(b"data") + fs_bytes.rm(os.fsencode(tmp_path / "a.txt")) + assert not (tmp_path / "a.txt").exists() + + (tmp_path / "dir").mkdir() + (tmp_path / "dir" / "a.txt").write_bytes(b"data") + fs_bytes.rm(os.fsencode(tmp_path / "dir"), recursive=True) + assert not (tmp_path / "dir").exists() + + def test_checksum(fs, remote_dir): data = b"iterative.ai" @@ -427,6 +372,24 @@ def test_checksum(fs, remote_dir): assert fs.checksum(remote_dir + "/a.txt") == checksum +def test_bytes_checksum(fs_bytes, tmp_path): + (tmp_path / "a file ' $name").write_bytes(b"data") + path = os.fsencode(tmp_path / "a file ' $name") + assert fs_bytes.checksum(path) == hashlib.md5(b"data").hexdigest() + + +def test_bytes_checksum_non_utf8_name(fs_bytes, non_utf8_file): + checksum = hashlib.md5(b"data").hexdigest() + assert fs_bytes.checksum(non_utf8_file) == checksum + + +def test_bytes_checksum_missing_non_utf8_name(fs_bytes, tmp_path): + with pytest.raises(FileNotFoundError): + fs_bytes.checksum(os.fsencode(tmp_path) + b"/missing-\xff") + # The error output must not close the connection + assert fs_bytes.ls(os.fsencode(tmp_path)) == [] + + def test_ls(fs, remote_dir, plain_remote_dir): fs.mkdir(remote_dir + "dir/") files = set() @@ -450,6 +413,25 @@ def test_ls(fs, remote_dir, plain_remote_dir): assert dirs == expected +@pytest.mark.parametrize("detail", [True, False]) +def test_bytes_ls_omits_dot_entries(fs_bytes, tmp_path, monkeypatch, detail): + (tmp_path / "data").write_bytes(b"data") + path = os.fsencode(tmp_path) + original = SFTPClient.readdir + + async def readdir(channel, path): + entries = await original(channel, path) + attrs = await channel.stat(path) + return entries + [ + SFTPName(name, attrs=attrs) for name in (b"", b".", b"..") + ] + + monkeypatch.setattr(SFTPClient, "readdir", readdir) + listing = fs_bytes.ls(path, detail=detail) + names = [info["name"] for info in listing] if detail else listing + assert names == [path + b"/data"] + + def test_walk(fs, remote_dir, plain_remote_dir): fs.mkdir(remote_dir + "/a") fs.mkdir(remote_dir + "/a/b") @@ -514,6 +496,31 @@ def __fspath__(self): assert strip(["foo/bar/1", "foo/bar/2"]) == ["foo/bar/1", "foo/bar/2"] +@pytest.mark.parametrize( + "path, parent", + [ + ("ssh://host/a/b", "/a"), + ("/a/b", "/a"), + ("/a/b/", "/a"), + ("/a", ""), + ("/", ""), + ("a/b", "a"), + ("a", ""), + ("", ""), + (b"/a/b", b"/a"), + (b"/a/b/", b"/a"), + (b"/a", b""), + (b"/", b""), + (b"a/b", b"a"), + (b"a", b""), + (b"", b""), + ], +) +def test_parent(path, parent): + # Bytes paths get the same parents as str paths + assert SSHFileSystem._parent(path) == parent + + def test_mkdir(fs, remote_dir): fs.mkdir(remote_dir + "dir/") assert fs.isdir(remote_dir + "dir/") @@ -687,6 +694,14 @@ def test_put_file(fs, remote_dir, file_path, tmp_path): assert stream.read() == b"data" +@pytest.mark.parametrize("file_path", [b"a.txt", b"dir/a.txt"]) +def test_bytes_put_file(fs_bytes, tmp_path, file_path): + (tmp_path / "upload.txt").write_bytes(b"data") + remote_file = os.fsencode(tmp_path) + b"/" + file_path + fs_bytes.put_file(str(tmp_path / "upload.txt"), remote_file) + assert (tmp_path / os.fsdecode(file_path)).read_bytes() == b"data" + + @pytest.mark.parametrize("file_path", ["a.txt", "dir/a.txt"]) def test_get_file(fs, remote_dir, file_path, tmp_path): remote_file = remote_dir + f"/{file_path}" @@ -700,6 +715,13 @@ def test_get_file(fs, remote_dir, file_path, tmp_path): assert local_file.read_bytes() == b"data" +def test_bytes_get_file(fs_bytes, tmp_path): + (tmp_path / "a.txt").write_bytes(b"data") + local_file = tmp_path / "downloaded.txt" + fs_bytes.get_file(os.fsencode(tmp_path / "a.txt"), str(local_file)) + assert local_file.read_bytes() == b"data" + + def test_concurrency_for_raw_commands(fs, remote_dir): with fs.open(remote_dir + "/cp_data", "wb") as stream: stream.write(b"hello!") @@ -751,3 +773,9 @@ def test_pipe_file(fs, remote_dir): assert ( f.read() == test_data ), "The data read from the file does not match the data written." + + +@pytest.mark.parametrize("file_path", [b"a.txt", b"dir/a.txt"]) +def test_bytes_pipe_file(fs_bytes, tmp_path, file_path): + fs_bytes.pipe_file(os.fsencode(tmp_path) + b"/" + file_path, b"data") + assert (tmp_path / os.fsdecode(file_path)).read_bytes() == b"data"