Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "Prefer format() over string interpolation operator" issue #136

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 18 additions & 19 deletions scripts/tls.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@

def printUsage(s=None):
if s:
print("ERROR: %s" % s)
print("ERROR: {0!s}".format(s))

print("")
print("Version: %s" % __version__)
print("Version: {0!s}".format(__version__))
print("")
print("RNG: %s" % prngName)
print("RNG: {0!s}".format(prngName))
print("")
print("Modules:")
if tackpyLoaded:
Expand Down Expand Up @@ -88,7 +88,7 @@ def printUsage(s=None):

def printError(s):
"""Print error message and exit"""
sys.stderr.write("ERROR: %s\n" % s)
sys.stderr.write("ERROR: {0!s}\n".format(s))
sys.exit(-1)


Expand Down Expand Up @@ -192,22 +192,22 @@ def handleArgs(argv, argString, flagsList=[]):


def printGoodConnection(connection, seconds):
print(" Handshake time: %.3f seconds" % seconds)
print(" Version: %s" % connection.getVersionName())
print(" Cipher: %s %s" % (connection.getCipherName(),
print(" Handshake time: {0:.3f} seconds".format(seconds))
print(" Version: {0!s}".format(connection.getVersionName()))
print(" Cipher: {0!s} {1!s}".format(connection.getCipherName(),
connection.getCipherImplementation()))
print(" Ciphersuite: {0}".\
format(CipherSuite.ietfNames[connection.session.cipherSuite]))
if connection.session.srpUsername:
print(" Client SRP username: %s" % connection.session.srpUsername)
print(" Client SRP username: {0!s}".format(connection.session.srpUsername))
if connection.session.clientCertChain:
print(" Client X.509 SHA1 fingerprint: %s" %
connection.session.clientCertChain.getFingerprint())
print(" Client X.509 SHA1 fingerprint: {0!s}".format(
connection.session.clientCertChain.getFingerprint()))
else:
print(" No client certificate provided by peer")
if connection.session.serverCertChain:
print(" Server X.509 SHA1 fingerprint: %s" %
connection.session.serverCertChain.getFingerprint())
print(" Server X.509 SHA1 fingerprint: {0!s}".format(
connection.session.serverCertChain.getFingerprint()))
if connection.version >= (3, 3) and connection.serverSigAlg is not None:
print(" Key exchange signature: {1}+{0}".format(\
HashAlgorithm.toStr(connection.serverSigAlg[0]),
Expand All @@ -218,18 +218,18 @@ def printGoodConnection(connection, seconds):
if connection.dhGroupSize is not None:
print(" DH group size: {0} bits".format(connection.dhGroupSize))
if connection.session.serverName:
print(" SNI: %s" % connection.session.serverName)
print(" SNI: {0!s}".format(connection.session.serverName))
if connection.session.tackExt:
if connection.session.tackInHelloExt:
emptyStr = "\n (via TLS Extension)"
else:
emptyStr = "\n (via TACK Certificate)"
print(" TACK: %s" % emptyStr)
print(" TACK: {0!s}".format(emptyStr))
print(str(connection.session.tackExt))
if connection.session.appProto:
print(" Application Layer Protocol negotiated: {0}".format(
connection.session.appProto.decode('utf-8')))
print(" Next-Protocol Negotiated: %s" % connection.next_proto)
print(" Next-Protocol Negotiated: {0!s}".format(connection.next_proto))
print(" Encrypt-then-MAC: {0}".format(connection.encryptThenMAC))
print(" Extended Master Secret: {0}".format(
connection.extendedMasterSecret))
Expand Down Expand Up @@ -314,11 +314,10 @@ def serverCmd(argv):
if tacks and not certChain:
raise SyntaxError("Must specify CERT with Tacks")

print("I am an HTTPS test server, I will listen on %s:%d" %
(address[0], address[1]))
print("I am an HTTPS test server, I will listen on {0!s}:{1:d}".format(address[0], address[1]))
if directory:
os.chdir(directory)
print("Serving files from %s" % os.getcwd())
print("Serving files from {0!s}".format(os.getcwd()))

if certChain and privateKey:
print("Using certificate and private key...")
Expand Down Expand Up @@ -402,5 +401,5 @@ def handshake(self, connection):
elif sys.argv[1] == "server"[:len(sys.argv[1])]:
serverCmd(sys.argv[2:])
else:
printUsage("Unknown command: %s" % sys.argv[1])
printUsage("Unknown command: {0!s}".format(sys.argv[1]))

8 changes: 4 additions & 4 deletions scripts/tlsdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@

if len(sys.argv) == 1 or (len(sys.argv)==2 and sys.argv[1].lower().endswith("help")):
print("")
print("Version: %s" % __version__)
print("Version: {0!s}".format(__version__))
print("")
print("RNG: %s" % prngName)
print("RNG: {0!s}".format(prngName))
print("")
print("Modules:")
if m2cryptoLoaded:
Expand Down Expand Up @@ -78,7 +78,7 @@ def reformatDocString(s):
if command == "valid":
print("")
else:
print("Bad command: '%s'" % command)
print("Bad command: '{0!s}'".format(command))

elif cmd == "createsrp":
dbName = args.get(2)
Expand Down Expand Up @@ -145,6 +145,6 @@ def numBits(n):
N, g, s, v = db[username]
print(numBits(N), username)
else:
print("Bad command: '%s'" % cmd)
print("Bad command: '{0!s}'".format(cmd))
except:
raise
38 changes: 19 additions & 19 deletions tests/tlstest.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,14 @@ def printUsage(s=None):
else:
crypto = "Python crypto"
if s:
print("ERROR: %s" % s)
print("""\ntls.py version %s (using %s)
print("ERROR: {0!s}".format(s))
print("""\ntls.py version {0!s} (using {1!s})

Commands:
server HOST:PORT DIRECTORY

client HOST:PORT DIRECTORY
""" % (__version__, crypto))
""".format(__version__, crypto))
sys.exit(-1)


Expand Down Expand Up @@ -220,9 +220,9 @@ def connect():
connection.fault = fault
try:
connection.handshakeClientSRP("test", "password")
print(" Good Fault %s" % (Fault.faultNames[fault]))
print(" Good Fault {0!s}".format((Fault.faultNames[fault])))
except TLSFaultError as e:
print(" BAD FAULT %s: %s" % (Fault.faultNames[fault], str(e)))
print(" BAD FAULT {0!s}: {1!s}".format(Fault.faultNames[fault], str(e)))
badFault = True

test_no += 1
Expand All @@ -247,9 +247,9 @@ def connect():
connection.fault = fault
try:
connection.handshakeClientSRP("test", "password")
print(" Good Fault %s" % (Fault.faultNames[fault]))
print(" Good Fault {0!s}".format((Fault.faultNames[fault])))
except TLSFaultError as e:
print(" BAD FAULT %s: %s" % (Fault.faultNames[fault], str(e)))
print(" BAD FAULT {0!s}: {1!s}".format(Fault.faultNames[fault], str(e)))
badFault = True

test_no += 1
Expand All @@ -261,9 +261,9 @@ def connect():
connection.fault = fault
try:
connection.handshakeClientCert()
print(" Good Fault %s" % (Fault.faultNames[fault]))
print(" Good Fault {0!s}".format((Fault.faultNames[fault])))
except TLSFaultError as e:
print(" BAD FAULT %s: %s" % (Fault.faultNames[fault], str(e)))
print(" BAD FAULT {0!s}: {1!s}".format(Fault.faultNames[fault], str(e)))
badFault = True

test_no += 1
Expand Down Expand Up @@ -316,9 +316,9 @@ def connect():
connection.fault = fault
try:
connection.handshakeClientCert(x509Chain, x509Key)
print(" Good Fault %s" % (Fault.faultNames[fault]))
print(" Good Fault {0!s}".format((Fault.faultNames[fault])))
except TLSFaultError as e:
print(" BAD FAULT %s: %s" % (Fault.faultNames[fault], str(e)))
print(" BAD FAULT {0!s}: {1!s}".format(Fault.faultNames[fault], str(e)))
badFault = True

test_no += 1
Expand Down Expand Up @@ -416,7 +416,7 @@ def connect():
settings.maxVersion = (3,1)
connection.handshakeClientCert(settings=settings)
testConnClient(connection)
print("%s %s" % (connection.getCipherName(), connection.getCipherImplementation()))
print("{0!s} {1!s}".format(connection.getCipherName(), connection.getCipherImplementation()))
connection.close()

test_no += 1
Expand Down Expand Up @@ -448,14 +448,14 @@ def connect():
settings.cipherNames = [cipher]
settings.cipherImplementations = [implementation, "python"]
connection.handshakeClientCert(settings=settings)
print("%s %s:" % (connection.getCipherName(), connection.getCipherImplementation()), end=' ')
print("{0!s} {1!s}:".format(connection.getCipherName(), connection.getCipherImplementation()), end=' ')

startTime = time.clock()
connection.write(b"hello"*10000)
h = connection.read(min=50000, max=50000)
stopTime = time.clock()
if stopTime-startTime:
print("100K exchanged at rate of %d bytes/sec" % int(100000/(stopTime-startTime)))
print("100K exchanged at rate of {0:d} bytes/sec".format(int(100000/(stopTime-startTime))))
else:
print("100K exchanged very fast")

Expand Down Expand Up @@ -657,9 +657,9 @@ def connect():
# python 3.4.2 doesn't have it though
context = ssl.create_default_context(\
cafile=os.path.join(dir, "serverX509Cert.pem"))
server = xmlrpclib.Server('https://%s:%s' % address, context=context)
server = xmlrpclib.Server('https://{0!s}:{1!s}'.format(*address), context=context)
except (TypeError, AttributeError):
server = xmlrpclib.Server('https://%s:%s' % address)
server = xmlrpclib.Server('https://{0!s}:{1!s}'.format(*address))

synchro.recv(1)
assert server.add(1,2) == 3
Expand All @@ -670,7 +670,7 @@ def connect():

print('Test {0} - good tlslite XMLRPC client'.format(test_no))
transport = XMLRPCTransport(ignoreAbruptClose=True)
server = xmlrpclib.Server('https://%s:%s' % address, transport)
server = xmlrpclib.Server('https://{0!s}:{1!s}'.format(*address), transport)
synchro.recv(1)
assert server.add(1,2) == 3
synchro.recv(1)
Expand All @@ -679,7 +679,7 @@ def connect():
test_no += 1

print('Test {0} - good XMLRPC ignored protocol'.format(test_no))
server = xmlrpclib.Server('http://%s:%s' % address, transport)
server = xmlrpclib.Server('http://{0!s}:{1!s}'.format(*address), transport)
synchro.recv(1)
assert server.add(1,2) == 3
synchro.recv(1)
Expand Down Expand Up @@ -1311,4 +1311,4 @@ def add(self, x, y): return x + y
elif sys.argv[1] == "server"[:len(sys.argv[1])]:
serverTestCmd(sys.argv[2:])
else:
printUsage("Unknown command: %s" % sys.argv[1])
printUsage("Unknown command: {0!s}".format(sys.argv[1]))
2 changes: 1 addition & 1 deletion tlslite/basedb.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def open(self):
self.db = anydbm.open(self.filename, "w") #raises anydbm.error
try:
if self.db["--Reserved--type"] != self.type:
raise ValueError("Not a %s database" % self.type)
raise ValueError("Not a {0!s} database".format(self.type))
except KeyError:
raise ValueError("Not a recognized database")

Expand Down
3 changes: 1 addition & 2 deletions tlslite/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ def __call__(self, connection):
if self.x509Fingerprint:
if chain.getFingerprint() != self.x509Fingerprint:
raise TLSFingerprintError(\
"X.509 fingerprint mismatch: %s, %s" % \
(chain.getFingerprint(), self.x509Fingerprint))
"X.509 fingerprint mismatch: {0!s}, {1!s}".format(chain.getFingerprint(), self.x509Fingerprint))
elif chain:
raise TLSAuthenticationTypeError()
else:
Expand Down
12 changes: 6 additions & 6 deletions tlslite/handshakesettings.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,28 +178,28 @@ def _sanityCheckPrimitivesNames(other):
unknownCiphers = [val for val in other.cipherNames \
if val not in ALL_CIPHER_NAMES]
if unknownCiphers:
raise ValueError("Unknown cipher name: %s" % unknownCiphers)
raise ValueError("Unknown cipher name: {0!s}".format(unknownCiphers))

unknownMacs = [val for val in other.macNames \
if val not in ALL_MAC_NAMES]
if unknownMacs:
raise ValueError("Unknown MAC name: %s" % unknownMacs)
raise ValueError("Unknown MAC name: {0!s}".format(unknownMacs))

unknownKex = [val for val in other.keyExchangeNames \
if val not in KEY_EXCHANGE_NAMES]
if unknownKex:
raise ValueError("Unknown key exchange name: %s" % unknownKex)
raise ValueError("Unknown key exchange name: {0!s}".format(unknownKex))

unknownImpl = [val for val in other.cipherImplementations \
if val not in CIPHER_IMPLEMENTATIONS]
if unknownImpl:
raise ValueError("Unknown cipher implementation: %s" % \
unknownImpl)
raise ValueError("Unknown cipher implementation: {0!s}".format( \
unknownImpl))

unknownType = [val for val in other.certificateTypes \
if val not in CERTIFICATE_TYPES]
if unknownType:
raise ValueError("Unknown certificate type: %s" % unknownType)
raise ValueError("Unknown certificate type: {0!s}".format(unknownType))

unknownCurve = [val for val in other.eccCurves \
if val not in ALL_CURVE_NAMES]
Expand Down
14 changes: 7 additions & 7 deletions tlslite/tlsconnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,12 +698,12 @@ def _clientGetServerHello(self, settings, clientHello):
if serverHello.server_version < settings.minVersion:
for result in self._sendError(\
AlertDescription.protocol_version,
"Too old version: %s" % str(serverHello.server_version)):
"Too old version: {0!s}".format(str(serverHello.server_version))):
yield result
if serverHello.server_version > settings.maxVersion:
for result in self._sendError(\
AlertDescription.protocol_version,
"Too new version: %s" % str(serverHello.server_version)):
"Too new version: {0!s}".format(str(serverHello.server_version))):
yield result
serverVer = serverHello.server_version
cipherSuites = CipherSuite.filterForVersion(clientHello.cipher_suites,
Expand Down Expand Up @@ -1035,11 +1035,11 @@ def _clientGetKeyFromChain(self, certificate, settings, tackExt=None):
publicKey = certChain.getEndEntityPublicKey()
if len(publicKey) < settings.minKeySize:
for result in self._sendError(AlertDescription.handshake_failure,
"Other party's public key too small: %d" % len(publicKey)):
"Other party's public key too small: {0:d}".format(len(publicKey))):
yield result
if len(publicKey) > settings.maxKeySize:
for result in self._sendError(AlertDescription.handshake_failure,
"Other party's public key too large: %d" % len(publicKey)):
"Other party's public key too large: {0:d}".format(len(publicKey))):
yield result

