Changeset 2046:e59335e8b934


Ignore:
Timestamp:
Feb 1, 2021, 5:47:45 PM (10 months ago)
Author:
Stefan Schwarzer <sschwarzer@…>
Branch:
default
Message:
Raise `NoEncodingError` for absent encoding

If an FTP session instance doesn't have an `encoding` attribute, let
`FTPHost` raise a `NoEncodingError`. This is a new exception.

Before, the code would fall back to the ftputil default encoding,
latin-1. This could be surprising behavior for some ftputil users. So
rather fail explicitly and early if no `encoding` attribute exists.
Otherwise, it the fallback encoding had been wrong, we might get
exceptions only much later in production.

ticket: 143
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • ftputil/error.py

    r2045 r2046  
    2525    "InternalError",
    2626    "KeepAliveError",
     27    "NoEncodingError",
    2728    "ParserError",
    2829    "PermanentError",
     
    115116
    116117
     118class NoEncodingError(InternalError):
     119    """Raised if session instances don't specify an encoding."""
     120
     121    pass
     122
     123
    117124# Currently not used
    118125class KeepAliveError(InternalError):
  • ftputil/host.py

    r2034 r2046  
    145145        with ftputil.error.ftplib_error_to_ftp_os_error:
    146146            session = factory(*args, **kwargs)
    147             self._encoding = getattr(
    148                 session, "encoding", ftputil.path_encoding.DEFAULT_ENCODING
    149             )
     147            if not hasattr(session, "encoding"):
     148                raise ftputil.error.NoEncodingError(
     149                    f"session instance {session!r} must have an `encoding` attribute"
     150                )
     151            self._encoding = session.encoding
    150152        return session
    151153
  • test/test_host.py

    r2035 r2046  
    9090        with test_base.ftp_host_factory(scripted_session.factory(script)) as host:
    9191            assert host.getcwd() == "/home"
     92
     93    def test_missing_encoding_attribute(self):
     94        """
     95        Test if a missing `encoding` attribute on the session instance leads to
     96        a `NoEncodingError`.
     97        """
     98
     99        class InvalidSessionError:
     100            pass
     101
     102        with pytest.raises(ftputil.error.NoEncodingError):
     103            _ = ftputil.host.FTPHost(session_factory=InvalidSessionError)
    92104
    93105
Note: See TracChangeset for help on using the changeset viewer.