Ticket #14332: 0001-Use-the-new-string-formatting-interface.patch

File 0001-Use-the-new-string-formatting-interface.patch, 31.0 KB (added by cypherpunks, 3 years ago)
  • lib/chutney/Templating.py

    From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
    From: cypherpunks <cypherpunks@torproject.org>
    Date: Sat, 2 Jul 2016 21:00:27 +0000
    Subject: [PATCH] Use the new string formatting interface
    
    The str.format() interface avoids errors in the printf-style string
    formatting interface, and provides a generally more powerful, flexible
    and extensible approach to formatting text.
    
    See https://pyformat.info/ for more information.
    
    Closes ticket 14332.
    ---
     lib/chutney/Templating.py       |   2 +-
     lib/chutney/TorNet.py           | 124 ++++++++++++++++++++--------------------
     lib/chutney/Traffic.py          |  76 +++++++++++++-----------
     networks/basic-min-mixed        |   8 +--
     networks/hs-min-mixed           |  16 ++----
     scripts/chutney_tests/verify.py |  26 ++++-----
     6 files changed, 127 insertions(+), 125 deletions(-)
    
    diff --git a/lib/chutney/Templating.py b/lib/chutney/Templating.py
    index de3de90..ff3b496 100644
    a b class Environ(_DictWrapper): 
    210210        except KeyError:
    211211            pass
    212212
    213         fn = getattr(self, "_get_%s" % key, None)
     213        fn = getattr(self, "_get_{}".format(key), None)
    214214        if fn is not None:
    215215            try:
    216216                rv = fn(my)
  • lib/chutney/TorNet.py

    diff --git a/lib/chutney/TorNet.py b/lib/chutney/TorNet.py
    index 6db7ad4..40165dc 100644
    a b class LocalNodeBuilder(NodeBuilder): 
    250250            except OSError as e:
    251251                # only catch file not found error
    252252                if e.errno == errno.ENOENT:
    253                     print("Cannot find tor binary %r. Use "
     253                    print("Cannot find tor binary {!r}. Use "
    254254                          "CHUTNEY_TOR environment variable to set the "
    255                           "path, or put the binary into $PATH." % tor)
     255                          "path, or put the binary into $PATH.".format(tor))
    256256                    sys.exit(0)
    257257                else:
    258258                    raise
    class LocalNodeBuilder(NodeBuilder): 
    286286                    # well, this could get spammy
    287287                    # TODO: warn once per option per tor binary
    288288                    # TODO: print tor version?
    289                     print(("The tor binary at %r does not support the "
    290                            "option in the torrc line:\n"
    291                            "%r") % (tor, line.strip()))
     289                    print("The tor binary at {!r} does not support the "
     290                          "option in the torrc line:\n{!r}".format(
     291                              tor, line.strip()))
    292292                    # we could decide to skip these lines entirely
    293293                    # TODO: write tor version?
    294294                    f.writelines(["# " + tor + " unsupported: " + line])
    class LocalNodeBuilder(NodeBuilder): 
    375375            '-c', certfile,
    376376            '-m', str(lifetime),
    377377            '-a', addr]
    378         print("Creating identity key %s for %s with %s" % (
     378        print("Creating identity key {} for {} with {}".format(
    379379            idfile, self._env['nick'], " ".join(cmdline)))
    380380        try:
    381381            p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
    382382        except OSError as e:
    383383            # only catch file not found error
    384384            if e.errno == errno.ENOENT:
    385                 print("Cannot find tor-gencert binary %r. Use "
     385                print("Cannot find tor-gencert binary {!r}. Use "
    386386                      "CHUTNEY_TOR_GENCERT environment variable to set the "
    387                       "path, or put the binary into $PATH." % tor_gencert)
     387                      "path, or put the binary into "
     388                      "$PATH.".format(tor_gencert))
    388389                sys.exit(0)
    389390            else:
    390391                raise
    class LocalNodeBuilder(NodeBuilder): 
    411412        except OSError as e:
    412413            # only catch file not found error
    413414            if e.errno == errno.ENOENT:
    414                 print("Cannot find tor binary %r. Use "
    415                       "CHUTNEY_TOR environment variable to set the "
    416                       "path, or put the binary into $PATH." % tor)
     415                print("Cannot find tor binary {!r}. Use CHUTNEY_TOR "
     416                      "environment variable to set the path, or put the "
     417                      "binary into $PATH.".format(tor))
    417418                sys.exit(0)
    418419            else:
    419420                raise
    420421        stdout, stderr = p.communicate()
    421422        fingerprint = "".join((stdout.rstrip().split('\n')[-1]).split()[1:])
    422423        if not re.match(r'^[A-F0-9]{40}$', fingerprint):
    423             print(("Error when calling %r. It gave %r as a fingerprint "
    424                    " and %r on stderr.") % (" ".join(cmdline), stdout, stderr))
     424            print("Error when calling {!r}. It gave {!r} as a fingerprint "
     425                  " and {!r} on stderr.".format(" ".join(cmdline), stdout,
     426                                                stderr))
    425427            sys.exit(1)
    426428        self._env['fingerprint'] = fingerprint
    427429
    class LocalNodeBuilder(NodeBuilder): 
    457459                options = ("AlternateDirAuthority",)
    458460            else:
    459461                options = ("DirAuthority",)
    460             self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
     462            self._env['dirserver_flags'] += " hs v3ident={}".format(v3id)
    461463
    462464        authlines = ""
    463465        for authopt in options:
    464             authlines += "%s %s orport=%s" % (
     466            authlines += "{} {} orport={}".format(
    465467                authopt, self._env['nick'], self._env['orport'])
    466468            # It's ok to give an authority's IPv6 address to an IPv4-only
    467469            # client or relay: it will and must ignore it
    468470            if self._env['ipv6_addr'] is not None:
    469                 authlines += " ipv6=%s:%s" % (self._env['ipv6_addr'],
    470                                               self._env['orport'])
    471             authlines += " %s %s:%s %s\n" % (
     471                authlines += " ipv6={}:{}".format(self._env['ipv6_addr'],
     472                                                  self._env['orport'])
     473            authlines += " {} {}:{} {}\n".format(
    472474                self._env['dirserver_flags'], self._env['ip'],
    473475                self._env['dirport'], self._env['fingerprint'])
    474476        return authlines
    class LocalNodeBuilder(NodeBuilder): 
    480482        if not self._env['bridge']:
    481483            return ""
    482484
    483         bridgelines = "Bridge %s:%s\n" % (self._env['ip'],
    484                                           self._env['orport'])
     485        bridgelines = "Bridge {}:{}\n".format(self._env['ip'],
     486                                              self._env['orport'])
    485487        if self._env['ipv6_addr'] is not None:
    486             bridgelines += "Bridge %s:%s\n" % (self._env['ipv6_addr'],
    487                                                self._env['orport'])
     488            bridgelines += "Bridge {}:{}\n".format(self._env['ipv6_addr'],
     489                                                   self._env['orport'])
    488490        return bridgelines
    489491
    490492
    class LocalNodeController(NodeController): 
    538540        pid = self.getPid()
    539541        nick = self._env['nick']
    540542        datadir = self._env['dir']
    541         corefile = "core.%s" % pid
     543        corefile = "core.{}".format(pid)
    542544        if self.isRunning(pid):
    543545            if listRunning:
    544                 print("%s is running with PID %s" % (nick, pid))
     546                print("{} is running with PID {}".format(nick, pid))
    545547            return True
    546548        elif os.path.exists(os.path.join(datadir, corefile)):
    547549            if listNonRunning:
    548                 print("%s seems to have crashed, and left core file %s" % (
    549                     nick, corefile))
     550                print("{} seems to have crashed, and left core file "
     551                      "{}".format(nick, corefile))
    550552            return False
    551553        else:
    552554            if listNonRunning:
    553                 print("%s is stopped" % nick)
     555                print("{} is stopped".format(nick))
    554556            return False
    555557
    556558    def hup(self):
    class LocalNodeController(NodeController): 
    558560        pid = self.getPid()
    559561        nick = self._env['nick']
    560562        if self.isRunning(pid):
    561             print("Sending sighup to %s" % nick)
     563            print("Sending sighup to {}".format(nick))
    562564            os.kill(pid, signal.SIGHUP)
    563565            return True
    564566        else:
    565             print("%s is not running" % nick)
     567            print("{} is not running".format(nick))
    566568            return False
    567569
    568570    def start(self):
    class LocalNodeController(NodeController): 
    570572           already running, False if we failed."""
    571573
    572574        if self.isRunning():
    573             print("%s is already running" % self._env['nick'])
     575            print("{} is already running".format(self._env['nick']))
    574576            return True
    575577        tor_path = self._env['tor']
    576578        torrc = self._getTorrcFname()
    class LocalNodeController(NodeController): 
    584586        except OSError as e:
    585587            # only catch file not found error
    586588            if e.errno == errno.ENOENT:
    587                 print("Cannot find tor binary %r. Use CHUTNEY_TOR "
     589                print("Cannot find tor binary {!r}. Use CHUTNEY_TOR "
    588590                      "environment variable to set the path, or put the "
    589                       "binary into $PATH." % tor_path)
     591                      "binary into $PATH.".format(tor_path))
    590592                sys.exit(0)
    591593            else:
    592594                raise
    class LocalNodeController(NodeController): 
    609611            p.poll()
    610612        if p.returncode is not None and p.returncode != 0:
    611613            if self._env['poll_launch_time'] is None:
    612                 print("Couldn't launch %s (%s): %s" % (self._env['nick'],
    613                                                        " ".join(cmdline),
    614                                                        p.returncode))
     614                print("Couldn't launch {} ({}): {}".format(self._env['nick'],
     615                                                           " ".join(cmdline),
     616                                                           p.returncode))
    615617            else:
    616                 print("Couldn't poll %s (%s) "
    617                       "after waiting %s seconds for launch"
    618                       ": %s" % (self._env['nick'],
    619                                 " ".join(cmdline),
    620                                 self._env['poll_launch_time'],
    621                                 p.returncode))
     618                print("Couldn't poll {} ({}) after waiting {} seconds for "
     619                      "launch: {}".format(self._env['nick'], " ".join(cmdline),
     620                                          self._env['poll_launch_time'],
     621                                          p.returncode))
    622622            return False
    623623        return True
    624624
    class LocalNodeController(NodeController): 
    626626        """Try to stop this node by sending it the signal 'sig'."""
    627627        pid = self.getPid()
    628628        if not self.isRunning(pid):
    629             print("%s is not running" % self._env['nick'])
     629            print("{} is not running".format(self._env['nick']))
    630630            return
    631631        os.kill(pid, sig)
    632632
    633633    def cleanup_lockfile(self):
    634634        lf = self._env['lockfile']
    635635        if not self.isRunning() and os.path.exists(lf):
    636             print('Removing stale lock file for {0} ...'.format(
    637                 self._env['nick']))
     636            print("Removing stale lock file for {} ...".format(
     637                  self._env['nick']))
    638638            os.remove(lf)
    639639
    640640    def waitOnLaunch(self):
    class TorEnviron(chutney.Templating.Environ): 
    764764        return my['dirport_base'] + my['nodenum']
    765765
    766766    def _get_dir(self, my):
    767         return os.path.abspath(os.path.join(my['net_base_dir'],
    768                                             "nodes",
    769                                             "%03d%s" % (
    770                                                 my['nodenum'], my['tag'])))
     767        return os.path.abspath(os.path.join(my['net_base_dir'], "nodes",
     768                                            "{:03d}{}".format(my['nodenum'],
     769                                                              my['tag'])))
    771770
    772771    def _get_nick(self, my):
    773         return "test%03d%s" % (my['nodenum'], my['tag'])
     772        return "test{:03d}{}".format(my['nodenum'], my['tag'])
    774773
    775774    def _get_tor_gencert(self, my):
    776         return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
     775        return my['tor-gencert'] or "{}-gencert".format(my['tor'])
    777776
    778777    def _get_auth_passphrase(self, my):
    779778        return self['nick']  # OMG TEH SECURE!
    class TorEnviron(chutney.Templating.Environ): 
    802801                hostname = hostname.strip()
    803802                my['hs-hostname'] = hostname
    804803            except IOError as e:
    805                 print("Error: hs %r error %d: %r opening hostname file '%r'" %
    806                       (my['nick'], e.errno, e.strerror, hs_hostname_file))
     804                print("Error: hs {!r} error {:d}: {!r} opening hostname file "
     805                      "{!r}".format(my['nick'], e.errno, e.strerror,
     806                                    hs_hostname_file))
    807807        return my['hs-hostname']
    808808
    809809
    class Network(object): 
    829829        if not os.path.exists(nodesdir):
    830830            return
    831831
    832         newdir = newdirbase = "%s.%d" % (nodesdir, time.time())
     832        newdir = newdirbase = "{}.{:.0f}".format(nodesdir, time.time())
    833833        i = 0
    834834        while os.path.exists(newdir):
    835835            i += 1
    836             newdir = "%s.%d" % (newdirbase, i)
     836            newdir = "{}.{:d}".format(newdirbase, i)
    837837
    838         print("NOTE: renaming %r to %r" % (nodesdir, newdir))
     838        print("NOTE: renaming {!r} to {!r}".format(nodesdir, newdir))
    839839        os.rename(nodesdir, newdir)
    840840
    841841    def _checkConfig(self):
    class Network(object): 
    872872    def status(self):
    873873        statuses = [n.getController().check() for n in self._nodes]
    874874        n_ok = len([x for x in statuses if x])
    875         print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
     875        print("{:d}/{:d} nodes are running".format(n_ok, len(self._nodes)))
    876876        return n_ok == len(self._nodes)
    877877
    878878    def restart(self):
    class Network(object): 
    902902        for sig, desc in [(signal.SIGINT, "SIGINT"),
    903903                          (signal.SIGINT, "another SIGINT"),
    904904                          (signal.SIGKILL, "SIGKILL")]:
    905             print("Sending %s to nodes" % desc)
     905            print("Sending {} to nodes".format(desc))
    906906            for c in controllers:
    907907                if c.isRunning():
    908908                    c.stop(sig=sig)
    def getTests(): 
    942942
    943943def usage(network):
    944944    return "\n".join(["Usage: chutney {command/test} {networkfile}",
    945                       "Known commands are: %s" % (
     945                      "Known commands are: {}".format(
    946946                          " ".join(x for x in dir(network)
    947947                                   if not x.startswith("_"))),
    948                       "Known tests are: %s" % (
     948                      "Known tests are: {}".format(
    949949                          " ".join(getTests()))
    950950                      ])
    951951
    952952
    953953def exit_on_error(err_msg):
    954     print("Error: {0}\n".format(err_msg))
     954    print("Error: {}\n".format(err_msg))
    955955    print(usage(_THE_NETWORK))
    956956    sys.exit(1)
    957957
    def runConfigFile(verb, data): 
    977977    # tell the user we don't know what their verb meant
    978978    if not hasattr(network, verb):
    979979        print(usage(network))
    980         print("Error: I don't know how to %s." % verb)
     980        print("Error: I don't know how to {}.".format(verb))
    981981        return
    982982
    983983    return getattr(network, verb)()
    def parseArgs(): 
    987987    if len(sys.argv) < 3:
    988988        exit_on_error("Not enough arguments given.")
    989989    if not os.path.isfile(sys.argv[2]):
    990         exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
     990        exit_on_error("Cannot find networkfile: {}.".format(sys.argv[2]))
    991991    return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
    992992
    993993
  • lib/chutney/Traffic.py

    diff --git a/lib/chutney/Traffic.py b/lib/chutney/Traffic.py
    index b5f75fd..aecd61c 100644
    a b debug_flag = False 
    3737def debug(s):
    3838    "Print a debug message on stdout if debug_flag is True."
    3939    if debug_flag:
    40         print("DEBUG: %s" % s)
     40        print("DEBUG: {}".format(s))
    4141
    4242
    4343def socks_cmd(addr_port):
    def socks_cmd(addr_port): 
    5656        addr = socket.inet_aton(host)
    5757    except socket.error:
    5858        addr = '\x00\x00\x00\x01'
    59         dnsname = '%s\x00' % host
    60     debug("Socks 4a request to %s:%d" % (host, port))
     59        dnsname = "{}\x00".format(host)
     60    debug("Socks 4a request to {}:{:d}".format(host, port))
    6161    return struct.pack('!BBH', ver, cmd, port) + addr + user + dnsname
    6262
    6363
    class TestSuite(object): 
    8989        return self.not_done == 0
    9090
    9191    def status(self):
    92         return('%d/%d/%d' % (self.not_done, self.successes, self.failures))
     92        return "{:d}/{:d}/{:d}".format(self.not_done, self.successes,
     93                                       self.failures)
    9394
    9495
    9596class Peer(object):
    class Listener(Peer): 
    130131
    131132    def accept(self):
    132133        newsock, endpoint = self.s.accept()
    133         debug("new client from %s:%s (fd=%d)" %
    134               (endpoint[0], endpoint[1], newsock.fileno()))
     134        debug("new client from {}:{} (fd={:d})".format(endpoint[0],
     135                                                       endpoint[1],
     136                                                       newsock.fileno()))
    135137        self.tt.add(Sink(self.tt, newsock))
    136138
    137139
    class Sink(Peer): 
    158160            debug("no verification required - no data")
    159161            return 0
    160162        self.inbuf += self.s.recv(len(data) - len(self.inbuf))
    161         debug("successfully received (bytes=%d)" % len(self.inbuf))
     163        debug("successfully received (bytes={:d})".format(len(self.inbuf)))
    162164        while len(self.inbuf) >= len(data):
    163165            assert(len(self.inbuf) <= len(data) or self.repetitions > 1)
    164166            if self.inbuf[:len(data)] != data:
    165                 debug("receive comparison failed (bytes=%d)" % len(data))
     167                debug("receive comparison failed (bytes={:d})".format(
     168                      len(data)))
    166169                return -1  # Failed verification.
    167170            # if we're not debugging, print a dot every dot_repetitions reps
    168171            elif (not debug_flag and self.tt.dot_repetitions > 0 and
    class Sink(Peer): 
    170173                sys.stdout.write('.')
    171174                sys.stdout.flush()
    172175            # repeatedly check data against self.inbuf if required
    173             debug("receive comparison success (bytes=%d)" % len(data))
     176            debug("receive comparison success (bytes={:d})".format(len(data)))
    174177            self.inbuf = self.inbuf[len(data):]
    175             debug("receive leftover bytes (bytes=%d)" % len(self.inbuf))
     178            debug("receive leftover bytes (bytes={:d})".format(
     179                  len(self.inbuf)))
    176180            self.repetitions -= 1
    177             debug("receive remaining repetitions (reps=%d)" % self.repetitions)
     181            debug("receive remaining repetitions (reps={:d})".format(
     182                  self.repetitions))
    178183        if self.repetitions == 0 and len(self.inbuf) == 0:
    179184            debug("successful verification")
    180185        # calculate the actual length of data remaining, including reps
    181         debug("receive remaining bytes (bytes=%d)"
    182               % (self.repetitions*len(data) - len(self.inbuf)))
     186        debug("receive remaining bytes (bytes={:d})".format(
     187              self.repetitions*len(data) - len(self.inbuf)))
    183188        return self.repetitions*len(data) - len(self.inbuf)
    184189
    185190
    class Source(Peer): 
    227232            self.inbuf += self.s.recv(8 - len(self.inbuf))
    228233            if len(self.inbuf) == 8:
    229234                if ord(self.inbuf[0]) == 0 and ord(self.inbuf[1]) == 0x5a:
    230                     debug("proxy handshake successful (fd=%d)" % self.fd())
     235                    debug("proxy handshake successful "
     236                          "(fd={:d})".format(self.fd()))
    231237                    self.state = self.CONNECTED
    232238                    self.inbuf = ''
    233                     debug("successfully connected (fd=%d)" % self.fd())
     239                    debug("successfully connected (fd={:d})".format(self.fd()))
    234240                    # if we have no reps or no data, skip sending actual data
    235241                    if self.want_to_write():
    236242                        return 1    # Keep us around for writing.
    class Source(Peer): 
    239245                        debug("no connection required - no data")
    240246                        return 0
    241247                else:
    242                     debug("proxy handshake failed (0x%x)! (fd=%d)" %
    243                           (ord(self.inbuf[1]), self.fd()))
     248                    debug("proxy handshake failed (0x{:x})! (fd={:d})".format(
     249                          ord(self.inbuf[1]), self.fd()))
    244250                    self.state = self.NOT_CONNECTED
    245251                    return -1
    246252            assert(8 - len(self.inbuf) > 0)
    class Source(Peer): 
    260266        if self.state == self.CONNECTING:
    261267            if self.proxy is None:
    262268                self.state = self.CONNECTED
    263                 debug("successfully connected (fd=%d)" % self.fd())
     269                debug("successfully connected (fd={:d})".format(self.fd()))
    264270            else:
    265271                self.state = self.CONNECTING_THROUGH_PROXY
    266272                self.outbuf = socks_cmd(self.dest)
    class Source(Peer): 
    271277            if (len(self.outbuf) < len(self.data) and self.repetitions > 0):
    272278                self.outbuf += self.data
    273279                self.repetitions -= 1
    274                 debug("adding more data to send (bytes=%d)" % len(self.data))
    275                 debug("now have data to send (bytes=%d)" % len(self.outbuf))
    276                 debug("send repetitions remaining (reps=%d)"
    277                       % self.repetitions)
     280                debug("adding more data to send (bytes={:d})".format(
     281                      len(self.data)))
     282                debug("now have data to send (bytes={:d})".format(
     283                      len(self.outbuf)))
     284                debug("send repetitions remaining (reps={:d})".format(
     285                      self.repetitions))
    278286        try:
    279287            n = self.s.send(self.outbuf)
    280288        except socket.error as e:
    281289            if e[0] == errno.ECONNREFUSED:
    282                 debug("connection refused (fd=%d)" % self.fd())
     290                debug("connection refused (fd={:d})".format(self.fd()))
    283291                return -1
    284292            raise
    285293        # sometimes, this debug statement prints 0
    286294        # it should print length of the data sent
    287295        # but the code works as long as this doesn't keep on happening
    288296        if n > 0:
    289             debug("successfully sent (bytes=%d)" % n)
     297            debug("successfully sent (bytes={:d})".format(n))
    290298            self._sent_no_bytes = 0
    291299        else:
    292300            debug("BUG: sent no bytes")
    293301            self._sent_no_bytes += 1
    294302            # We can't retry too fast, otherwise clients burn all their HSDirs
    295303            if self._sent_no_bytes >= 2:
    296                 print("Sent no data %d times. Stalled." %
    297                       (self._sent_no_bytes))
     304                print("Sent no data {:d} times. Stalled.".format(
     305                      self._sent_no_bytes))
    298306                return -1
    299307            time.sleep(5)
    300308        self.outbuf = self.outbuf[n:]
    301309        if self.state == self.CONNECTING_THROUGH_PROXY:
    302310            return 1  # Keep us around.
    303         debug("bytes remaining on outbuf (bytes=%d)" % len(self.outbuf))
     311        debug("bytes remaining on outbuf (bytes={:d})".format(
     312              len(self.outbuf)))
    304313        # calculate the actual length of data remaining, including reps
    305314        # When 0, we're being removed.
    306         debug("bytes remaining overall (bytes=%d)"
    307               % (self.repetitions*len(self.data) + len(self.outbuf)))
     315        debug("bytes remaining overall (bytes={:d})".format(
     316              self.repetitions*len(self.data) + len(self.outbuf)))
    308317        return self.repetitions*len(self.data) + len(self.outbuf)
    309318
    310319
    class TrafficTester(): 
    336345        if self.repetitions == 0:
    337346            self.data = {}
    338347        self.dot_repetitions = dot_repetitions
    339         debug("listener fd=%d" % self.listener.fd())
     348        debug("listener fd={:d}".format(self.listener.fd()))
    340349        self.peers = {}  # fd:Peer
    341350
    342351    def sinks(self):
    class TrafficTester(): 
    362371            rset = [self.listener.fd()] + list(self.peers)
    363372            wset = [p.fd() for p in
    364373                    filter(lambda x: x.want_to_write(), self.sources())]
    365             # debug("rset %s wset %s" % (rset, wset))
     374            # debug("rset {} wset {}".format(rset, wset))
    366375            sets = select.select(rset, wset, [], 1)
    367376            if all(len(s) == 0 for s in sets):
    368377                self.timeout -= 1
    class TrafficTester(): 
    375384                p = self.peers[fd]
    376385                n = p.on_readable()
    377386                if n > 0:
    378                     # debug("need %d more octets from fd %d" % (n, fd))
     387                    # debug("need {:d} more octets from fd {:d}".format(n, fd))
    379388                    pass
    380389                elif n == 0:  # Success.
    381390                    self.tests.success()
    class TrafficTester(): 
    398407
    399408        for fd in self.peers:
    400409            peer = self.peers[fd]
    401             debug("peer fd=%d never pending close, never read or wrote" % fd)
     410            debug("peer fd={:d} never pending close, never read or "
     411                  "wrote".format(fd))
    402412            self.pending_close.append(peer.s)
    403413        self.listener.s.close()
    404414        for s in self.pending_close:
  • networks/basic-min-mixed

    diff --git a/networks/basic-min-mixed b/networks/basic-min-mixed
    index 5ae7bd5..6d9a2f3 100644
    a b def version(node): 
    3535# Every time chutney takes an action, it will pick versions at random
    3636# It will likely choose different versions for each action
    3737# This could be confusing, so log a message each time
    38 print("Chose 1 %s authority, 1 %s authority, 1 %s exit and 1 %s client"
    39       % (version(Authority),
    40          version(OldAuthority),
    41          version(OldNewExitRelay),
    42          version(OldNewClient)))
     38print("Chose 1 {} authority, 1 {} authority, 1 {} exit and 1 {} client".format(
     39      version(Authority), version(OldAuthority), version(OldNewExitRelay),
     40      version(OldNewClient)))
    4341
    4442# The minimum number of authorities/relays/exits is 3, the minimum path length
    4543NODES = Authority.getN(1) + OldAuthority.getN(1) + OldExitRelay.getN(1) + OldClient.getN(1)
  • networks/hs-min-mixed

    diff --git a/networks/hs-min-mixed b/networks/hs-min-mixed
    index 8de3825..eae3685 100644
    a b def version(node): 
    3939# Every time chutney takes an action, it will pick versions at random
    4040# It will likely choose different versions for each action
    4141# This could be confusing, so log a message each time
    42 print(("Chose 1 %s authority, 1 %s authority, %d %s non-exit relay, " +
    43        "%d %s non-exit relay, 1 %s client and 1 %s hidden service")
    44       % (version(Authority),
    45          version(OldAuthority),
    46          2 if OldNewNonExitRelay == NonExitRelay else 1,
    47          version(NonExitRelay),
    48          2 if OldNewNonExitRelay == OldNonExitRelay else 1,
    49          version(OldNonExitRelay),
    50          version(OldNewClient),
    51          version(OldNewHS)))
     42print("Chose 1 {} authority, 1 {} authority, {:d} {} non-exit relay, "
     43      "{:d} {} non-exit relay, 1 {} client and 1 {} hidden service".format(
     44      version(Authority), version(OldAuthority),
     45      2 if OldNewNonExitRelay == NonExitRelay else 1, version(NonExitRelay),
     46      2 if OldNewNonExitRelay == OldNonExitRelay else 1,
     47      version(OldNonExitRelay), version(OldNewClient), version(OldNewHS)))
    5248
    5349# A hidden service needs 5 authorities/relays to ensure it can build HS
    5450# connections:
  • scripts/chutney_tests/verify.py

    diff --git a/scripts/chutney_tests/verify.py b/scripts/chutney_tests/verify.py
    index b887ee7..551f82f 100644
    a b def run_test(network): 
    66    wait_time = network._dfltEnv['bootstrap_time']
    77    start_time = time.time()
    88    end_time = start_time + wait_time
    9     print("Verifying data transmission: (retrying for up to %d seconds)"
    10           % wait_time)
     9    print("Verifying data transmission: (retrying for up to {:d} "
     10          "seconds)".format(wait_time))
    1111    status = False
    1212    # Keep on retrying the verify until it succeeds or times out
    1313    while not status and time.time() < end_time:
    def run_test(network): 
    1717        # Avoid madly spewing output if we fail immediately each time
    1818        if not status:
    1919            time.sleep(5)
    20     print("Transmission: %s" % ("Success" if status else "Failure"))
     20    print("Transmission: {}".format("Success" if status else "Failure"))
    2121    if not status:
    2222        # TODO: allow the debug flag to be passed as an argument to
    2323        # src/test/test-network.sh and chutney
    def _configure_exits(tt, bind_to, tmpdata, reps, client_list, exit_list, 
    143143                                 CLIENT_EXIT_PATH_NODES *
    144144                                 connection_count)
    145145        for op in client_list:
    146             print("  Exit to %s:%d via client %s:%s"
    147                   % (LISTEN_ADDR, LISTEN_PORT,
    148                      'localhost', op._env['socksport']))
     146            print("  Exit to {}:{:d} via client {}:{}".format(
     147                  LISTEN_ADDR, LISTEN_PORT, 'localhost', op._env['socksport']))
    149148            for _ in range(connection_count):
    150149                proxy = ('localhost', int(op._env['socksport']))
    151150                tt.add(chutney.Traffic.Source(tt, bind_to, tmpdata, proxy,
    def _configure_hs(tt, tmpdata, reps, client_list, hs_list, HS_PORT, 
    175174    for hs in hs_list:
    176175        hs_bind_to = (hs._env['hs_hostname'], HS_PORT)
    177176        for client in hs_client_list:
    178             print("  HS to %s:%d (%s:%d) via client %s:%s"
    179                   % (hs._env['hs_hostname'], HS_PORT,
    180                      LISTEN_ADDR, LISTEN_PORT,
    181                      'localhost', client._env['socksport']))
     177            print("  HS to {}:{:d} ({}:{:d}) via client {}:{}".format(
     178                  hs._env['hs_hostname'], HS_PORT, LISTEN_ADDR, LISTEN_PORT,
     179                  'localhost', client._env['socksport']))
    182180            for _ in range(connection_count):
    183181                proxy = ('localhost', int(client._env['socksport']))
    184182                tt.add(chutney.Traffic.Source(tt, hs_bind_to, tmpdata,
    def _report_bandwidth(data_length, total_path_node_count, start_time, 
    211209        single_stream_bandwidth = (data_length / elapsed_time / BWDIVISOR)
    212210        overall_bandwidth = (cumulative_data_sent / elapsed_time /
    213211                             BWDIVISOR)
    214         print("Single Stream Bandwidth: %.2f MBytes/s"
    215               % single_stream_bandwidth)
    216         print("Overall tor Bandwidth: %.2f MBytes/s"
    217               % overall_bandwidth)
     212        print("Single Stream Bandwidth: {:.2f} MBytes/s".format(
     213              single_stream_bandwidth))
     214        print("Overall tor Bandwidth: {:.2f} MBytes/s".format(
     215              overall_bandwidth))