Changeset 1343:bcadc5b1504f


Ignore:
Timestamp:
Aug 4, 2013, 5:29:02 PM (7 years ago)
Author:
Stefan Schwarzer <sschwarzer@…>
Branch:
default
Message:
Use double quotes (") for strings.

I used to have a rule to put "identifier-like" strings in single
quotes (') and other strings in double quotes. For example, dictionary
keys would usually be in single quotes, but error messages in double
quotes.

Unfortunately, there are many border cases, so over time I've become
tired of thinking about when I should use one kind of quotes or the
other. So everything is in double quotes now. Also, I guess most
people are rather used to double quotes for strings and thus will
welcome the change. :-)
Files:
23 edited

Legend:

Unmodified
Added
Removed
  • Makefile

    r1303 r1343  
    3737patch:
    3838        @echo "Patching files"
    39         ${SED} "s/^__version__ = '.*'/__version__ = \'`cat VERSION`\'/" \
     39        ${SED} "s/^__version__ = '.*'/__version__ = \"`cat VERSION`\"/" \
    4040                ${SOURCE_DIR}/ftputil_version.py
    4141        ${SED} "s/^:Version:   .*/:Version:   ${VERSION}/" \
  • ftputil/__init__.py

    r1319 r1343  
    1111
    1212    # Example session
    13     host = ftputil.FTPHost('ftp.domain.com', 'me', 'secret')
    14     print host.getcwd()  # e. g. '/home/me'
    15     source = host.open('sourcefile', 'r')
    16     host.mkdir('newdir')
    17     host.chdir('newdir')
    18     target = host.open('targetfile', 'w')
     13    host = ftputil.FTPHost("ftp.domain.com", "me", "secret")
     14    print host.getcwd()  # e. g. "/home/me"
     15    source = host.open("sourcefile", "r")
     16    host.mkdir("newdir")
     17    host.chdir("newdir")
     18    target = host.open("targetfile", "w")
    1919    host.copyfileobj(source, target)
    2020    source.close()
    2121    target.close()
    22     host.remove('targetfile')
     22    host.remove("targetfile")
    2323    host.chdir(host.pardir)
    24     host.rmdir('newdir')
     24    host.rmdir("newdir")
    2525    host.close()
    2626
     
    3030    host.download(remote_file, local_file)
    3131
    32     Both accept an additional mode parameter. If it is 'b', the
     32    Both accept an additional mode parameter. If it is "b", the
    3333    transfer mode will be for binary files.
    3434
  • ftputil/error.py

    r1224 r1343  
    2323# it's _not_ recommended.
    2424__all__ = [
    25   'FTPError',
    26   'InternalError',
    27   'RootDirError',
    28   'InaccessibleLoginDirError',
    29   'TimeShiftError',
    30   'ParserError',
    31   'KeepAliveError',
    32   'FTPOSError',
    33   'TemporaryError',
    34   'PermanentError',
    35   'CommandNotImplementedError',
    36   'SyncError',
    37   'FTPIOError',
     25  "FTPError",
     26  "InternalError",
     27  "RootDirError",
     28  "InaccessibleLoginDirError",
     29  "TimeShiftError",
     30  "ParserError",
     31  "KeepAliveError",
     32  "FTPOSError",
     33  "TemporaryError",
     34  "PermanentError",
     35  "CommandNotImplementedError",
     36  "SyncError",
     37  "FTPIOError",
    3838  ]
    3939
  • ftputil/file.py

    r1342 r1343  
    150150        # Always use binary mode (see above).
    151151        transfer_type = "I"
    152         command = 'TYPE {0}'.format(transfer_type)
     152        command = "TYPE {0}".format(transfer_type)
    153153        with ftputil.error.ftplib_error_to_ftp_io_error:
    154154            self._session.voidcmd(command)
    155155        # Make transfer command.
    156         command_type = ('STOR', 'RETR')[is_read_mode]
    157         command = '{0} {1}'.format(command_type, path)
     156        command_type = ("STOR", "RETR")[is_read_mode]
     157        command = "{0} {1}".format(command_type, path)
    158158        # Force to binary regardless of transfer type (see above).
    159159        makefile_mode = mode
  • ftputil/file_transfer.py

    r1329 r1343  
    1515# # Only `chunks` should be used by clients of the ftputil library. Any
    1616# #  other functionality is supposed to be used via `FTPHost` objects.
    17 # __all__ = ['chunks']
     17# __all__ = ["chunks"]
    1818__all__ = []
    1919
  • ftputil/host.py

    r1319 r1343  
    1919import ftputil.tool
    2020
    21 __all__ = ['FTPHost']
     21__all__ = ["FTPHost"]
    2222
    2323
     
    4040    #
    4141    #   host = FTPHost(ftp_server, user, password)
    42     #   f = host.open('index.html')
     42    #   f = host.open("index.html")
    4343    #   host.getcwd()   # would block!
    4444    #
     
    7676        # that this is, strictly speaking, dependent on the server OS
    7777        # but it seems to work at least with Unix and Windows servers.
    78         self.curdir, self.pardir, self.sep = '.', '..', '/'
     78        self.curdir, self.pardir, self.sep = ".", "..", "/"
    7979        # Set default time shift (used in `upload_if_newer` and
    8080        # `download_if_newer`).
     
    114114        # this `FTPHost` object, use the same factory for this
    115115        # `FTPHost` object's child sessions.
    116         factory = kwargs.pop('session_factory', ftplib.FTP)
     116        factory = kwargs.pop("session_factory", ftplib.FTP)
    117117        # pylint: disable=W0142
    118118        with ftputil.error.ftplib_error_to_ftp_os_error:
     
    349349        try:
    350350            # May raise `FTPIOError` if directory isn't writable.
    351             file_ = self.open(helper_file_name, 'w')
     351            file_ = self.open(helper_file_name, "w")
    352352            file_.close()
    353353        except ftputil.error.FTPIOError:
    354354            raise ftputil.error.TimeShiftError(
    355                     '''couldn't write helper file in directory "{0}"'''.
     355                    """couldn't write helper file in directory '{0}'""".
    356356                    format(self.getcwd()))
    357357        # If everything worked up to here it should be possible to stat
     
    405405        `target`.
    406406        """
    407         if 'length' in kwargs:
    408             max_chunk_size = kwargs['length']
     407        if "length" in kwargs:
     408            max_chunk_size = kwargs["length"]
    409409            warnings.warn(("Parameter name `length` will be removed in "
    410410                           "ftputil 2.6, use `max_chunk_size` instead"),
     
    417417        #XXX Should we allow mode "a" at all? We don't support appending!
    418418        # Invalid mode values are handled when a file object is made.
    419         if mode == 'b':
    420             return 'rb', 'wb'
     419        if mode == "b":
     420            return "rb", "wb"
    421421        else:
    422             return 'r', 'w'
     422            return "r", "w"
    423423
    424424    def _upload_files(self, source_path, target_path, mode):
     
    437437        return source_file, target_file
    438438
    439     def upload(self, source, target, mode='', callback=None):
     439    def upload(self, source, target, mode="", callback=None):
    440440        """
    441441        Upload a file from the local source (name) to the remote
    442         target (name). The argument `mode` is an empty string or 'a' for
    443         text copies, or 'b' for binary copies.
     442        target (name). The argument `mode` is an empty string or "a" for
     443        text copies, or "b" for binary copies.
    444444        """
    445445        target = ftputil.tool.as_unicode(target)
     
    448448                                        conditional=False, callback=callback)
    449449
    450     def upload_if_newer(self, source, target, mode='', callback=None):
     450    def upload_if_newer(self, source, target, mode="", callback=None):
    451451        """
    452452        Upload a file only if it's newer than the target on the
     
    476476        return source_file, target_file
    477477
    478     def download(self, source, target, mode='', callback=None):
     478    def download(self, source, target, mode="", callback=None):
    479479        """
    480480        Download a file from the remote source (name) to the local
    481         target (name). The argument mode is an empty string or 'a' for
    482         text copies, or 'b' for binary copies.
     481        target (name). The argument mode is an empty string or "a" for
     482        text copies, or "b" for binary copies.
    483483        """
    484484        source = ftputil.tool.as_unicode(source)
     
    487487                                        conditional=False, callback=callback)
    488488
    489     def download_if_newer(self, source, target, mode='', callback=None):
     489    def download_if_newer(self, source, target, mode="", callback=None):
    490490        """
    491491        Download a file only if it's newer than the target on the
  • ftputil/path.py

    r1294 r1343  
    181181
    182182        For each directory in the directory tree rooted at top
    183         (including top itself, but excluding '.' and '..'), call
     183        (including top itself, but excluding "." and ".."), call
    184184        func(arg, dirname, fnames). dirname is the name of the
    185185        directory, and fnames a list of the names of the files and
    186         subdirectories in dirname (excluding '.' and '..').  func may
     186        subdirectories in dirname (excluding "." and "..").  func may
    187187        modify the fnames list in-place (e.g. via del or slice
    188188        assignment), and walk will only recurse into the
  • ftputil/stat.py

    r1283 r1343  
    1919
    2020# These can be used to write custom parsers.
    21 __all__ = ['StatResult', 'Parser', 'UnixParser', 'MSParser']
     21__all__ = ["StatResult", "Parser", "UnixParser", "MSParser"]
    2222
    2323
     
    3232
    3333    _index_mapping = {
    34       'st_mode':  0, 'st_ino':   1, 'st_dev':    2, 'st_nlink':    3,
    35       'st_uid':   4, 'st_gid':   5, 'st_size':   6, 'st_atime':    7,
    36       'st_mtime': 8, 'st_ctime': 9, '_st_name': 10, '_st_target': 11}
     34      "st_mode":  0, "st_ino":   1, "st_dev":    2, "st_nlink":    3,
     35      "st_uid":   4, "st_gid":   5, "st_size":   6, "st_atime":    7,
     36      "st_mtime": 8, "st_ctime": 9, "_st_name": 10, "_st_target": 11}
    3737
    3838    def __init__(self, sequence):
     
    6666    # Map month abbreviations to month numbers.
    6767    _month_numbers = {
    68       'jan':  1, 'feb':  2, 'mar':  3, 'apr':  4,
    69       'may':  5, 'jun':  6, 'jul':  7, 'aug':  8,
    70       'sep':  9, 'oct': 10, 'nov': 11, 'dec': 12}
     68      "jan":  1, "feb":  2, "mar":  3, "apr":  4,
     69      "may":  5, "jun":  6, "jul":  7, "aug":  8,
     70      "sep":  9, "oct": 10, "nov": 11, "dec": 12}
    7171
    7272    _total_regex = re.compile(r"^total\s+\d+")
     
    122122        #TODO Add support for "S" and sticky bit ("t", "T").
    123123        for bit in mode_string[1:10]:
    124             bit = (bit != '-')
     124            bit = (bit != "-")
    125125            st_mode = (st_mode << 1) + bit
    126         if mode_string[3] == 's':
     126        if mode_string[3] == "s":
    127127            st_mode = st_mode | stat.S_ISUID
    128         if mode_string[6] == 's':
     128        if mode_string[6] == "s":
    129129            st_mode = st_mode | stat.S_ISGID
    130         file_type_to_mode = {'b': stat.S_IFBLK, 'c': stat.S_IFCHR,
    131                              'd': stat.S_IFDIR, 'l': stat.S_IFLNK,
    132                              'p': stat.S_IFIFO, 's': stat.S_IFSOCK,
    133                              '-': stat.S_IFREG,
     130        file_type_to_mode = {"b": stat.S_IFBLK, "c": stat.S_IFCHR,
     131                             "d": stat.S_IFDIR, "l": stat.S_IFLNK,
     132                             "p": stat.S_IFIFO, "s": stat.S_IFSOCK,
     133                             "-": stat.S_IFREG,
    134134                             # Ignore types which `ls` can't make sense of
    135135                             # (assuming the FTP server returns listings
    136136                             # like `ls` does).
    137                              '?': 0,
     137                             "?": 0,
    138138                            }
    139139        file_type = mode_string[0]
     
    187187        else:
    188188            # `year_or_time` is a time hh:mm.
    189             hour, minute = year_or_time.split(':')
     189            hour, minute = year_or_time.split(":")
    190190            year, hour, minute = None, int(hour), int(minute)
    191191            # Try the current year
     
    244244        # send a mail (see ftputil.txt/html).
    245245        try:
    246             month, day, year = [int(part) for part in date.split('-')]
     246            month, day, year = [int(part) for part in date.split("-")]
    247247            if year >= 1000:
    248248                # We have a four-digit year, so no need for heuristics.
     
    257257            raise ftputil.error.ParserError("invalid time string '{0}'".
    258258                                            format(time_))
    259         if hour == 12 and am_pm == 'A':
     259        if hour == 12 and am_pm == "A":
    260260            hour = 0
    261         if hour != 12 and am_pm == 'P':
     261        if hour != 12 and am_pm == "P":
    262262            hour = hour + 12
    263263        st_mtime = time.mktime( (year, month, day,
     
    337337            # name ends and the target name starts.
    338338            raise ftputil.error.ParserError(
    339                   'name "{0}" contains more than one "->"'.format(name))
     339                    '''name '{0}' contains more than one "->"'''.format(name))
    340340        elif name.count(" -> ") == 1:
    341             st_name, st_target = name.split(' -> ')
     341            st_name, st_target = name.split(" -> ")
    342342        else:
    343343            st_name, st_target = name, None
     
    509509        # the output of an FTP `LIST` command. Unfortunately, it is
    510510        # not possible to do this for the root directory `/`.
    511         if path == '/':
     511        if path == "/":
    512512            raise ftputil.error.RootDirError(
    513513                  "can't stat remote root directory")
  • ftputil/sync.py

    r1224 r1343  
    2222import ftputil.error
    2323
    24 __all__ = ['FTPHost', 'LocalHost', 'Syncer']
     24__all__ = ["FTPHost", "LocalHost", "Syncer"]
    2525
    2626
  • ftputil/version.py

    r1224 r1343  
    1212
    1313# ftputil version number; substituted by `make patch`
    14 __version__ = '2.8'
     14__version__ = "2.8"
    1515
    1616_ftputil_version = __version__
  • test/mock_ftplib.py

    r1307 r1343  
    9494    """
    9595    # Used by `MockSession.cwd` and `MockSession.pwd`
    96     current_dir = '/home/sschwarzer'
     96    current_dir = "/home/sschwarzer"
    9797
    9898    # Used by `MockSession.dir`. This is a mapping from absolute path
     
    102102
    103103    # File content to be used (indirectly) with `transfercmd`.
    104     mock_file_content = b''
    105 
    106     def __init__(self, host='', user='', password=''):
     104    mock_file_content = b""
     105
     106    def __init__(self, host="", user="", password=""):
    107107        self.closed = 0
    108108        # Count successful `transfercmd` invocations to ensure that
     
    115115        if DEBUG:
    116116            print(cmd)
    117         if cmd == 'STAT':
    118             return 'MockSession server awaiting your commands ;-)'
    119         elif cmd.startswith('TYPE '):
     117        if cmd == "STAT":
     118            return "MockSession server awaiting your commands ;-)"
     119        elif cmd.startswith("TYPE "):
    120120            return
    121         elif cmd.startswith('SITE CHMOD'):
     121        elif cmd.startswith("SITE CHMOD"):
    122122            raise ftplib.error_perm("502 command not implemented")
    123123        else:
     
    128128
    129129    def _remove_trailing_slash(self, path):
    130         if path != '/' and path.endswith('/'):
     130        if path != "/" and path.endswith("/"):
    131131            path = path[:-1]
    132132        return path
     
    163163        if path not in self.dir_contents:
    164164            raise ftplib.error_perm
    165         dir_lines = self.dir_contents[path].split('\n')
     165        dir_lines = self.dir_contents[path].split("\n")
    166166        for line in dir_lines:
    167167            if callback is None:
     
    173173        assert self._transfercmds == 1
    174174        self._transfercmds = self._transfercmds - 1
    175         return '2xx'
     175        return "2xx"
    176176
    177177    def transfercmd(self, cmd):
     
    190190        # Fail if path isn't available (this name is hard-coded here
    191191        # and has to be used for the corresponding tests).
    192         if (cmd, path) == ('RETR', 'notthere'):
     192        if (cmd, path) == ("RETR", "notthere"):
    193193            raise ftplib.error_perm
    194194        assert self._transfercmds == 0
     
    205205
    206206    dir_contents = {
    207       '/': """\
     207      "/": """\
    208208drwxr-xr-x   2 45854    200           512 May  4  2000 home""",
    209209
    210       '/home': """\
     210      "/home": """\
    211211drwxr-sr-x   2 45854    200           512 May  4  2000 sschwarzer
    212212-rw-r--r--   1 45854    200          4605 Jan 19  1970 older
     
    217217drwxr-sr-x   2 45854    200           512 May  4  2000 file_name_test""",
    218218
    219       '/home/python': """\
     219      "/home/python": """\
    220220lrwxrwxrwx   1 45854    200             7 Jan 19  2002 link_link -> ../link
    221221lrwxrwxrwx   1 45854    200            14 Jan 19  2002 bad_link -> /home/bad_link""",
    222222
    223       '/home/sschwarzer': """\
     223      "/home/sschwarzer": """\
    224224total 14
    225225drwxr-sr-x   2 45854    200           512 May  4  2000 chemeng
     
    233233drwxr-sr-x   6 45854    200           512 Sep 20  1999 scios2""",
    234234
    235       '/home/dir with spaces': """\
     235      "/home/dir with spaces": """\
    236236total 1
    237237-rw-r--r--   1 45854    200          4604 Jan 19 23:11 file with spaces""",
    238238
    239       '/home/file_name_test': """\
     239      "/home/file_name_test": """\
    240240drwxr-sr-x   2 45854    200           512 May 29  2000 ä
    241241drwxr-sr-x   2 45854    200           512 May 29  2000 empty_ä
     
    243243lrwxrwxrwx   2 45854    200             6 May 29  2000 ü -> ä""",
    244244
    245       '/home/file_name_test/ä': """\
     245      "/home/file_name_test/ä": """\
    246246-rw-r--r--   1 45854    200          4604 Jan 19 23:11 ö
    247247-rw-r--r--   1 45854    200          4604 Jan 19 23:11 o""",
    248248
    249       '/home/file_name_test/empty_ä': """\
     249      "/home/file_name_test/empty_ä": """\
    250250""",
    251251      # Fail when trying to write to this directory (the content isn't
    252252      # relevant).
    253       'sschwarzer': "",
     253      "sschwarzer": "",
    254254    }
    255255
     
    258258
    259259    dir_contents = {
    260       '/': """\
     260      "/": """\
    26126110-23-01  03:25PM       <DIR>          home""",
    262262
    263       '/home': """\
     263      "/home": """\
    26426410-23-01  03:25PM       <DIR>          msformat""",
    265265
    266       '/home/msformat': """\
     266      "/home/msformat": """\
    26726710-23-01  03:25PM       <DIR>          WindowsXP
    26826812-07-01  02:05PM       <DIR>          XPLaunch
     
    27027007-17-00  02:08PM                89264 O2KKeys.exe""",
    271271
    272       '/home/msformat/XPLaunch': """\
     272      "/home/msformat/XPLaunch": """\
    27327310-23-01  03:25PM       <DIR>          WindowsXP
    27427412-07-01  02:05PM       <DIR>          XPLaunch
     
    27727707-17-00  02:08PM                89264 O2KKeys.exe""",
    278278
    279       '/home/msformat/XPLaunch/empty': "total 0",
     279      "/home/msformat/XPLaunch/empty": "total 0",
    280280    }
  • test/test_base.py

    r1224 r1343  
    1 # Copyright (C) 2003-2012, Stefan Schwarzer <sschwarzer@sschwarzer.net>
     1# Copyright (C) 2003-2013, Stefan Schwarzer <sschwarzer@sschwarzer.net>
    22# See the file LICENSE for licensing terms.
    33
     
    1313def ftp_host_factory(session_factory=mock_ftplib.MockUnixFormatSession,
    1414                     ftp_host_class=ftputil.FTPHost):
    15     return ftp_host_class('dummy_host', 'dummy_user', 'dummy_password',
     15    return ftp_host_class("dummy_host", "dummy_user", "dummy_password",
    1616                          session_factory=session_factory)
  • test/test_error.py

    r1247 r1343  
    6464
    6565
    66 if __name__ == '__main__':
     66if __name__ == "__main__":
    6767    unittest.main()
  • test/test_file.py

    r1340 r1343  
    3535
    3636    def cwd(self, dir):
    37         if dir in (self._login_dir, self._login_dir + '/'):
     37        if dir in (self._login_dir, self._login_dir + "/"):
    3838            raise ftplib.error_perm
    3939        else:
     
    4949                 session_factory=InaccessibleDirSession)
    5050        self.assertRaises(ftputil.error.FTPIOError, host.open,
    51                           '/inaccessible/new_file', 'w')
     51                          "/inaccessible/new_file", "w")
    5252
    5353    def test_caching(self):
     
    5555        host = test_base.ftp_host_factory()
    5656        self.assertEqual(len(host._children), 0)
    57         path1 = 'path1'
    58         path2 = 'path2'
     57        path1 = "path1"
     58        path2 = "path2"
    5959        # Open one file and inspect cache.
    60         file1 = host.open(path1, 'w')
     60        file1 = host.open(path1, "w")
    6161        child1 = host._children[0]
    6262        self.assertEqual(len(host._children), 1)
    6363        self.assertFalse(child1._file.closed)
    6464        # Open another file.
    65         file2 = host.open(path2, 'w')
     65        file2 = host.open(path2, "w")
    6666        child2 = host._children[1]
    6767        self.assertEqual(len(host._children), 2)
     
    7373        self.assertFalse(child2._file.closed)
    7474        # Re-open first child's file.
    75         file1 = host.open(path1, 'w')
     75        file1 = host.open(path1, "w")
    7676        child1_1 = file1._host
    7777        # Check if it's reused.
     
    8787        host = test_base.ftp_host_factory()
    8888        self.assertRaises(ftputil.error.FTPIOError, host.open,
    89                           '/home/sschwarzer', 'w')
     89                          "/home/sschwarzer", "w")
    9090
    9191    def test_binary_read(self):
     
    137137        """Write ASCII text with `writelines`."""
    138138        host = test_base.ftp_host_factory()
    139         data = [' \n', 'line 2\n', 'line 3']
     139        data = [" \n", "line 2\n", "line 3"]
    140140        backup_data = data[:]
    141         output = host.open('dummy', 'w', newline="\r\n")
     141        output = host.open("dummy", "w", newline="\r\n")
    142142        output.writelines(data)
    143143        output.close()
    144         child_data = mock_ftplib.content_of('dummy')
    145         expected_data = b' \r\nline 2\r\nline 3'
     144        child_data = mock_ftplib.content_of("dummy")
     145        expected_data = b" \r\nline 2\r\nline 3"
    146146        self.assertEqual(child_data, expected_data)
    147147        # Ensure that the original data was not modified.
     
    151151        """Read binary data with `readline`."""
    152152        host = test_base.ftp_host_factory(session_factory=ReadMockSession)
    153         input_ = host.open('dummy', 'rb')
     153        input_ = host.open("dummy", "rb")
    154154        data = input_.readline(3)
    155         self.assertEqual(data, b'lin')
     155        self.assertEqual(data, b"lin")
    156156        data = input_.readline(10)
    157         self.assertEqual(data, b'e 1\r\n')
     157        self.assertEqual(data, b"e 1\r\n")
    158158        data = input_.readline(13)
    159         self.assertEqual(data, b'another line\r')
    160         data = input_.readline()
    161         self.assertEqual(data, b'\n')
    162         data = input_.readline()
    163         self.assertEqual(data, b'yet another line')
    164         data = input_.readline()
    165         self.assertEqual(data, b'')
     159        self.assertEqual(data, b"another line\r")
     160        data = input_.readline()
     161        self.assertEqual(data, b"\n")
     162        data = input_.readline()
     163        self.assertEqual(data, b"yet another line")
     164        data = input_.readline()
     165        self.assertEqual(data, b"")
    166166        input_.close()
    167167
     
    169169        """Read ASCII text with `readline`."""
    170170        host = test_base.ftp_host_factory(session_factory=ReadMockSession)
    171         input_ = host.open('dummy', 'r')
     171        input_ = host.open("dummy", "r")
    172172        data = input_.readline(3)
    173         self.assertEqual(data, 'lin')
     173        self.assertEqual(data, "lin")
    174174        data = input_.readline(10)
    175         self.assertEqual(data, 'e 1\n')
     175        self.assertEqual(data, "e 1\n")
    176176        data = input_.readline(13)
    177         self.assertEqual(data, 'another line\n')
    178         data = input_.readline()
    179         self.assertEqual(data, 'yet another line')
    180         data = input_.readline()
    181         self.assertEqual(data, '')
     177        self.assertEqual(data, "another line\n")
     178        data = input_.readline()
     179        self.assertEqual(data, "yet another line")
     180        data = input_.readline()
     181        self.assertEqual(data, "")
    182182        input_.close()
    183183
     
    185185        """Read ASCII text with `readlines`."""
    186186        host = test_base.ftp_host_factory(session_factory=ReadMockSession)
    187         input_ = host.open('dummy', 'r')
     187        input_ = host.open("dummy", "r")
    188188        data = input_.read(3)
    189         self.assertEqual(data, 'lin')
     189        self.assertEqual(data, "lin")
    190190        data = input_.readlines()
    191         self.assertEqual(data, ['e 1\n', 'another line\n',
    192                                 'yet another line'])
     191        self.assertEqual(data, ["e 1\n", "another line\n",
     192                                "yet another line"])
    193193        input_.close()
    194194
     
    199199        """
    200200        host = test_base.ftp_host_factory(session_factory=ReadMockSession)
    201         input_ = host.open('dummy', 'rb')
     201        input_ = host.open("dummy", "rb")
    202202        input_iterator = iter(input_)
    203203        self.assertEqual(next(input_iterator), b"line 1\r\n")
     
    213213        """
    214214        host = test_base.ftp_host_factory(session_factory=ReadMockSession)
    215         input_ = host.open('dummy')
     215        input_ = host.open("dummy")
    216216        input_iterator = iter(input_)
    217217        self.assertEqual(next(input_iterator), "line 1\n")
     
    224224        """Test whether reading a file which isn't there fails."""
    225225        host = test_base.ftp_host_factory()
    226         self.assertRaises(ftputil.error.FTPIOError, host.open, 'notthere', 'r')
    227 
    228 
    229 if __name__ == '__main__':
     226        self.assertRaises(ftputil.error.FTPIOError, host.open, "notthere", "r")
     227
     228
     229if __name__ == "__main__":
    230230    unittest.main()
  • test/test_file_transfer.py

    r1269 r1343  
    113113
    114114
    115 if __name__ == '__main__':
     115if __name__ == "__main__":
    116116    unittest.main()
  • test/test_host.py

    r1331 r1343  
    5656class FailOnLoginSession(mock_ftplib.MockSession):
    5757
    58     def __init__(self, host='', user='', password=''):
     58    def __init__(self, host="", user="", password=""):
    5959        raise ftplib.error_perm
    6060
     
    119119class FailingUploadAndDownloadFTPHost(ftputil.FTPHost):
    120120
    121     def upload(self, source, target, mode=''):
     121    def upload(self, source, target, mode=""):
    122122        assert False, "`FTPHost.upload` should not have been called"
    123123
    124     def download(self, source, target, mode=''):
     124    def download(self, source, target, mode=""):
    125125        assert False, "`FTPHost.download` should not have been called"
    126126
     
    262262                 session_factory=RecursiveListingForDotAsPathSession)
    263263        files = host.listdir(host.curdir)
    264         self.assertEqual(files, ['bin', 'dev', 'etc', 'pub', 'usr'])
     264        self.assertEqual(files, ["bin", "dev", "etc", "pub", "usr"])
    265265        host.close()
    266266
     
    276276    def test_ascii_upload(self):
    277277        """Test ASCII mode upload."""
    278         local_source = '_test_source_'
     278        local_source = "_test_source_"
    279279        data = ascii_data()
    280280        self.generate_ascii_file(data, local_source)
    281281        # Upload.
    282282        host = test_base.ftp_host_factory()
    283         host.upload(local_source, 'dummy')
     283        host.upload(local_source, "dummy")
    284284        # Check uploaded content. The data which was uploaded has its
    285285        # line endings converted so the conversion must also be
    286286        # applied to `data`.
    287         remote_file_content = mock_ftplib.content_of('dummy')
     287        remote_file_content = mock_ftplib.content_of("dummy")
    288288        self.assertEqual(ftputil.tool.as_bytes(data.replace("\r", os.linesep)),
    289289                         remote_file_content)
     
    293293    def test_binary_download(self):
    294294        """Test binary mode download."""
    295         local_target = '__test_target'
     295        local_target = "_test_target_"
    296296        host = test_base.ftp_host_factory(
    297297                 session_factory=BinaryDownloadMockSession)
    298298        # Download
    299         host.download('dummy', local_target, 'b')
     299        host.download("dummy", local_target, "b")
    300300        # Read file and compare
    301         with open(local_target, 'rb') as fobj:
     301        with open(local_target, "rb") as fobj:
    302302            data = fobj.read()
    303         remote_file_content = mock_ftplib.content_of('dummy')
     303        remote_file_content = mock_ftplib.content_of("dummy")
    304304        self.assertEqual(data, remote_file_content)
    305305        # Clean up
     
    308308    def test_conditional_upload(self):
    309309        """Test conditional ASCII mode upload."""
    310         local_source = '__test_source'
     310        local_source = "_test_source_"
    311311        data = ascii_data()
    312312        self.generate_ascii_file(data, local_source)
     
    314314        host = test_base.ftp_host_factory(
    315315                 ftp_host_class=FailingUploadAndDownloadFTPHost)
    316         flag = host.upload_if_newer(local_source, '/home/newer')
     316        flag = host.upload_if_newer(local_source, "/home/newer")
    317317        self.assertEqual(flag, False)
    318318        # Target is older, so upload.
    319319        host = test_base.ftp_host_factory()
    320         flag = host.upload_if_newer(local_source, '/home/older')
     320        flag = host.upload_if_newer(local_source, "/home/older")
    321321        self.assertEqual(flag, True)
    322322        # Check uploaded content. The data which was uploaded has its
    323323        # line endings converted so the conversion must also be
    324         # applied to 'data'.
    325         remote_file_content = mock_ftplib.content_of('older')
     324        # applied to `data`.
     325        remote_file_content = mock_ftplib.content_of("older")
    326326        self.assertEqual(ftputil.tool.as_bytes(data.replace("\r", os.linesep)),
    327327                         remote_file_content)
    328328        # Target doesn't exist, so upload.
    329329        host = test_base.ftp_host_factory()
    330         flag = host.upload_if_newer(local_source, '/home/notthere')
     330        flag = host.upload_if_newer(local_source, "/home/notthere")
    331331        self.assertEqual(flag, True)
    332         remote_file_content = mock_ftplib.content_of('notthere')
     332        remote_file_content = mock_ftplib.content_of("notthere")
    333333        self.assertEqual(ftputil.tool.as_bytes(data.replace("\r", os.linesep)),
    334334                         remote_file_content)
     
    341341        delete the local target file.
    342342        """
    343         with open(filename, 'rb') as fobj:
     343        with open(filename, "rb") as fobj:
    344344            data = fobj.read()
    345345        # The name `newer` is used by all callers, so use it here, too.
    346         remote_file_content = mock_ftplib.content_of('newer')
     346        remote_file_content = mock_ftplib.content_of("newer")
    347347        self.assertEqual(data, remote_file_content)
    348348        # Clean up
     
    354354        exists.
    355355        """
    356         local_target = '__test_target'
     356        local_target = "__test_target"
    357357        # Target does not exist, so download.
    358358        host = test_base.ftp_host_factory(
    359359                 session_factory=BinaryDownloadMockSession)
    360         flag = host.download_if_newer('/home/newer', local_target, 'b')
     360        flag = host.download_if_newer("/home/newer", local_target, "b")
    361361        self.assertEqual(flag, True)
    362362        self.compare_and_delete_downloaded_data(local_target)
     
    364364    def test_conditional_download_with_older_target(self):
    365365        """Test conditional binary mode download with newer source file."""
    366         local_target = '__test_target'
     366        local_target = "__test_target"
    367367        # Make target file.
    368         open(local_target, 'w').close()
     368        open(local_target, "w").close()
    369369        # Source is newer (date in 2020), so download.
    370370        host = test_base.ftp_host_factory(
    371371                 session_factory=BinaryDownloadMockSession)
    372         flag = host.download_if_newer('/home/newer', local_target, 'b')
     372        flag = host.download_if_newer("/home/newer", local_target, "b")
    373373        self.assertEqual(flag, True)
    374374        self.compare_and_delete_downloaded_data(local_target)
     
    376376    def test_conditional_download_with_newer_target(self):
    377377        """Test conditional binary mode download with older source file."""
    378         local_target = '__test_target'
     378        local_target = "__test_target"
    379379        # Make target file.
    380         open(local_target, 'w').close()
     380        open(local_target, "w").close()
    381381        # Source is older (date in 1970), so don't download.
    382382        host = test_base.ftp_host_factory(
    383383                 ftp_host_class=FailingUploadAndDownloadFTPHost,
    384384                 session_factory=BinaryDownloadMockSession)
    385         flag = host.download_if_newer('/home/older', local_target, 'b')
     385        flag = host.download_if_newer("/home/older", local_target, "b")
    386386        self.assertEqual(flag, False)
    387387        # Remove target file
     
    589589
    590590
    591 if __name__ == '__main__':
     591if __name__ == "__main__":
    592592    unittest.main()
    593593    import __main__
  • test/test_path.py

    r1290 r1343  
    3838        """Test regular `FTPHost._Path.isdir/isfile/islink`."""
    3939        host = test_base.ftp_host_factory()
    40         testdir = '/home/sschwarzer'
     40        testdir = "/home/sschwarzer"
    4141        host.chdir(testdir)
    4242        # Test a path which isn't there.
    43         self.assertFalse(host.path.isdir ('notthere'))
    44         self.assertFalse(host.path.isfile('notthere'))
    45         self.assertFalse(host.path.islink('notthere'))
     43        self.assertFalse(host.path.isdir ("notthere"))
     44        self.assertFalse(host.path.isfile("notthere"))
     45        self.assertFalse(host.path.islink("notthere"))
    4646        #  This checks additional code (see ticket #66).
    47         self.assertFalse(host.path.isdir ('/notthere/notthere'))
    48         self.assertFalse(host.path.isfile('/notthere/notthere'))
    49         self.assertFalse(host.path.islink('/notthere/notthere'))
     47        self.assertFalse(host.path.isdir ("/notthere/notthere"))
     48        self.assertFalse(host.path.isfile("/notthere/notthere"))
     49        self.assertFalse(host.path.islink("/notthere/notthere"))
    5050        # Test a directory.
    5151        self.assertTrue (host.path.isdir (testdir))
     
    5353        self.assertFalse(host.path.islink(testdir))
    5454        # Test a file.
    55         testfile = '/home/sschwarzer/index.html'
     55        testfile = "/home/sschwarzer/index.html"
    5656        self.assertFalse(host.path.isdir (testfile))
    5757        self.assertTrue (host.path.isfile(testfile))
     
    5959        # Test a link. Since the link target of `osup` doesn't exist,
    6060        # neither `isdir` nor `isfile` return `True`.
    61         testlink = '/home/sschwarzer/osup'
     61        testlink = "/home/sschwarzer/osup"
    6262        self.assertFalse(host.path.isdir (testlink))
    6363        self.assertFalse(host.path.isfile(testlink))
     
    6767        """Test whether the workaround for space-containing paths is used."""
    6868        host = test_base.ftp_host_factory()
    69         testdir = '/home/sschwarzer'
     69        testdir = "/home/sschwarzer"
    7070        host.chdir(testdir)
    7171        # Test a file name containing spaces.
    72         testfile = '/home/dir with spaces/file with spaces'
     72        testfile = "/home/dir with spaces/file with spaces"
    7373        self.assertFalse(host.path.isdir (testfile))
    7474        self.assertTrue (host.path.isfile(testfile))
     
    8080               session_factory=SessionWithInaccessibleLoginDirectory)
    8181        self.assertRaises(ftputil.error.InaccessibleLoginDirError,
    82                           host._dir, '/home dir')
     82                          host._dir, "/home dir")
    8383
    8484    def test_isdir_isfile_islink_with_exception(self):
    8585        """Test failing `FTPHost._Path.isdir/isfile/islink`."""
    8686        host = test_base.ftp_host_factory(ftp_host_class=FailingFTPHost)
    87         testdir = '/home/sschwarzer'
     87        testdir = "/home/sschwarzer"
    8888        host.chdir(testdir)
    8989        # Test if exceptions are propagated.
     
    9797        # Regular use of `exists`
    9898        host = test_base.ftp_host_factory()
    99         testdir = '/home/sschwarzer'
     99        testdir = "/home/sschwarzer"
    100100        host.chdir(testdir)
    101101        self.assertTrue (host.path.exists("index.html"))
     
    212212
    213213
    214 if __name__ == '__main__':
     214if __name__ == "__main__":
    215215    unittest.main()
  • test/test_public_servers.py

    r1286 r1343  
    174174
    175175
    176 if __name__ == '__main__':
     176if __name__ == "__main__":
    177177    unittest.main()
  • test/test_real_ftp.py

    r1333 r1343  
    3737    #password = getpass.getpass()
    3838    #return server, user, password
    39     return "localhost", 'ftptest', 'd605581757de5eb56d568a4419f4126e'
     39    return "localhost", "ftptest", "d605581757de5eb56d568a4419f4126e"
    4040
    4141
     
    8080    def add_dir(self, path):
    8181        """Schedule a directory with path `path` for removal."""
    82         self._ftp_items.append(('d', self._host.path.abspath(path)))
     82        self._ftp_items.append(("d", self._host.path.abspath(path)))
    8383
    8484    def add_file(self, path):
    8585        """Schedule a file with path `path` for removal."""
    86         self._ftp_items.append(('f', self._host.path.abspath(path)))
     86        self._ftp_items.append(("f", self._host.path.abspath(path)))
    8787
    8888    def clean(self):
     
    9797        for type_, path in reversed(self._ftp_items):
    9898            try:
    99                 if type_ == 'd':
     99                if type_ == "d":
    100100                    # If something goes wrong in `rmtree` we might
    101101                    # leave a mess behind.
    102102                    self._host.rmtree(path)
    103                 elif type_ == 'f':
     103                elif type_ == "f":
    104104                    # Minor mess if `remove` fails
    105105                    self._host.remove(path)
     
    124124        """Create a file on the FTP host."""
    125125        self.cleaner.add_file(path)
    126         file_ = self.host.open(path, 'wb')
     126        file_ = self.host.open(path, "wb")
    127127        # Write something. Otherwise the FTP server might not update
    128128        # the time of last modification if the file existed before.
     
    132132    def make_local_file(self):
    133133        """Create a file on the local host (= on the client side)."""
    134         fobj = open('_local_file_', 'wb')
     134        fobj = open("_local_file_", "wb")
    135135        fobj.write(b"abc\x12\x34def\t")
    136136        fobj.close()
     
    173173        host = self.host
    174174        # No `_dir1_` yet
    175         self.assertFalse('_dir1_' in host.listdir(host.curdir))
     175        self.assertFalse("_dir1_" in host.listdir(host.curdir))
    176176        # Vanilla case, all should go well.
    177         host.makedirs('_dir1_/dir2/dir3/dir4')
    178         self.cleaner.add_dir('_dir1_')
     177        host.makedirs("_dir1_/dir2/dir3/dir4")
     178        self.cleaner.add_dir("_dir1_")
    179179        # Check host.
    180         self.assertTrue(host.path.isdir('_dir1_'))
    181         self.assertTrue(host.path.isdir('_dir1_/dir2'))
    182         self.assertTrue(host.path.isdir('_dir1_/dir2/dir3'))
    183         self.assertTrue(host.path.isdir('_dir1_/dir2/dir3/dir4'))
     180        self.assertTrue(host.path.isdir("_dir1_"))
     181        self.assertTrue(host.path.isdir("_dir1_/dir2"))
     182        self.assertTrue(host.path.isdir("_dir1_/dir2/dir3"))
     183        self.assertTrue(host.path.isdir("_dir1_/dir2/dir3/dir4"))
    184184
    185185    def test_makedirs_from_non_root_directory(self):
     
    188188        host = self.host
    189189        # No `_dir1_` and `_dir2_` yet
    190         self.assertFalse('_dir1_' in host.listdir(host.curdir))
    191         self.assertFalse('_dir2_' in host.listdir(host.curdir))
     190        self.assertFalse("_dir1_" in host.listdir(host.curdir))
     191        self.assertFalse("_dir2_" in host.listdir(host.curdir))
    192192        # Part 1: Try to make directories starting from `_dir1_` and
    193193        # change to non-root directory.
    194194        self.cleaner.add_dir("_dir1_")
    195         host.mkdir('_dir1_')
    196         host.chdir('_dir1_')
    197         host.makedirs('_dir2_/_dir3_')
     195        host.mkdir("_dir1_")
     196        host.chdir("_dir1_")
     197        host.makedirs("_dir2_/_dir3_")
    198198        # Test for expected directory hierarchy.
    199         self.assertTrue (host.path.isdir('/_dir1_'))
    200         self.assertTrue (host.path.isdir('/_dir1_/_dir2_'))
    201         self.assertTrue (host.path.isdir('/_dir1_/_dir2_/_dir3_'))
    202         self.assertFalse(host.path.isdir('/_dir1_/_dir1_'))
     199        self.assertTrue (host.path.isdir("/_dir1_"))
     200        self.assertTrue (host.path.isdir("/_dir1_/_dir2_"))
     201        self.assertTrue (host.path.isdir("/_dir1_/_dir2_/_dir3_"))
     202        self.assertFalse(host.path.isdir("/_dir1_/_dir1_"))
    203203        # Remove all but the directory we're in.
    204         host.rmdir('/_dir1_/_dir2_/_dir3_')
    205         host.rmdir('/_dir1_/_dir2_')
     204        host.rmdir("/_dir1_/_dir2_/_dir3_")
     205        host.rmdir("/_dir1_/_dir2_")
    206206        # Part 2: Try to make directories starting from root.
    207207        self.cleaner.add_dir("/_dir2_")
    208         host.makedirs('/_dir2_/_dir3_')
     208        host.makedirs("/_dir2_/_dir3_")
    209209        # Test for expected directory hierarchy
    210         self.assertTrue (host.path.isdir('/_dir2_'))
    211         self.assertTrue (host.path.isdir('/_dir2_/_dir3_'))
    212         self.assertFalse(host.path.isdir('/_dir1_/_dir2_'))
     210        self.assertTrue (host.path.isdir("/_dir2_"))
     211        self.assertTrue (host.path.isdir("/_dir2_/_dir3_"))
     212        self.assertFalse(host.path.isdir("/_dir1_/_dir2_"))
    213213
    214214    def test_makedirs_of_existing_directory(self):
    215215        host = self.host
    216216        # The (chrooted) login directory
    217         host.makedirs('/')
     217        host.makedirs("/")
    218218
    219219    def test_makedirs_with_file_in_the_way(self):
    220220        host = self.host
    221         self.cleaner.add_dir('_dir1_')
    222         host.mkdir('_dir1_')
    223         self.make_remote_file('_dir1_/file1')
     221        self.cleaner.add_dir("_dir1_")
     222        host.mkdir("_dir1_")
     223        self.make_remote_file("_dir1_/file1")
    224224        # Try it.
    225225        self.assertRaises(ftputil.error.PermanentError,
    226                           host.makedirs, '_dir1_/file1')
     226                          host.makedirs, "_dir1_/file1")
    227227        self.assertRaises(ftputil.error.PermanentError,
    228                           host.makedirs, '_dir1_/file1/dir2')
     228                          host.makedirs, "_dir1_/file1/dir2")
    229229
    230230    def test_makedirs_with_existing_directory(self):
    231231        host = self.host
    232232        self.cleaner.add_dir("_dir1_")
    233         host.mkdir('_dir1_')
    234         host.makedirs('_dir1_/dir2')
     233        host.mkdir("_dir1_")
     234        host.makedirs("_dir1_/dir2")
    235235        # Check
    236         self.assertTrue(host.path.isdir('_dir1_'))
    237         self.assertTrue(host.path.isdir('_dir1_/dir2'))
     236        self.assertTrue(host.path.isdir("_dir1_"))
     237        self.assertTrue(host.path.isdir("_dir1_/dir2"))
    238238
    239239    def test_makedirs_in_non_writable_directory(self):
     
    241241        # Preparation: `rootdir1` exists but is only writable by root.
    242242        self.assertRaises(ftputil.error.PermanentError, host.makedirs,
    243                           'rootdir1/dir2')
     243                          "rootdir1/dir2")
    244244
    245245    def test_makedirs_with_writable_directory_at_end(self):
    246246        host = self.host
    247         self.cleaner.add_dir('rootdir2/dir2')
     247        self.cleaner.add_dir("rootdir2/dir2")
    248248        # Preparation: `rootdir2` exists but is only writable by root.
    249249        # `dir2` is writable by regular ftp user. These both should work.
    250         host.makedirs('rootdir2/dir2')
    251         host.makedirs('rootdir2/dir2/dir3')
     250        host.makedirs("rootdir2/dir2")
     251        host.makedirs("rootdir2/dir2/dir3")
    252252
    253253
     
    257257        host = self.host
    258258        # Build a tree.
    259         self.cleaner.add_dir('_dir1_')
    260         host.makedirs('_dir1_/dir2')
    261         self.make_remote_file('_dir1_/file1')
    262         self.make_remote_file('_dir1_/file2')
    263         self.make_remote_file('_dir1_/dir2/file3')
    264         self.make_remote_file('_dir1_/dir2/file4')
     259        self.cleaner.add_dir("_dir1_")
     260        host.makedirs("_dir1_/dir2")
     261        self.make_remote_file("_dir1_/file1")
     262        self.make_remote_file("_dir1_/file2")
     263        self.make_remote_file("_dir1_/dir2/file3")
     264        self.make_remote_file("_dir1_/dir2/file4")
    265265        # Try to remove a _file_ with `rmtree`.
    266266        self.assertRaises(ftputil.error.PermanentError, host.rmtree,
    267                           '_dir1_/file2')
     267                          "_dir1_/file2")
    268268        # Remove `dir2`.
    269         host.rmtree('_dir1_/dir2')
    270         self.assertFalse(host.path.exists('_dir1_/dir2'))
    271         self.assertTrue (host.path.exists('_dir1_/file2'))
     269        host.rmtree("_dir1_/dir2")
     270        self.assertFalse(host.path.exists("_dir1_/dir2"))
     271        self.assertTrue (host.path.exists("_dir1_/file2"))
    272272        # Re-create `dir2` and remove `_dir1_`.
    273         host.mkdir('_dir1_/dir2')
    274         self.make_remote_file('_dir1_/dir2/file3')
    275         self.make_remote_file('_dir1_/dir2/file4')
    276         host.rmtree('_dir1_')
    277         self.assertFalse(host.path.exists('_dir1_'))
     273        host.mkdir("_dir1_/dir2")
     274        self.make_remote_file("_dir1_/dir2/file3")
     275        self.make_remote_file("_dir1_/dir2/file4")
     276        host.rmtree("_dir1_")
     277        self.assertFalse(host.path.exists("_dir1_"))
    278278
    279279    def test_rmtree_with_error_handler(self):
    280280        host = self.host
    281         self.cleaner.add_dir('_dir1_')
    282         host.mkdir('_dir1_')
    283         self.make_remote_file('_dir1_/file1')
     281        self.cleaner.add_dir("_dir1_")
     282        host.mkdir("_dir1_")
     283        self.make_remote_file("_dir1_/file1")
    284284        # Prepare error "handler"
    285285        log = []
     
    287287            log.append(args)
    288288        # Try to remove a file as root "directory".
    289         host.rmtree('_dir1_/file1', ignore_errors=True, onerror=error_handler)
     289        host.rmtree("_dir1_/file1", ignore_errors=True, onerror=error_handler)
    290290        self.assertEqual(log, [])
    291         host.rmtree('_dir1_/file1', ignore_errors=False, onerror=error_handler)
     291        host.rmtree("_dir1_/file1", ignore_errors=False, onerror=error_handler)
    292292        self.assertEqual(log[0][0], host.listdir)
    293         self.assertEqual(log[0][1], '_dir1_/file1')
     293        self.assertEqual(log[0][1], "_dir1_/file1")
    294294        self.assertEqual(log[1][0], host.rmdir)
    295         self.assertEqual(log[1][1], '_dir1_/file1')
    296         host.rmtree('_dir1_')
     295        self.assertEqual(log[1][1], "_dir1_/file1")
     296        host.rmtree("_dir1_")
    297297        # Try to remove a non-existent directory.
    298298        del log[:]
    299         host.rmtree('_dir1_', ignore_errors=False, onerror=error_handler)
     299        host.rmtree("_dir1_", ignore_errors=False, onerror=error_handler)
    300300        self.assertEqual(log[0][0], host.listdir)
    301         self.assertEqual(log[0][1], '_dir1_')
     301        self.assertEqual(log[0][1], "_dir1_")
    302302        self.assertEqual(log[1][0], host.rmdir)
    303         self.assertEqual(log[1][1], '_dir1_')
     303        self.assertEqual(log[1][1], "_dir1_")
    304304
    305305    def test_remove_non_existent_item(self):
     
    309309
    310310    def test_remove_existing_file(self):
    311         self.cleaner.add_file('_testfile_')
    312         self.make_remote_file('_testfile_')
    313         host = self.host
    314         self.assertTrue(host.path.isfile('_testfile_'))
    315         host.remove('_testfile_')
    316         self.assertFalse(host.path.exists('_testfile_'))
     311        self.cleaner.add_file("_testfile_")
     312        self.make_remote_file("_testfile_")
     313        host = self.host
     314        self.assertTrue(host.path.isfile("_testfile_"))
     315        host.remove("_testfile_")
     316        self.assertFalse(host.path.exists("_testfile_"))
    317317
    318318
     
    323323        host = self.host
    324324        expected = [
    325           ('walk_test',
    326            ['dir1', 'dir2', 'dir3'],
    327            ['file4']),
    328 
    329           ('walk_test/dir1',
    330            ['dir11', 'dir12'],
     325          ("walk_test",
     326           ["dir1", "dir2", "dir3"],
     327           ["file4"]),
     328
     329          ("walk_test/dir1",
     330           ["dir11", "dir12"],
    331331           []),
    332332
    333           ('walk_test/dir1/dir11',
     333          ("walk_test/dir1/dir11",
    334334           [],
    335335           []),
    336336
    337           ('walk_test/dir1/dir12',
    338            ['dir123'],
    339            ['file121', 'file122']),
    340 
    341           ('walk_test/dir1/dir12/dir123',
     337          ("walk_test/dir1/dir12",
     338           ["dir123"],
     339           ["file121", "file122"]),
     340
     341          ("walk_test/dir1/dir12/dir123",
    342342           [],
    343            ['file1234']),
    344 
    345           ('walk_test/dir2',
     343           ["file1234"]),
     344
     345          ("walk_test/dir2",
    346346           [],
    347347           []),
    348348
    349           ('walk_test/dir3',
    350            ['dir33'],
    351            ['file31', 'file32']),
    352 
    353           ('walk_test/dir3/dir33',
     349          ("walk_test/dir3",
     350           ["dir33"],
     351           ["file31", "file32"]),
     352
     353          ("walk_test/dir3/dir33",
    354354           [],
    355355           []),
     
    357357        # Collect data using `walk`.
    358358        actual = []
    359         for items in host.walk('walk_test'):
     359        for items in host.walk("walk_test"):
    360360            actual.append(items)
    361361        # Compare with expected results.
     
    368368        host = self.host
    369369        expected = [
    370           ('walk_test/dir1/dir11',
     370          ("walk_test/dir1/dir11",
    371371           [],
    372372           []),
    373373
    374           ('walk_test/dir1/dir12/dir123',
     374          ("walk_test/dir1/dir12/dir123",
    375375           [],
    376            ['file1234']),
    377 
    378           ('walk_test/dir1/dir12',
    379            ['dir123'],
    380            ['file121', 'file122']),
    381 
    382           ('walk_test/dir1',
    383            ['dir11', 'dir12'],
     376           ["file1234"]),
     377
     378          ("walk_test/dir1/dir12",
     379           ["dir123"],
     380           ["file121", "file122"]),
     381
     382          ("walk_test/dir1",
     383           ["dir11", "dir12"],
    384384           []),
    385385
    386           ('walk_test/dir2',
     386          ("walk_test/dir2",
    387387           [],
    388388           []),
    389389
    390           ('walk_test/dir3/dir33',
     390          ("walk_test/dir3/dir33",
    391391           [],
    392392           []),
    393393
    394           ('walk_test/dir3',
    395            ['dir33'],
    396            ['file31', 'file32']),
    397 
    398           ('walk_test',
    399            ['dir1', 'dir2', 'dir3'],
    400            ['file4'])
     394          ("walk_test/dir3",
     395           ["dir33"],
     396           ["file31", "file32"]),
     397
     398          ("walk_test",
     399           ["dir1", "dir2", "dir3"],
     400           ["file4"])
    401401          ]
    402402        # Collect data using `walk`.
    403403        actual = []
    404         for items in host.walk('walk_test', topdown=False):
     404        for items in host.walk("walk_test", topdown=False):
    405405            actual.append(items)
    406406        # Compare with expected results.
     
    415415        host = self.host
    416416        # Make sure the target of the renaming operation is removed.
    417         self.cleaner.add_file('_testfile2_')
     417        self.cleaner.add_file("_testfile2_")
    418418        self.make_remote_file("_testfile1_")
    419         host.rename('_testfile1_', '_testfile2_')
    420         self.assertFalse(host.path.exists('_testfile1_'))
    421         self.assertTrue (host.path.exists('_testfile2_'))
     419        host.rename("_testfile1_", "_testfile2_")
     420        self.assertFalse(host.path.exists("_testfile1_"))
     421        self.assertTrue (host.path.exists("_testfile2_"))
    422422
    423423    def test_rename_with_spaces_in_directory(self):
     
    538538        host = self.host
    539539        host.synchronize_times()
    540         local_file = '_local_file_'
    541         remote_file = '_remote_file_'
     540        local_file = "_local_file_"
     541        remote_file = "_remote_file_"
    542542        # Make local file to upload.
    543543        self.make_local_file()
     
    547547        try:
    548548            self.cleaner.add_file(remote_file)
    549             host.upload(local_file, remote_file, 'b')
     549            host.upload(local_file, remote_file, "b")
    550550            # Retry; shouldn't be uploaded
    551             uploaded = host.upload_if_newer(local_file, remote_file, 'b')
     551            uploaded = host.upload_if_newer(local_file, remote_file, "b")
    552552            self.assertEqual(uploaded, False)
    553553            # Rewrite the local file.
    554554            self.make_local_file()
    555555            # Retry; should be uploaded now
    556             uploaded = host.upload_if_newer(local_file, remote_file, 'b')
     556            uploaded = host.upload_if_newer(local_file, remote_file, "b")
    557557            self.assertEqual(uploaded, True)
    558558        finally:
     
    563563        host = self.host
    564564        host.synchronize_times()
    565         local_file = '_local_file_'
    566         remote_file = '_remote_file_'
     565        local_file = "_local_file_"
     566        remote_file = "_remote_file_"
    567567        # Make a remote file.
    568568        self.make_remote_file(remote_file)
    569569        # File should be downloaded as it's not present yet.
    570         downloaded = host.download_if_newer(remote_file, local_file, 'b')
     570        downloaded = host.download_if_newer(remote_file, local_file, "b")
    571571        self.assertEqual(downloaded, True)
    572572        try:
     
    579579            fobj.close()
    580580            # Local file is present and newer, so shouldn't download.
    581             downloaded = host.download_if_newer(remote_file, local_file, 'b')
     581            downloaded = host.download_if_newer(remote_file, local_file, "b")
    582582            self.assertEqual(downloaded, False)
    583583            # Re-make the remote file.
     
    586586            # possible deviation because of the precision into account),
    587587            # so should download.
    588             downloaded = host.download_if_newer(remote_file, local_file, 'b')
     588            downloaded = host.download_if_newer(remote_file, local_file, "b")
    589589            self.assertEqual(downloaded, True)
    590590        finally:
     
    606606            transferred_chunks_list.append(chunk)
    607607        try:
    608             host.download(FILENAME, FILENAME, 'b', callback=test_callback)
     608            host.download(FILENAME, FILENAME, "b", callback=test_callback)
    609609            # Construct a list of data chunks we expect.
    610610            expected_chunks_list = []
     
    627627        REMOTE_FILENAME = "debian-keyring.tar.gz"
    628628        host = self.host
    629         file_obj1 = host.open(REMOTE_FILENAME, 'rb')
    630         file_obj2 = host.open(REMOTE_FILENAME, 'rb')
     629        file_obj1 = host.open(REMOTE_FILENAME, "rb")
     630        file_obj2 = host.open(REMOTE_FILENAME, "rb")
    631631        file_obj2.close()
    632632        # This should re-use the second child because the first isn't
    633633        # closed but the second is.
    634         file_obj = host.open(REMOTE_FILENAME, 'rb')
     634        file_obj = host.open(REMOTE_FILENAME, "rb")
    635635        self.assertEqual(len(host._children), 2)
    636636        self.assertTrue(file_obj._host is host._children[1])
     
    640640        REMOTE_FILENAME = "debian-keyring.tar.gz"
    641641        host = self.host
    642         file_obj1 = host.open(REMOTE_FILENAME, 'rb')
     642        file_obj1 = host.open(REMOTE_FILENAME, "rb")
    643643        file_obj1.close()
    644644        # Monkey-patch file to simulate an FTP server timeout below.
     
    647647        file_obj1._host._session.pwd = timed_out_pwd
    648648        # Try to get a file - which shouldn't be the timed-out file.
    649         file_obj2 = host.open(REMOTE_FILENAME, 'rb')
     649        file_obj2 = host.open(REMOTE_FILENAME, "rb")
    650650        self.assertTrue(file_obj1 is not file_obj2)
    651651        # Re-use closed and not timed-out child session.
    652652        file_obj2.close()
    653         file_obj3 = host.open(REMOTE_FILENAME, 'rb')
     653        file_obj3 = host.open(REMOTE_FILENAME, "rb")
    654654        file_obj3.close()
    655655        self.assertTrue(file_obj2 is file_obj3)
     
    731731        # http://ftputil.sschwarzer.net/trac/ticket/17 and
    732732        # http://ftputil.sschwarzer.net/trac/ticket/51 .
    733         file1 = self.host.open("debian-keyring.tar.gz", 'rb')
     733        file1 = self.host.open("debian-keyring.tar.gz", "rb")
    734734        time.sleep(1)
    735735        # Depending on the FTP server, this might return a status code
     
    740740    def test_subsequent_reading(self):
    741741        # Opening a file for reading
    742         file1 = self.host.open("debian-keyring.tar.gz", 'rb')
     742        file1 = self.host.open("debian-keyring.tar.gz", "rb")
    743743        file1.close()
    744744        # Make sure that there are no problems if the connection is reused.
    745         file2 = self.host.open("debian-keyring.tar.gz", 'rb')
     745        file2 = self.host.open("debian-keyring.tar.gz", "rb")
    746746        file2.close()
    747747        self.assertTrue(file1._session is file2._session)
     
    753753        self.assertTrue(host.path.isdir("dir with spaces"))
    754754        self.assertEqual(host.listdir("dir with spaces"),
    755                          ['second dir', 'some file', 'some_file'])
     755                         ["second dir", "some file", "some_file"])
    756756        self.assertTrue(host.path.isdir ("dir with spaces/second dir"))
    757757        self.assertTrue(host.path.isfile("dir with spaces/some_file"))
     
    795795
    796796
    797 if __name__ == '__main__':
     797if __name__ == "__main__":
    798798    print("""\
    799799Test real FTP access.
  • test/test_stat.py

    r1259 r1343  
    9393          ]
    9494        expected_stat_results = [
    95           [17901, None, None, 2, '45854', '200', 512, None,
     95          [17901, None, None, 2, "45854", "200", 512, None,
    9696           (2000, 5, 4, 0, 0, 0), None, "chemeng link", "chemeng target"],
    97           [33188, None, None, 1, '45854', '200', 4604, None,
     97          [33188, None, None, 1, "45854", "200", 4604, None,
    9898           (self._expected_year(), 12, 19, 23, 11, 0), None,
    9999           "index.html", None],
    100           [17901, None, None, 2, '45854', '200', 512, None,
     100          [17901, None, None, 2, "45854", "200", 512, None,
    101101           (2000, 5, 29, 0, 0, 0), None, "os2", None],
    102           [41471, None, None, 2, '45854', '200', 512, None,
     102          [41471, None, None, 2, "45854", "200", 512, None,
    103103           (2000, 5, 29, 0, 0, 0), None, "osup", "../os2"]
    104104          ]
     
    139139          ]
    140140        expected_stat_results = [
    141           [17901, None, None, 2, None, '200', 512, None,
     141          [17901, None, None, 2, None, "200", 512, None,
    142142           (2000, 5, 4, 0, 0, 0), None, "chemeng link", "chemeng target"],
    143           [33188, None, None, 1, None, '200', 4604, None,
     143          [33188, None, None, 1, None, "200", 4604, None,
    144144           (self._expected_year(), 12, 19, 23, 11, 0), None,
    145145           "index.html", None],
    146           [17901, None, None, 2, None, '200', 512, None,
     146          [17901, None, None, 2, None, "200", 512, None,
    147147           (2000, 5, 29, 0, 0, 0), None, "os2", None],
    148           [41471, None, None, 2, None, '200', 512, None,
     148          [41471, None, None, 2, None, "200", 512, None,
    149149           (2000, 5, 29, 0, 0, 0), None, "osup", "../os2"]
    150150          ]
     
    295295        """Test whether `lstat` fails for a nonexistent path."""
    296296        self.assertRaises(ftputil.error.PermanentError,
    297                           self.stat._lstat, '/home/sschw/notthere')
    298         self.assertRaises(ftputil.error.PermanentError,
    299                           self.stat._lstat, '/home/sschwarzer/notthere')
     297                          self.stat._lstat, "/home/sschw/notthere")
     298        self.assertRaises(ftputil.error.PermanentError,
     299                          self.stat._lstat, "/home/sschwarzer/notthere")
    300300
    301301    def test_lstat_for_root(self):
     
    307307        possible to do this for the root directory `/`.
    308308        """
    309         self.assertRaises(ftputil.error.RootDirError, self.stat._lstat, '/')
     309        self.assertRaises(ftputil.error.RootDirError, self.stat._lstat, "/")
    310310        try:
    311             self.stat._lstat('/')
     311            self.stat._lstat("/")
    312312        except ftputil.error.RootDirError as exc:
    313313            self.assertFalse(isinstance(exc, ftputil.error.FTPOSError))
     
    315315    def test_lstat_one_unix_file(self):
    316316        """Test `lstat` for a file described in Unix-style format."""
    317         stat_result = self.stat._lstat('/home/sschwarzer/index.html')
     317        stat_result = self.stat._lstat("/home/sschwarzer/index.html")
    318318        # Second form is needed for Python 3
    319         self.assertTrue(oct(stat_result.st_mode) in ('0100644', '0o100644'))
     319        self.assertTrue(oct(stat_result.st_mode) in ("0100644", "0o100644"))
    320320        self.assertEqual(stat_result.st_size, 4604)
    321321        self.assertEqual(stat_result._st_mtime_precision, 60)
     
    324324        """Test `lstat` for a file described in DOS-style format."""
    325325        self.stat = test_stat(session_factory=mock_ftplib.MockMSFormatSession)
    326         stat_result = self.stat._lstat('/home/msformat/abcd.exe')
     326        stat_result = self.stat._lstat("/home/msformat/abcd.exe")
    327327        self.assertEqual(stat_result._st_mtime_precision, 60)
    328328
    329329    def test_lstat_one_unix_dir(self):
    330330        """Test `lstat` for a directory described in Unix-style format."""
    331         stat_result = self.stat._lstat('/home/sschwarzer/scios2')
     331        stat_result = self.stat._lstat("/home/sschwarzer/scios2")
    332332        # Second form is needed for Python 3
    333         self.assertTrue(oct(stat_result.st_mode) in ('042755', '0o42755'))
     333        self.assertTrue(oct(stat_result.st_mode) in ("042755", "0o42755"))
    334334        self.assertEqual(stat_result.st_ino, None)
    335335        self.assertEqual(stat_result.st_dev, None)
    336336        self.assertEqual(stat_result.st_nlink, 6)
    337         self.assertEqual(stat_result.st_uid, '45854')
    338         self.assertEqual(stat_result.st_gid, '200')
     337        self.assertEqual(stat_result.st_uid, "45854")
     338        self.assertEqual(stat_result.st_gid, "200")
    339339        self.assertEqual(stat_result.st_size, 512)
    340340        self.assertEqual(stat_result.st_atime, None)
     
    344344        self.assertEqual(stat_result._st_mtime_precision, 24*60*60)
    345345        self.assertTrue(stat_result ==
    346           (17901, None, None, 6, '45854', '200', 512, None,
     346          (17901, None, None, 6, "45854", "200", 512, None,
    347347           stat_tuple_to_seconds((1999, 9, 20, 0, 0, 0)), None))
    348348
     
    350350        """Test `lstat` for a directory described in DOS-style format."""
    351351        self.stat = test_stat(session_factory=mock_ftplib.MockMSFormatSession)
    352         stat_result = self.stat._lstat('/home/msformat/WindowsXP')
     352        stat_result = self.stat._lstat("/home/msformat/WindowsXP")
    353353        self.assertEqual(stat_result._st_mtime_precision, 60)
    354354
    355355    def test_lstat_via_stat_module(self):
    356356        """Test `lstat` indirectly via `stat` module."""
    357         stat_result = self.stat._lstat('/home/sschwarzer/')
     357        stat_result = self.stat._lstat("/home/sschwarzer/")
    358358        self.assertTrue(stat.S_ISDIR(stat_result.st_mode))
    359359
     
    361361        """Test `stat` when invoked on a link."""
    362362        # Simple link
    363         stat_result = self.stat._stat('/home/link')
     363        stat_result = self.stat._stat("/home/link")
    364364        self.assertEqual(stat_result.st_size, 4604)
    365365        # Link pointing to a link
    366         stat_result = self.stat._stat('/home/python/link_link')
     366        stat_result = self.stat._stat("/home/python/link_link")
    367367        self.assertEqual(stat_result.st_size, 4604)
    368         stat_result = self.stat._stat('../python/link_link')
     368        stat_result = self.stat._stat("../python/link_link")
    369369        self.assertEqual(stat_result.st_size, 4604)
    370370        # Recursive link structures
    371371        self.assertRaises(ftputil.error.PermanentError,
    372                           self.stat._stat, '../python/bad_link')
    373         self.assertRaises(ftputil.error.PermanentError,
    374                           self.stat._stat, '/home/bad_link')
     372                          self.stat._stat, "../python/bad_link")
     373        self.assertRaises(ftputil.error.PermanentError,
     374                          self.stat._stat, "/home/bad_link")
    375375
    376376    #
     
    434434        """Test failing `FTPHost.listdir`."""
    435435        self.assertRaises(ftputil.error.PermanentError,
    436                           self.stat._listdir, 'notthere')
     436                          self.stat._listdir, "notthere")
    437437
    438438    def test_succeeding_listdir(self):
    439439        """Test succeeding `FTPHost.listdir`."""
    440440        # Do we have all expected "files"?
    441         self.assertEqual(len(self.stat._listdir('.')), 9)
     441        self.assertEqual(len(self.stat._listdir(".")), 9)
    442442        # Have they the expected names?
    443         expected = ('chemeng download image index.html os2 '
    444                     'osup publications python scios2').split()
    445         remote_file_list = self.stat._listdir('.')
     443        expected = ("chemeng download image index.html os2 "
     444                    "osup publications python scios2").split()
     445        remote_file_list = self.stat._listdir(".")
    446446        for file in expected:
    447447            self.assertTrue(file in remote_file_list)
    448448
    449449
    450 if __name__ == '__main__':
     450if __name__ == "__main__":
    451451    unittest.main()
  • test/test_stat_cache.py

    r1295 r1343  
    9696        # If bug #38 is present, this raises an `IndexError`.
    9797        items = host.listdir(host.curdir)
    98         self.assertEqual(items[:3], ['chemeng', 'download', 'image'])
     98        self.assertEqual(items[:3], ["chemeng", "download", "image"])
    9999
    100100
    101 if __name__ == '__main__':
     101if __name__ == "__main__":
    102102    unittest.main()
  • test/test_sync.py

    r1261 r1343  
    129129
    130130
    131 if __name__ == '__main__':
     131if __name__ == "__main__":
    132132    unittest.main()
  • test/test_with_statement.py

    r1319 r1343  
    3838            # wasn't successfully constructed, the assignment to `host`
    3939            # shouldn't have happened.
    40             self.assertFalse('host' in locals())
     40            self.assertFalse("host" in locals())
    4141        else:
    4242            raise self.failureException("ftputil.error.FTPOSError not raised")
     
    5858        with test_base.ftp_host_factory(
    5959               session_factory=ReadMockSession) as host:
    60             with host.open('dummy', 'r') as f:
     60            with host.open("dummy", "r") as f:
    6161                self.assertEqual(f.closed, False)
    6262                data = f.readline()
    63                 self.assertEqual(data, 'line 1\n')
     63                self.assertEqual(data, "line 1\n")
    6464                self.assertEqual(f.closed, False)
    6565            self.assertEqual(f.closed, True)
     
    7171                # This should fail since the directory isn't accessible
    7272                # by definition.
    73                 with host.open('/inaccessible/new_file', 'w') as f:
     73                with host.open("/inaccessible/new_file", "w") as f:
    7474                    pass
    7575            except ftputil.error.FTPIOError:
    7676                # The file construction shouldn't have succeeded, so
    7777                # `f` should be absent from the local namespace.
    78                 self.assertFalse('f' in locals())
     78                self.assertFalse("f" in locals())
    7979            else:
    8080                raise self.failureException(
     
    8585               session_factory=ReadMockSession) as host:
    8686            try:
    87                 with host.open('dummy', 'r') as f:
     87                with host.open("dummy", "r") as f:
    8888                    self.assertEqual(f.closed, False)
    8989                    raise ClientCodeException()
     
    9494
    9595
    96 if __name__ == '__main__':
     96if __name__ == "__main__":
    9797    unittest.main()
Note: See TracChangeset for help on using the changeset viewer.