# If there's no TLS Extension, look for a TACK cert
Expand Down Expand Up @@ -1449,7 +1449,7 @@ def _serverGetClientHello(self, settings, certChain, verifierDB,
self.version = settings.minVersion
for result in self._sendError(\
AlertDescription.protocol_version,
"Too old version: %s" % str(clientHello.client_version)):
"Too old version: {0!s}".format(str(clientHello.client_version))):
yield result

# Sanity check the ALPN extension
Expand Down Expand Up @@ -1834,13 +1834,13 @@ def _serverCertKeyExchange(self, clientHello, serverHello,
if len(publicKey) < settings.minKeySize:
for result in self._sendError(\
AlertDescription.handshake_failure,
"Client's public key too small: %d" % len(publicKey)):
"Client's public key too small: {0:d}".format(len(publicKey))):
yield result

if len(publicKey) > settings.maxKeySize:
for result in self._sendError(\
AlertDescription.handshake_failure,
"Client's public key too large: %d" % len(publicKey)):
"Client's public key too large: {0:d}".format(len(publicKey))):
yield result

if not publicKey.verify(certificateVerify.signature, verifyBytes):
Expand Down
4 changes: 2 additions & 2 deletions tlslite/tlsrecordlayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ def _getMsg(self, expectedType, secondaryType=None, constructorType=None):
#alert nor renegotiation
for result in self._sendError(\
AlertDescription.unexpected_message,
"received type=%d" % recordHeader.type):
"received type={0:d}".format(recordHeader.type)):
yield result

break
Expand Down Expand Up @@ -760,7 +760,7 @@ def _getMsg(self, expectedType, secondaryType=None, constructorType=None):
if subType not in secondaryType:
for result in self._sendError(\
AlertDescription.unexpected_message,
"Expecting %s, got %s" % (str(secondaryType), subType)):
"Expecting {0!s}, got {1!s}".format(str(secondaryType), subType)):
yield result

#Update handshake hashes
Expand Down
Loading