Merge 'pr44': remove u"" marker from most files

refs #30
This commit is contained in:
Brian Warner 2016-06-04 15:13:21 -07:00
commit 7042a01369
13 changed files with 546 additions and 544 deletions

View File

@ -4,7 +4,7 @@ from .wordlist import (byte_to_even_word, byte_to_odd_word,
even_words_lowercase, odd_words_lowercase) even_words_lowercase, odd_words_lowercase)
def make_code(channel_id, code_length): def make_code(channel_id, code_length):
assert isinstance(channel_id, type(u"")), type(channel_id) assert isinstance(channel_id, type("")), type(channel_id)
words = [] words = []
for i in range(code_length): for i in range(code_length):
# we start with an "odd word" # we start with an "odd word"
@ -12,7 +12,7 @@ def make_code(channel_id, code_length):
words.append(byte_to_odd_word[os.urandom(1)].lower()) words.append(byte_to_odd_word[os.urandom(1)].lower())
else: else:
words.append(byte_to_even_word[os.urandom(1)].lower()) words.append(byte_to_even_word[os.urandom(1)].lower())
return u"%s-%s" % (channel_id, u"-".join(words)) return "%s-%s" % (channel_id, "-".join(words))
def extract_channel_id(code): def extract_channel_id(code):
channel_id = int(code.split("-")[0]) channel_id = int(code.split("-")[0])

View File

@ -68,9 +68,9 @@ def show_usage(args):
" ORDER BY `started` ASC LIMIT ?", " ORDER BY `started` ASC LIMIT ?",
(args.n,)) (args.n,))
for row in c.fetchall(): for row in c.fetchall():
if row["type"] == u"rendezvous": if row["type"] == "rendezvous":
counters = rendezvous_counters counters = rendezvous_counters
elif row["type"] == u"transit": elif row["type"] == "transit":
counters = transit_counters counters = transit_counters
total_transit_bytes += row["total_bytes"] total_transit_bytes += row["total_bytes"]
else: else:

View File

@ -63,7 +63,7 @@ class Mailbox:
def open(self, side, when): def open(self, side, when):
# requires caller to db.commit() # requires caller to db.commit()
assert isinstance(side, type(u"")), type(side) assert isinstance(side, type("")), type(side)
db = self._db db = self._db
row = db.execute("SELECT * FROM `mailboxes`" row = db.execute("SELECT * FROM `mailboxes`"
" WHERE `app_id`=? AND `id`=?", " WHERE `app_id`=? AND `id`=?",
@ -126,7 +126,7 @@ class Mailbox:
self.broadcast_message(sm) self.broadcast_message(sm)
def close(self, side, mood, when): def close(self, side, mood, when):
assert isinstance(side, type(u"")), type(side) assert isinstance(side, type("")), type(side)
db = self._db db = self._db
row = db.execute("SELECT * FROM `mailboxes`" row = db.execute("SELECT * FROM `mailboxes`"
" WHERE `app_id`=? AND `id`=?", " WHERE `app_id`=? AND `id`=?",
@ -200,7 +200,7 @@ class AppNamespace:
for size in range(1,4): # stick to 1-999 for now for size in range(1,4): # stick to 1-999 for now
available = set() available = set()
for id_int in range(10**(size-1), 10**size): for id_int in range(10**(size-1), 10**size):
id = u"%d" % id_int id = "%d" % id_int
if id not in claimed: if id not in claimed:
available.add(id) available.add(id)
if available: if available:
@ -208,7 +208,7 @@ class AppNamespace:
# ouch, 999 currently claimed. Try random ones for a while. # ouch, 999 currently claimed. Try random ones for a while.
for tries in range(1000): for tries in range(1000):
id_int = random.randrange(1000, 1000*1000) id_int = random.randrange(1000, 1000*1000)
id = u"%d" % id_int id = "%d" % id_int
if id not in claimed: if id not in claimed:
return id return id
raise ValueError("unable to find a free nameplate-id") raise ValueError("unable to find a free nameplate-id")
@ -226,8 +226,8 @@ class AppNamespace:
# * started or second will be populated # * started or second will be populated
# * a mailbox id will be created, but not a mailbox row # * a mailbox id will be created, but not a mailbox row
# (ids are randomly unique, so we can defer creation until 'open') # (ids are randomly unique, so we can defer creation until 'open')
assert isinstance(nameplate_id, type(u"")), type(nameplate_id) assert isinstance(nameplate_id, type("")), type(nameplate_id)
assert isinstance(side, type(u"")), type(side) assert isinstance(side, type("")), type(side)
db = self._db db = self._db
row = db.execute("SELECT * FROM `nameplates`" row = db.execute("SELECT * FROM `nameplates`"
" WHERE `app_id`=? AND `id`=?", " WHERE `app_id`=? AND `id`=?",
@ -271,8 +271,8 @@ class AppNamespace:
# * if the nameplate is now unused: # * if the nameplate is now unused:
# * mailbox.nameplate_closed will be populated # * mailbox.nameplate_closed will be populated
# * the nameplate row will be removed # * the nameplate row will be removed
assert isinstance(nameplate_id, type(u"")), type(nameplate_id) assert isinstance(nameplate_id, type("")), type(nameplate_id)
assert isinstance(side, type(u"")), type(side) assert isinstance(side, type("")), type(side)
db = self._db db = self._db
row = db.execute("SELECT * FROM `nameplates`" row = db.execute("SELECT * FROM `nameplates`"
" WHERE `app_id`=? AND `id`=?", " WHERE `app_id`=? AND `id`=?",
@ -312,18 +312,18 @@ class AppNamespace:
if row["second"]: if row["second"]:
waiting_time = row["second"] - row["started"] waiting_time = row["second"] - row["started"]
total_time = delete_time - row["started"] total_time = delete_time - row["started"]
result = u"lonely" result = "lonely"
if row["second"]: if row["second"]:
result = u"happy" result = "happy"
if pruned: if pruned:
result = u"pruney" result = "pruney"
if row["crowded"]: if row["crowded"]:
result = u"crowded" result = "crowded"
return Usage(started=started, waiting_time=waiting_time, return Usage(started=started, waiting_time=waiting_time,
total_time=total_time, result=result) total_time=total_time, result=result)
def open_mailbox(self, mailbox_id, side, when): def open_mailbox(self, mailbox_id, side, when):
assert isinstance(mailbox_id, type(u"")), type(mailbox_id) assert isinstance(mailbox_id, type("")), type(mailbox_id)
db = self._db db = self._db
if not mailbox_id in self._mailboxes: if not mailbox_id in self._mailboxes:
if self._log_requests: if self._log_requests:
@ -379,23 +379,23 @@ class AppNamespace:
total_time = delete_time - row["started"] total_time = delete_time - row["started"]
if num_sides == 0: if num_sides == 0:
result = u"quiet" result = "quiet"
elif num_sides == 1: elif num_sides == 1:
result = u"lonely" result = "lonely"
else: else:
result = u"happy" result = "happy"
moods = set([row["first_mood"], second_mood]) moods = set([row["first_mood"], second_mood])
if u"lonely" in moods: if "lonely" in moods:
result = u"lonely" result = "lonely"
if u"errory" in moods: if "errory" in moods:
result = u"errory" result = "errory"
if u"scary" in moods: if "scary" in moods:
result = u"scary" result = "scary"
if pruned: if pruned:
result = u"pruney" result = "pruney"
if row["crowded"]: if row["crowded"]:
result = u"crowded" result = "crowded"
return Usage(started=started, waiting_time=waiting_time, return Usage(started=started, waiting_time=waiting_time,
total_time=total_time, result=result) total_time=total_time, result=result)
@ -512,7 +512,7 @@ class AppNamespace:
log.msg(" deleting mailbox", mailbox_id) log.msg(" deleting mailbox", mailbox_id)
self._summarize_mailbox_and_store(mailbox_id, self._summarize_mailbox_and_store(mailbox_id,
all_mailbox_rows[mailbox_id], all_mailbox_rows[mailbox_id],
u"pruney", now, pruned=True) "pruney", now, pruned=True)
db.execute("DELETE FROM `messages`" db.execute("DELETE FROM `messages`"
" WHERE `app_id`=? AND `mailbox_id`=?", " WHERE `app_id`=? AND `mailbox_id`=?",
(self._app_id, mailbox_id)) (self._app_id, mailbox_id))
@ -547,7 +547,7 @@ class Rendezvous(service.MultiService):
return self._log_requests return self._log_requests
def get_app(self, app_id): def get_app(self, app_id):
assert isinstance(app_id, type(u"")) assert isinstance(app_id, type(""))
if not app_id in self._apps: if not app_id in self._apps:
if self._log_requests: if self._log_requests:
log.msg("spawning app_id %s" % (app_id,)) log.msg("spawning app_id %s" % (app_id,))

View File

@ -164,7 +164,7 @@ class WebSocketRendezvous(websocket.WebSocketServerProtocol):
if self._did_allocate: if self._did_allocate:
raise Error("you already allocated one, don't be greedy") raise Error("you already allocated one, don't be greedy")
nameplate_id = self._app.allocate_nameplate(self._side, server_rx) nameplate_id = self._app.allocate_nameplate(self._side, server_rx)
assert isinstance(nameplate_id, type(u"")) assert isinstance(nameplate_id, type(""))
self._did_allocate = True self._did_allocate = True
self.send("allocated", nameplate=nameplate_id) self.send("allocated", nameplate=nameplate_id)
@ -172,7 +172,7 @@ class WebSocketRendezvous(websocket.WebSocketServerProtocol):
if "nameplate" not in msg: if "nameplate" not in msg:
raise Error("claim requires 'nameplate'") raise Error("claim requires 'nameplate'")
nameplate_id = msg["nameplate"] nameplate_id = msg["nameplate"]
assert isinstance(nameplate_id, type(u"")), type(nameplate_id) assert isinstance(nameplate_id, type("")), type(nameplate_id)
self._nameplate_id = nameplate_id self._nameplate_id = nameplate_id
try: try:
mailbox_id = self._app.claim_nameplate(nameplate_id, self._side, mailbox_id = self._app.claim_nameplate(nameplate_id, self._side,
@ -195,7 +195,7 @@ class WebSocketRendezvous(websocket.WebSocketServerProtocol):
if "mailbox" not in msg: if "mailbox" not in msg:
raise Error("open requires 'mailbox'") raise Error("open requires 'mailbox'")
mailbox_id = msg["mailbox"] mailbox_id = msg["mailbox"]
assert isinstance(mailbox_id, type(u"")) assert isinstance(mailbox_id, type(""))
self._mailbox = self._app.open_mailbox(mailbox_id, self._side, self._mailbox = self._app.open_mailbox(mailbox_id, self._side,
server_rx) server_rx)
def _send(sm): def _send(sm):

View File

@ -115,14 +115,14 @@ class TransitConnection(protocol.Protocol):
finished = time.time() finished = time.time()
if not self._had_buddy: # 1 if not self._had_buddy: # 1
total_time = finished - self._started total_time = finished - self._started
self.factory.recordUsage(self._started, u"lonely", 0, self.factory.recordUsage(self._started, "lonely", 0,
total_time, None) total_time, None)
if self._had_buddy and self._buddy: # 2,4 if self._had_buddy and self._buddy: # 2,4
total_bytes = self._total_sent + self._buddy._total_sent total_bytes = self._total_sent + self._buddy._total_sent
starts = [self._started, self._buddy._started] starts = [self._started, self._buddy._started]
total_time = finished - min(starts) total_time = finished - min(starts)
waiting_time = max(starts) - min(starts) waiting_time = max(starts) - min(starts)
self.factory.recordUsage(self._started, u"happy", total_bytes, self.factory.recordUsage(self._started, "happy", total_bytes,
total_time, waiting_time) total_time, waiting_time)
def disconnect(self): def disconnect(self):
@ -130,7 +130,7 @@ class TransitConnection(protocol.Protocol):
self.factory.transitFailed(self) self.factory.transitFailed(self)
finished = time.time() finished = time.time()
total_time = finished - self._started total_time = finished - self._started
self.factory.recordUsage(self._started, u"errory", 0, self.factory.recordUsage(self._started, "errory", 0,
total_time, None) total_time, None)
class Transit(protocol.ServerFactory, service.MultiService): class Transit(protocol.ServerFactory, service.MultiService):

View File

@ -1,3 +1,4 @@
# no unicode_literals untill twisted update
from twisted.application import service from twisted.application import service
from twisted.internet import reactor, defer from twisted.internet import reactor, defer
from twisted.python import log from twisted.python import log

View File

@ -241,7 +241,7 @@ class PregeneratedCode(ServerBase, ScriptsBase, unittest.TestCase):
common_args = ["--hide-progress", common_args = ["--hide-progress",
"--relay-url", self.relayurl, "--relay-url", self.relayurl,
"--transit-helper", ""] "--transit-helper", ""]
code = u"1-abc" code = "1-abc"
message = "test message" message = "test message"
send_args = common_args + [ send_args = common_args + [
@ -443,7 +443,7 @@ class PregeneratedCode(ServerBase, ScriptsBase, unittest.TestCase):
common_args = ["--hide-progress", "--no-listen", common_args = ["--hide-progress", "--no-listen",
"--relay-url", self.relayurl, "--relay-url", self.relayurl,
"--transit-helper", ""] "--transit-helper", ""]
code = u"1-abc" code = "1-abc"
message = "test message" message = "test message"
send_args = common_args + [ "send", "--code", code ] send_args = common_args + [ "send", "--code", code ]
@ -527,7 +527,7 @@ class PregeneratedCode(ServerBase, ScriptsBase, unittest.TestCase):
class NotWelcome(ServerBase, unittest.TestCase): class NotWelcome(ServerBase, unittest.TestCase):
def setUp(self): def setUp(self):
self._setup_relay(error=u"please upgrade XYZ") self._setup_relay(error="please upgrade XYZ")
@inlineCallbacks @inlineCallbacks
def test_sender(self): def test_sender(self):
@ -535,7 +535,7 @@ class NotWelcome(ServerBase, unittest.TestCase):
"--relay-url", self.relayurl, "--relay-url", self.relayurl,
"--transit-helper", ""] "--transit-helper", ""]
send_args = common_args + [ "send", "--text", "hi", send_args = common_args + [ "send", "--text", "hi",
"--code", u"1-abc" ] "--code", "1-abc" ]
sargs = runner.parser.parse_args(send_args) sargs = runner.parser.parse_args(send_args)
sargs.cwd = self.mktemp() sargs.cwd = self.mktemp()
sargs.stdout = io.StringIO() sargs.stdout = io.StringIO()
@ -551,7 +551,7 @@ class NotWelcome(ServerBase, unittest.TestCase):
common_args = ["--hide-progress", "--no-listen", common_args = ["--hide-progress", "--no-listen",
"--relay-url", self.relayurl, "--relay-url", self.relayurl,
"--transit-helper", ""] "--transit-helper", ""]
receive_args = common_args + [ "receive", u"1-abc" ] receive_args = common_args + [ "receive", "1-abc" ]
rargs = runner.parser.parse_args(receive_args) rargs = runner.parser.parse_args(receive_args)
rargs.cwd = self.mktemp() rargs.cwd = self.mktemp()
rargs.stdout = io.StringIO() rargs.stdout = io.StringIO()
@ -566,7 +566,7 @@ class Cleanup(ServerBase, unittest.TestCase):
@inlineCallbacks @inlineCallbacks
def test_text(self): def test_text(self):
# the rendezvous channel should be deleted after success # the rendezvous channel should be deleted after success
code = u"1-abc" code = "1-abc"
common_args = ["--hide-progress", common_args = ["--hide-progress",
"--relay-url", self.relayurl, "--relay-url", self.relayurl,
"--transit-helper", ""] "--transit-helper", ""]
@ -601,12 +601,12 @@ class Cleanup(ServerBase, unittest.TestCase):
sargs = runner.parser.parse_args(common_args + sargs = runner.parser.parse_args(common_args +
["send", ["send",
"--text", "secret message", "--text", "secret message",
"--code", u"1-abc"]) "--code", "1-abc"])
sargs.stdout = io.StringIO() sargs.stdout = io.StringIO()
sargs.stderr = io.StringIO() sargs.stderr = io.StringIO()
sargs.timing = DebugTiming() sargs.timing = DebugTiming()
rargs = runner.parser.parse_args(common_args + rargs = runner.parser.parse_args(common_args +
["receive", u"1-WRONG"]) ["receive", "1-WRONG"])
rargs.stdout = io.StringIO() rargs.stdout = io.StringIO()
rargs.stderr = io.StringIO() rargs.stderr = io.StringIO()
rargs.timing = DebugTiming() rargs.timing = DebugTiming()
@ -624,7 +624,7 @@ class Cleanup(ServerBase, unittest.TestCase):
class ExtractFile(unittest.TestCase): class ExtractFile(unittest.TestCase):
def test_filenames(self): def test_filenames(self):
args = mock.Mock() args = mock.Mock()
args.relay_url = u"" args.relay_url = ""
ef = cmd_receive.TwistedReceiver(args)._extract_file ef = cmd_receive.TwistedReceiver(args)._extract_file
extract_dir = os.path.abspath(self.mktemp()) extract_dir = os.path.abspath(self.mktemp())

View File

@ -16,18 +16,18 @@ from ..server.database import get_db
class Server(ServerBase, unittest.TestCase): class Server(ServerBase, unittest.TestCase):
def test_apps(self): def test_apps(self):
app1 = self._rendezvous.get_app(u"appid1") app1 = self._rendezvous.get_app("appid1")
self.assertIdentical(app1, self._rendezvous.get_app(u"appid1")) self.assertIdentical(app1, self._rendezvous.get_app("appid1"))
app2 = self._rendezvous.get_app(u"appid2") app2 = self._rendezvous.get_app("appid2")
self.assertNotIdentical(app1, app2) self.assertNotIdentical(app1, app2)
def test_nameplate_allocation(self): def test_nameplate_allocation(self):
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
nids = set() nids = set()
# this takes a second, and claims all the short-numbered nameplates # this takes a second, and claims all the short-numbered nameplates
def add(): def add():
nameplate_id = app.allocate_nameplate(u"side1", 0) nameplate_id = app.allocate_nameplate("side1", 0)
self.assertEqual(type(nameplate_id), type(u"")) self.assertEqual(type(nameplate_id), type(""))
nid = int(nameplate_id) nid = int(nameplate_id)
nids.add(nid) nids.add(nid)
for i in range(9): add() for i in range(9): add()
@ -53,41 +53,41 @@ class Server(ServerBase, unittest.TestCase):
(nameplate_id,)).fetchone() (nameplate_id,)).fetchone()
def test_nameplate(self): def test_nameplate(self):
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
nameplate_id = app.allocate_nameplate(u"side1", 0) nameplate_id = app.allocate_nameplate("side1", 0)
self.assertEqual(type(nameplate_id), type(u"")) self.assertEqual(type(nameplate_id), type(""))
nid = int(nameplate_id) nid = int(nameplate_id)
self.assert_(0 < nid < 10, nid) self.assert_(0 < nid < 10, nid)
self.assertEqual(app.get_nameplate_ids(), set([nameplate_id])) self.assertEqual(app.get_nameplate_ids(), set([nameplate_id]))
# allocate also does a claim # allocate also does a claim
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
self.assertEqual(row["crowded"], False) self.assertEqual(row["crowded"], False)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
self.assertEqual(row["second"], None) self.assertEqual(row["second"], None)
mailbox_id = app.claim_nameplate(nameplate_id, u"side1", 1) mailbox_id = app.claim_nameplate(nameplate_id, "side1", 1)
self.assertEqual(type(mailbox_id), type(u"")) self.assertEqual(type(mailbox_id), type(""))
# duplicate claims by the same side are combined # duplicate claims by the same side are combined
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
mailbox_id2 = app.claim_nameplate(nameplate_id, u"side1", 2) mailbox_id2 = app.claim_nameplate(nameplate_id, "side1", 2)
self.assertEqual(mailbox_id, mailbox_id2) self.assertEqual(mailbox_id, mailbox_id2)
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
self.assertEqual(row["second"], None) self.assertEqual(row["second"], None)
# claim by the second side is new # claim by the second side is new
mailbox_id3 = app.claim_nameplate(nameplate_id, u"side2", 3) mailbox_id3 = app.claim_nameplate(nameplate_id, "side2", 3)
self.assertEqual(mailbox_id, mailbox_id3) self.assertEqual(mailbox_id, mailbox_id3)
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], u"side2") self.assertEqual(row["side2"], "side2")
self.assertEqual(row["crowded"], False) self.assertEqual(row["crowded"], False)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
self.assertEqual(row["second"], 3) self.assertEqual(row["second"], 3)
@ -95,43 +95,43 @@ class Server(ServerBase, unittest.TestCase):
# a third claim marks the nameplate as "crowded", but leaves the two # a third claim marks the nameplate as "crowded", but leaves the two
# existing claims alone # existing claims alone
self.assertRaises(rendezvous.CrowdedError, self.assertRaises(rendezvous.CrowdedError,
app.claim_nameplate, nameplate_id, u"side3", 0) app.claim_nameplate, nameplate_id, "side3", 0)
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], u"side2") self.assertEqual(row["side2"], "side2")
self.assertEqual(row["crowded"], True) self.assertEqual(row["crowded"], True)
# releasing a non-existent nameplate is ignored # releasing a non-existent nameplate is ignored
app.release_nameplate(nameplate_id+u"not", u"side4", 0) app.release_nameplate(nameplate_id+"not", "side4", 0)
# releasing a side that never claimed the nameplate is ignored # releasing a side that never claimed the nameplate is ignored
app.release_nameplate(nameplate_id, u"side4", 0) app.release_nameplate(nameplate_id, "side4", 0)
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], u"side2") self.assertEqual(row["side2"], "side2")
# releasing one side leaves the second claim # releasing one side leaves the second claim
app.release_nameplate(nameplate_id, u"side1", 5) app.release_nameplate(nameplate_id, "side1", 5)
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row["side1"], u"side2") self.assertEqual(row["side1"], "side2")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
# releasing one side multiple times is ignored # releasing one side multiple times is ignored
app.release_nameplate(nameplate_id, u"side1", 5) app.release_nameplate(nameplate_id, "side1", 5)
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row["side1"], u"side2") self.assertEqual(row["side1"], "side2")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
# releasing the second side frees the nameplate, and adds usage # releasing the second side frees the nameplate, and adds usage
app.release_nameplate(nameplate_id, u"side2", 6) app.release_nameplate(nameplate_id, "side2", 6)
row = self._nameplate(app, nameplate_id) row = self._nameplate(app, nameplate_id)
self.assertEqual(row, None) self.assertEqual(row, None)
usage = app._db.execute("SELECT * FROM `nameplate_usage`").fetchone() usage = app._db.execute("SELECT * FROM `nameplate_usage`").fetchone()
self.assertEqual(usage["app_id"], u"appid") self.assertEqual(usage["app_id"], "appid")
self.assertEqual(usage["started"], 0) self.assertEqual(usage["started"], 0)
self.assertEqual(usage["waiting_time"], 3) self.assertEqual(usage["waiting_time"], 3)
self.assertEqual(usage["total_time"], 6) self.assertEqual(usage["total_time"], 6)
self.assertEqual(usage["result"], u"crowded") self.assertEqual(usage["result"], "crowded")
def _mailbox(self, app, mailbox_id): def _mailbox(self, app, mailbox_id):
@ -140,12 +140,12 @@ class Server(ServerBase, unittest.TestCase):
(mailbox_id,)).fetchone() (mailbox_id,)).fetchone()
def test_mailbox(self): def test_mailbox(self):
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
mailbox_id = u"mid" mailbox_id = "mid"
m1 = app.open_mailbox(mailbox_id, u"side1", 0) m1 = app.open_mailbox(mailbox_id, "side1", 0)
row = self._mailbox(app, mailbox_id) row = self._mailbox(app, mailbox_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
self.assertEqual(row["crowded"], False) self.assertEqual(row["crowded"], False)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
@ -153,55 +153,55 @@ class Server(ServerBase, unittest.TestCase):
# opening the same mailbox twice, by the same side, gets the same # opening the same mailbox twice, by the same side, gets the same
# object # object
self.assertIdentical(m1, app.open_mailbox(mailbox_id, u"side1", 1)) self.assertIdentical(m1, app.open_mailbox(mailbox_id, "side1", 1))
row = self._mailbox(app, mailbox_id) row = self._mailbox(app, mailbox_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
self.assertEqual(row["crowded"], False) self.assertEqual(row["crowded"], False)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
self.assertEqual(row["second"], None) self.assertEqual(row["second"], None)
# opening a second side gets the same object, and adds a new claim # opening a second side gets the same object, and adds a new claim
self.assertIdentical(m1, app.open_mailbox(mailbox_id, u"side2", 2)) self.assertIdentical(m1, app.open_mailbox(mailbox_id, "side2", 2))
row = self._mailbox(app, mailbox_id) row = self._mailbox(app, mailbox_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], u"side2") self.assertEqual(row["side2"], "side2")
self.assertEqual(row["crowded"], False) self.assertEqual(row["crowded"], False)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
self.assertEqual(row["second"], 2) self.assertEqual(row["second"], 2)
# a third open marks it as crowded # a third open marks it as crowded
self.assertRaises(rendezvous.CrowdedError, self.assertRaises(rendezvous.CrowdedError,
app.open_mailbox, mailbox_id, u"side3", 3) app.open_mailbox, mailbox_id, "side3", 3)
row = self._mailbox(app, mailbox_id) row = self._mailbox(app, mailbox_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], u"side2") self.assertEqual(row["side2"], "side2")
self.assertEqual(row["crowded"], True) self.assertEqual(row["crowded"], True)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
self.assertEqual(row["second"], 2) self.assertEqual(row["second"], 2)
# closing a side that never claimed the mailbox is ignored # closing a side that never claimed the mailbox is ignored
m1.close(u"side4", u"mood", 4) m1.close("side4", "mood", 4)
row = self._mailbox(app, mailbox_id) row = self._mailbox(app, mailbox_id)
self.assertEqual(row["side1"], u"side1") self.assertEqual(row["side1"], "side1")
self.assertEqual(row["side2"], u"side2") self.assertEqual(row["side2"], "side2")
self.assertEqual(row["crowded"], True) self.assertEqual(row["crowded"], True)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
self.assertEqual(row["second"], 2) self.assertEqual(row["second"], 2)
# closing one side leaves the second claim # closing one side leaves the second claim
m1.close(u"side1", u"mood", 5) m1.close("side1", "mood", 5)
row = self._mailbox(app, mailbox_id) row = self._mailbox(app, mailbox_id)
self.assertEqual(row["side1"], u"side2") self.assertEqual(row["side1"], "side2")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
self.assertEqual(row["crowded"], True) self.assertEqual(row["crowded"], True)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
self.assertEqual(row["second"], 2) self.assertEqual(row["second"], 2)
# closing one side multiple is ignored # closing one side multiple is ignored
m1.close(u"side1", u"mood", 6) m1.close("side1", "mood", 6)
row = self._mailbox(app, mailbox_id) row = self._mailbox(app, mailbox_id)
self.assertEqual(row["side1"], u"side2") self.assertEqual(row["side1"], "side2")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
self.assertEqual(row["crowded"], True) self.assertEqual(row["crowded"], True)
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
@ -211,17 +211,17 @@ class Server(ServerBase, unittest.TestCase):
m1.add_listener("handle1", l1.append, stop1_f) m1.add_listener("handle1", l1.append, stop1_f)
# closing the second side frees the mailbox, and adds usage # closing the second side frees the mailbox, and adds usage
m1.close(u"side2", u"mood", 7) m1.close("side2", "mood", 7)
self.assertEqual(stop1, [True]) self.assertEqual(stop1, [True])
row = self._mailbox(app, mailbox_id) row = self._mailbox(app, mailbox_id)
self.assertEqual(row, None) self.assertEqual(row, None)
usage = app._db.execute("SELECT * FROM `mailbox_usage`").fetchone() usage = app._db.execute("SELECT * FROM `mailbox_usage`").fetchone()
self.assertEqual(usage["app_id"], u"appid") self.assertEqual(usage["app_id"], "appid")
self.assertEqual(usage["started"], 0) self.assertEqual(usage["started"], 0)
self.assertEqual(usage["waiting_time"], 2) self.assertEqual(usage["waiting_time"], 2)
self.assertEqual(usage["total_time"], 7) self.assertEqual(usage["total_time"], 7)
self.assertEqual(usage["result"], u"crowded") self.assertEqual(usage["result"], "crowded")
def _messages(self, app): def _messages(self, app):
c = app._db.execute("SELECT * FROM `messages`" c = app._db.execute("SELECT * FROM `messages`"
@ -229,85 +229,85 @@ class Server(ServerBase, unittest.TestCase):
return c.fetchall() return c.fetchall()
def test_messages(self): def test_messages(self):
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
mailbox_id = u"mid" mailbox_id = "mid"
m1 = app.open_mailbox(mailbox_id, u"side1", 0) m1 = app.open_mailbox(mailbox_id, "side1", 0)
m1.add_message(SidedMessage(side=u"side1", phase=u"phase", m1.add_message(SidedMessage(side="side1", phase="phase",
body=u"body", server_rx=1, body="body", server_rx=1,
msg_id=u"msgid")) msg_id="msgid"))
msgs = self._messages(app) msgs = self._messages(app)
self.assertEqual(len(msgs), 1) self.assertEqual(len(msgs), 1)
self.assertEqual(msgs[0]["body"], u"body") self.assertEqual(msgs[0]["body"], "body")
l1 = []; stop1 = []; stop1_f = lambda: stop1.append(True) l1 = []; stop1 = []; stop1_f = lambda: stop1.append(True)
l2 = []; stop2 = []; stop2_f = lambda: stop2.append(True) l2 = []; stop2 = []; stop2_f = lambda: stop2.append(True)
old = m1.add_listener("handle1", l1.append, stop1_f) old = m1.add_listener("handle1", l1.append, stop1_f)
self.assertEqual(len(old), 1) self.assertEqual(len(old), 1)
self.assertEqual(old[0].side, u"side1") self.assertEqual(old[0].side, "side1")
self.assertEqual(old[0].body, u"body") self.assertEqual(old[0].body, "body")
m1.add_message(SidedMessage(side=u"side1", phase=u"phase2", m1.add_message(SidedMessage(side="side1", phase="phase2",
body=u"body2", server_rx=1, body="body2", server_rx=1,
msg_id=u"msgid")) msg_id="msgid"))
self.assertEqual(len(l1), 1) self.assertEqual(len(l1), 1)
self.assertEqual(l1[0].body, u"body2") self.assertEqual(l1[0].body, "body2")
old = m1.add_listener("handle2", l2.append, stop2_f) old = m1.add_listener("handle2", l2.append, stop2_f)
self.assertEqual(len(old), 2) self.assertEqual(len(old), 2)
m1.add_message(SidedMessage(side=u"side1", phase=u"phase3", m1.add_message(SidedMessage(side="side1", phase="phase3",
body=u"body3", server_rx=1, body="body3", server_rx=1,
msg_id=u"msgid")) msg_id="msgid"))
self.assertEqual(len(l1), 2) self.assertEqual(len(l1), 2)
self.assertEqual(l1[-1].body, u"body3") self.assertEqual(l1[-1].body, "body3")
self.assertEqual(len(l2), 1) self.assertEqual(len(l2), 1)
self.assertEqual(l2[-1].body, u"body3") self.assertEqual(l2[-1].body, "body3")
m1.remove_listener("handle1") m1.remove_listener("handle1")
m1.add_message(SidedMessage(side=u"side1", phase=u"phase4", m1.add_message(SidedMessage(side="side1", phase="phase4",
body=u"body4", server_rx=1, body="body4", server_rx=1,
msg_id=u"msgid")) msg_id="msgid"))
self.assertEqual(len(l1), 2) self.assertEqual(len(l1), 2)
self.assertEqual(l1[-1].body, u"body3") self.assertEqual(l1[-1].body, "body3")
self.assertEqual(len(l2), 2) self.assertEqual(len(l2), 2)
self.assertEqual(l2[-1].body, u"body4") self.assertEqual(l2[-1].body, "body4")
m1._shutdown() m1._shutdown()
self.assertEqual(stop1, []) self.assertEqual(stop1, [])
self.assertEqual(stop2, [True]) self.assertEqual(stop2, [True])
# message adds are not idempotent: clients filter duplicates # message adds are not idempotent: clients filter duplicates
m1.add_message(SidedMessage(side=u"side1", phase=u"phase", m1.add_message(SidedMessage(side="side1", phase="phase",
body=u"body", server_rx=1, body="body", server_rx=1,
msg_id=u"msgid")) msg_id="msgid"))
msgs = self._messages(app) msgs = self._messages(app)
self.assertEqual(len(msgs), 5) self.assertEqual(len(msgs), 5)
self.assertEqual(msgs[-1]["body"], u"body") self.assertEqual(msgs[-1]["body"], "body")
class Prune(unittest.TestCase): class Prune(unittest.TestCase):
def test_apps(self): def test_apps(self):
rv = rendezvous.Rendezvous(get_db(":memory:"), None, None) rv = rendezvous.Rendezvous(get_db(":memory:"), None, None)
app = rv.get_app(u"appid") app = rv.get_app("appid")
app.allocate_nameplate(u"side", 121) app.allocate_nameplate("side", 121)
app.prune = mock.Mock() app.prune = mock.Mock()
rv.prune(now=123, old=122) rv.prune(now=123, old=122)
self.assertEqual(app.prune.mock_calls, [mock.call(123, 122)]) self.assertEqual(app.prune.mock_calls, [mock.call(123, 122)])
def test_active(self): def test_active(self):
rv = rendezvous.Rendezvous(get_db(":memory:"), None, None) rv = rendezvous.Rendezvous(get_db(":memory:"), None, None)
app = rv.get_app(u"appid1") app = rv.get_app("appid1")
self.assertFalse(app.is_active()) self.assertFalse(app.is_active())
mb = app.open_mailbox(u"mbid", u"side1", 0) mb = app.open_mailbox("mbid", "side1", 0)
self.assertFalse(mb.is_active()) self.assertFalse(mb.is_active())
self.assertFalse(app.is_active()) self.assertFalse(app.is_active())
mb.add_listener(u"handle", None, None) mb.add_listener("handle", None, None)
self.assertTrue(mb.is_active()) self.assertTrue(mb.is_active())
self.assertTrue(app.is_active()) self.assertTrue(app.is_active())
mb.remove_listener(u"handle") mb.remove_listener("handle")
self.assertFalse(mb.is_active()) self.assertFalse(mb.is_active())
self.assertFalse(app.is_active()) self.assertFalse(app.is_active())
@ -322,35 +322,35 @@ class Prune(unittest.TestCase):
new_mailboxes = set() new_mailboxes = set()
new_messages = set() new_messages = set()
APPID = u"appid" APPID = "appid"
app = rv.get_app(APPID) app = rv.get_app(APPID)
# Exercise the first-vs-second newness tests. These nameplates have # Exercise the first-vs-second newness tests. These nameplates have
# no mailbox. # no mailbox.
app.claim_nameplate(u"np-1", u"side1", 1) app.claim_nameplate("np-1", "side1", 1)
app.claim_nameplate(u"np-2", u"side1", 1) app.claim_nameplate("np-2", "side1", 1)
app.claim_nameplate(u"np-2", u"side2", 2) app.claim_nameplate("np-2", "side2", 2)
app.claim_nameplate(u"np-3", u"side1", 60) app.claim_nameplate("np-3", "side1", 60)
new_nameplates.add(u"np-3") new_nameplates.add("np-3")
app.claim_nameplate(u"np-4", u"side1", 1) app.claim_nameplate("np-4", "side1", 1)
app.claim_nameplate(u"np-4", u"side2", 60) app.claim_nameplate("np-4", "side2", 60)
new_nameplates.add(u"np-4") new_nameplates.add("np-4")
app.claim_nameplate(u"np-5", u"side1", 60) app.claim_nameplate("np-5", "side1", 60)
app.claim_nameplate(u"np-5", u"side2", 61) app.claim_nameplate("np-5", "side2", 61)
new_nameplates.add(u"np-5") new_nameplates.add("np-5")
# same for mailboxes # same for mailboxes
app.open_mailbox(u"mb-11", u"side1", 1) app.open_mailbox("mb-11", "side1", 1)
app.open_mailbox(u"mb-12", u"side1", 1) app.open_mailbox("mb-12", "side1", 1)
app.open_mailbox(u"mb-12", u"side2", 2) app.open_mailbox("mb-12", "side2", 2)
app.open_mailbox(u"mb-13", u"side1", 60) app.open_mailbox("mb-13", "side1", 60)
new_mailboxes.add(u"mb-13") new_mailboxes.add("mb-13")
app.open_mailbox(u"mb-14", u"side1", 1) app.open_mailbox("mb-14", "side1", 1)
app.open_mailbox(u"mb-14", u"side2", 60) app.open_mailbox("mb-14", "side2", 60)
new_mailboxes.add(u"mb-14") new_mailboxes.add("mb-14")
app.open_mailbox(u"mb-15", u"side1", 60) app.open_mailbox("mb-15", "side1", 60)
app.open_mailbox(u"mb-15", u"side2", 61) app.open_mailbox("mb-15", "side2", 61)
new_mailboxes.add(u"mb-15") new_mailboxes.add("mb-15")
rv.prune(now=123, old=50) rv.prune(now=123, old=50)
@ -387,7 +387,7 @@ class Prune(unittest.TestCase):
db = get_db(":memory:") db = get_db(":memory:")
rv = rendezvous.Rendezvous(db, None, 3600) rv = rendezvous.Rendezvous(db, None, 3600)
APPID = u"appid" APPID = "appid"
app = rv.get_app(APPID) app = rv.get_app(APPID)
# timestamps <=50 are "old", >=51 are "new" # timestamps <=50 are "old", >=51 are "new"
@ -397,12 +397,12 @@ class Prune(unittest.TestCase):
mailbox_survives = False mailbox_survives = False
messages_survive = False messages_survive = False
mbid = u"mbid" mbid = "mbid"
if nameplate is not None: if nameplate is not None:
app.claim_nameplate(u"npid", u"side1", when[nameplate], app.claim_nameplate("npid", "side1", when[nameplate],
_test_mailbox_id=mbid) _test_mailbox_id=mbid)
if mailbox is not None: if mailbox is not None:
mb = app.open_mailbox(mbid, u"side1", when[mailbox]) mb = app.open_mailbox(mbid, "side1", when[mailbox])
else: else:
# We might want a Mailbox, because that's the easiest way to add # We might want a Mailbox, because that's the easiest way to add
# a "messages" row, but we can't use app.open_mailbox() because # a "messages" row, but we can't use app.open_mailbox() because
@ -415,8 +415,8 @@ class Prune(unittest.TestCase):
app._mailboxes[mbid] = mb app._mailboxes[mbid] = mb
if messages is not None: if messages is not None:
sm = SidedMessage(u"side1", u"phase", u"body", when[messages], sm = SidedMessage("side1", "phase", "body", when[messages],
u"msgid") "msgid")
mb.add_message(sm) mb.add_message(sm)
if has_listeners: if has_listeners:
@ -500,7 +500,7 @@ class WSClient(websocket.WebSocketClientProtocol):
returnValue(m) returnValue(m)
def strip_acks(self): def strip_acks(self):
self.events = [e for e in self.events if e["type"] != u"ack"] self.events = [e for e in self.events if e["type"] != "ack"]
def send(self, mtype, **kwargs): def send(self, mtype, **kwargs):
kwargs["type"] = mtype kwargs["type"] = mtype
@ -630,126 +630,126 @@ class WebSocketAPI(ServerBase, unittest.TestCase):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"bind", appid=u"appid") # missing side= c1.send("bind", appid="appid") # missing side=
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"bind requires 'side'") self.assertEqual(err["error"], "bind requires 'side'")
c1.send(u"bind", side=u"side") # missing appid= c1.send("bind", side="side") # missing appid=
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"bind requires 'appid'") self.assertEqual(err["error"], "bind requires 'appid'")
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
yield c1.sync() yield c1.sync()
self.assertEqual(list(self._rendezvous._apps.keys()), [u"appid"]) self.assertEqual(list(self._rendezvous._apps.keys()), ["appid"])
c1.send(u"bind", appid=u"appid", side=u"side") # duplicate c1.send("bind", appid="appid", side="side") # duplicate
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"already bound") self.assertEqual(err["error"], "already bound")
c1.send_notype(other="misc") # missing 'type' c1.send_notype(other="misc") # missing 'type'
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"missing 'type'") self.assertEqual(err["error"], "missing 'type'")
c1.send("___unknown") # unknown type c1.send("___unknown") # unknown type
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"unknown type") self.assertEqual(err["error"], "unknown type")
c1.send("ping") # missing 'ping' c1.send("ping") # missing 'ping'
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"ping requires 'ping'") self.assertEqual(err["error"], "ping requires 'ping'")
@inlineCallbacks @inlineCallbacks
def test_list(self): def test_list(self):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"list") # too early, must bind first c1.send("list") # too early, must bind first
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"must bind first") self.assertEqual(err["error"], "must bind first")
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
c1.send(u"list") c1.send("list")
m = yield c1.next_non_ack() m = yield c1.next_non_ack()
self.assertEqual(m[u"type"], u"nameplates") self.assertEqual(m["type"], "nameplates")
self.assertEqual(m[u"nameplates"], []) self.assertEqual(m["nameplates"], [])
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
nameplate_id1 = app.allocate_nameplate(u"side", 0) nameplate_id1 = app.allocate_nameplate("side", 0)
app.claim_nameplate(u"np2", u"side", 0) app.claim_nameplate("np2", "side", 0)
c1.send(u"list") c1.send("list")
m = yield c1.next_non_ack() m = yield c1.next_non_ack()
self.assertEqual(m[u"type"], u"nameplates") self.assertEqual(m["type"], "nameplates")
nids = set() nids = set()
for n in m[u"nameplates"]: for n in m["nameplates"]:
self.assertEqual(type(n), dict) self.assertEqual(type(n), dict)
self.assertEqual(list(n.keys()), [u"id"]) self.assertEqual(list(n.keys()), ["id"])
nids.add(n[u"id"]) nids.add(n["id"])
self.assertEqual(nids, set([nameplate_id1, u"np2"])) self.assertEqual(nids, set([nameplate_id1, "np2"]))
@inlineCallbacks @inlineCallbacks
def test_allocate(self): def test_allocate(self):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"allocate") # too early, must bind first c1.send("allocate") # too early, must bind first
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"must bind first") self.assertEqual(err["error"], "must bind first")
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
c1.send(u"allocate") c1.send("allocate")
m = yield c1.next_non_ack() m = yield c1.next_non_ack()
self.assertEqual(m[u"type"], u"allocated") self.assertEqual(m["type"], "allocated")
nameplate_id = m[u"nameplate"] nameplate_id = m["nameplate"]
nids = app.get_nameplate_ids() nids = app.get_nameplate_ids()
self.assertEqual(len(nids), 1) self.assertEqual(len(nids), 1)
self.assertEqual(nameplate_id, list(nids)[0]) self.assertEqual(nameplate_id, list(nids)[0])
c1.send(u"allocate") c1.send("allocate")
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], self.assertEqual(err["error"],
u"you already allocated one, don't be greedy") "you already allocated one, don't be greedy")
c1.send(u"claim", nameplate=nameplate_id) # allocate+claim is ok c1.send("claim", nameplate=nameplate_id) # allocate+claim is ok
yield c1.sync() yield c1.sync()
row = app._db.execute("SELECT * FROM `nameplates`" row = app._db.execute("SELECT * FROM `nameplates`"
" WHERE `app_id`='appid' AND `id`=?", " WHERE `app_id`='appid' AND `id`=?",
(nameplate_id,)).fetchone() (nameplate_id,)).fetchone()
self.assertEqual(row["side1"], u"side") self.assertEqual(row["side1"], "side")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
@inlineCallbacks @inlineCallbacks
def test_claim(self): def test_claim(self):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
c1.send(u"claim") # missing nameplate= c1.send("claim") # missing nameplate=
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"claim requires 'nameplate'") self.assertEqual(err["error"], "claim requires 'nameplate'")
c1.send(u"claim", nameplate=u"np1") c1.send("claim", nameplate="np1")
m = yield c1.next_non_ack() m = yield c1.next_non_ack()
self.assertEqual(m[u"type"], u"claimed") self.assertEqual(m["type"], "claimed")
mailbox_id = m[u"mailbox"] mailbox_id = m["mailbox"]
self.assertEqual(type(mailbox_id), type(u"")) self.assertEqual(type(mailbox_id), type(""))
nids = app.get_nameplate_ids() nids = app.get_nameplate_ids()
self.assertEqual(len(nids), 1) self.assertEqual(len(nids), 1)
self.assertEqual(u"np1", list(nids)[0]) self.assertEqual("np1", list(nids)[0])
# claiming a nameplate will assign a random mailbox id, but won't # claiming a nameplate will assign a random mailbox id, but won't
# create the mailbox itself # create the mailbox itself
@ -761,212 +761,212 @@ class WebSocketAPI(ServerBase, unittest.TestCase):
def test_claim_crowded(self): def test_claim_crowded(self):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
app.claim_nameplate(u"np1", u"side1", 0) app.claim_nameplate("np1", "side1", 0)
app.claim_nameplate(u"np1", u"side2", 0) app.claim_nameplate("np1", "side2", 0)
# the third claim will signal crowding # the third claim will signal crowding
c1.send(u"claim", nameplate=u"np1") c1.send("claim", nameplate="np1")
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"crowded") self.assertEqual(err["error"], "crowded")
@inlineCallbacks @inlineCallbacks
def test_release(self): def test_release(self):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
app.claim_nameplate(u"np1", u"side2", 0) app.claim_nameplate("np1", "side2", 0)
c1.send(u"release") # didn't do claim first c1.send("release") # didn't do claim first
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], self.assertEqual(err["error"],
u"must claim a nameplate before releasing it") "must claim a nameplate before releasing it")
c1.send(u"claim", nameplate=u"np1") c1.send("claim", nameplate="np1")
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"release") c1.send("release")
m = yield c1.next_non_ack() m = yield c1.next_non_ack()
self.assertEqual(m[u"type"], u"released") self.assertEqual(m["type"], "released")
row = app._db.execute("SELECT * FROM `nameplates`" row = app._db.execute("SELECT * FROM `nameplates`"
" WHERE `app_id`='appid' AND `id`='np1'").fetchone() " WHERE `app_id`='appid' AND `id`='np1'").fetchone()
self.assertEqual(row["side1"], u"side2") self.assertEqual(row["side1"], "side2")
self.assertEqual(row["side2"], None) self.assertEqual(row["side2"], None)
c1.send(u"release") # no longer claimed c1.send("release") # no longer claimed
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], self.assertEqual(err["error"],
u"must claim a nameplate before releasing it") "must claim a nameplate before releasing it")
@inlineCallbacks @inlineCallbacks
def test_open(self): def test_open(self):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
c1.send(u"open") # missing mailbox= c1.send("open") # missing mailbox=
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"open requires 'mailbox'") self.assertEqual(err["error"], "open requires 'mailbox'")
mb1 = app.open_mailbox(u"mb1", u"side2", 0) mb1 = app.open_mailbox("mb1", "side2", 0)
mb1.add_message(SidedMessage(side=u"side2", phase=u"phase", mb1.add_message(SidedMessage(side="side2", phase="phase",
body=u"body", server_rx=0, body="body", server_rx=0,
msg_id=u"msgid")) msg_id="msgid"))
c1.send(u"open", mailbox=u"mb1") c1.send("open", mailbox="mb1")
m = yield c1.next_non_ack() m = yield c1.next_non_ack()
self.assertEqual(m[u"type"], u"message") self.assertEqual(m["type"], "message")
self.assertEqual(m[u"body"], u"body") self.assertEqual(m["body"], "body")
mb1.add_message(SidedMessage(side=u"side2", phase=u"phase2", mb1.add_message(SidedMessage(side="side2", phase="phase2",
body=u"body2", server_rx=0, body="body2", server_rx=0,
msg_id=u"msgid")) msg_id="msgid"))
m = yield c1.next_non_ack() m = yield c1.next_non_ack()
self.assertEqual(m[u"type"], u"message") self.assertEqual(m["type"], "message")
self.assertEqual(m[u"body"], u"body2") self.assertEqual(m["body"], "body2")
c1.send(u"open", mailbox=u"mb1") c1.send("open", mailbox="mb1")
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"you already have a mailbox open") self.assertEqual(err["error"], "you already have a mailbox open")
@inlineCallbacks @inlineCallbacks
def test_add(self): def test_add(self):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
app = self._rendezvous.get_app(u"appid") app = self._rendezvous.get_app("appid")
mb1 = app.open_mailbox(u"mb1", u"side2", 0) mb1 = app.open_mailbox("mb1", "side2", 0)
l1 = []; stop1 = []; stop1_f = lambda: stop1.append(True) l1 = []; stop1 = []; stop1_f = lambda: stop1.append(True)
mb1.add_listener("handle1", l1.append, stop1_f) mb1.add_listener("handle1", l1.append, stop1_f)
c1.send(u"add") # didn't open first c1.send("add") # didn't open first
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"must open mailbox before adding") self.assertEqual(err["error"], "must open mailbox before adding")
c1.send(u"open", mailbox=u"mb1") c1.send("open", mailbox="mb1")
c1.send(u"add", body=u"body") # missing phase= c1.send("add", body="body") # missing phase=
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"missing 'phase'") self.assertEqual(err["error"], "missing 'phase'")
c1.send(u"add", phase=u"phase") # missing body= c1.send("add", phase="phase") # missing body=
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"missing 'body'") self.assertEqual(err["error"], "missing 'body'")
c1.send(u"add", phase=u"phase", body=u"body") c1.send("add", phase="phase", body="body")
m = yield c1.next_non_ack() # echoed back m = yield c1.next_non_ack() # echoed back
self.assertEqual(m[u"type"], u"message") self.assertEqual(m["type"], "message")
self.assertEqual(m[u"body"], u"body") self.assertEqual(m["body"], "body")
self.assertEqual(len(l1), 1) self.assertEqual(len(l1), 1)
self.assertEqual(l1[0].body, u"body") self.assertEqual(l1[0].body, "body")
@inlineCallbacks @inlineCallbacks
def test_close(self): def test_close(self):
c1 = yield self.make_client() c1 = yield self.make_client()
yield c1.next_non_ack() yield c1.next_non_ack()
c1.send(u"bind", appid=u"appid", side=u"side") c1.send("bind", appid="appid", side="side")
c1.send(u"close", mood=u"mood") # must open first c1.send("close", mood="mood") # must open first
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"must open mailbox before closing") self.assertEqual(err["error"], "must open mailbox before closing")
c1.send(u"open", mailbox=u"mb1") c1.send("open", mailbox="mb1")
c1.send(u"close", mood=u"mood") c1.send("close", mood="mood")
m = yield c1.next_non_ack() m = yield c1.next_non_ack()
self.assertEqual(m[u"type"], u"closed") self.assertEqual(m["type"], "closed")
c1.send(u"close", mood=u"mood") # already closed c1.send("close", mood="mood") # already closed
err = yield c1.next_non_ack() err = yield c1.next_non_ack()
self.assertEqual(err[u"type"], u"error") self.assertEqual(err["type"], "error")
self.assertEqual(err[u"error"], u"must open mailbox before closing") self.assertEqual(err["error"], "must open mailbox before closing")
class Summary(unittest.TestCase): class Summary(unittest.TestCase):
def test_mailbox(self): def test_mailbox(self):
app = rendezvous.AppNamespace(None, None, False, None) app = rendezvous.AppNamespace(None, None, False, None)
# starts at time 1, maybe gets second open at time 3, closes at 5 # starts at time 1, maybe gets second open at time 3, closes at 5
base_row = {u"started": 1, u"second": None, base_row = {"started": 1, "second": None,
u"first_mood": None, u"crowded": False} "first_mood": None, "crowded": False}
def summ(num_sides, second_mood=None, pruned=False, **kwargs): def summ(num_sides, second_mood=None, pruned=False, **kwargs):
row = base_row.copy() row = base_row.copy()
row.update(kwargs) row.update(kwargs)
return app._summarize_mailbox(row, num_sides, second_mood, 5, return app._summarize_mailbox(row, num_sides, second_mood, 5,
pruned) pruned)
self.assertEqual(summ(1), Usage(1, None, 4, u"lonely")) self.assertEqual(summ(1), Usage(1, None, 4, "lonely"))
self.assertEqual(summ(1, u"lonely"), Usage(1, None, 4, u"lonely")) self.assertEqual(summ(1, "lonely"), Usage(1, None, 4, "lonely"))
self.assertEqual(summ(1, u"errory"), Usage(1, None, 4, u"errory")) self.assertEqual(summ(1, "errory"), Usage(1, None, 4, "errory"))
self.assertEqual(summ(1, crowded=True), Usage(1, None, 4, u"crowded")) self.assertEqual(summ(1, crowded=True), Usage(1, None, 4, "crowded"))
self.assertEqual(summ(2, first_mood=u"happy", self.assertEqual(summ(2, first_mood="happy",
second=3, second_mood=u"happy"), second=3, second_mood="happy"),
Usage(1, 2, 4, u"happy")) Usage(1, 2, 4, "happy"))
self.assertEqual(summ(2, first_mood=u"errory", self.assertEqual(summ(2, first_mood="errory",
second=3, second_mood=u"happy"), second=3, second_mood="happy"),
Usage(1, 2, 4, u"errory")) Usage(1, 2, 4, "errory"))
self.assertEqual(summ(2, first_mood=u"happy", self.assertEqual(summ(2, first_mood="happy",
second=3, second_mood=u"errory"), second=3, second_mood="errory"),
Usage(1, 2, 4, u"errory")) Usage(1, 2, 4, "errory"))
self.assertEqual(summ(2, first_mood=u"scary", self.assertEqual(summ(2, first_mood="scary",
second=3, second_mood=u"happy"), second=3, second_mood="happy"),
Usage(1, 2, 4, u"scary")) Usage(1, 2, 4, "scary"))
self.assertEqual(summ(2, first_mood=u"scary", self.assertEqual(summ(2, first_mood="scary",
second=3, second_mood=u"errory"), second=3, second_mood="errory"),
Usage(1, 2, 4, u"scary")) Usage(1, 2, 4, "scary"))
self.assertEqual(summ(2, first_mood=u"happy", second=3, pruned=True), self.assertEqual(summ(2, first_mood="happy", second=3, pruned=True),
Usage(1, 2, 4, u"pruney")) Usage(1, 2, 4, "pruney"))
def test_nameplate(self): def test_nameplate(self):
a = rendezvous.AppNamespace(None, None, False, None) a = rendezvous.AppNamespace(None, None, False, None)
# starts at time 1, maybe gets second open at time 3, closes at 5 # starts at time 1, maybe gets second open at time 3, closes at 5
base_row = {u"started": 1, u"second": None, u"crowded": False} base_row = {"started": 1, "second": None, "crowded": False}
def summ(num_sides, pruned=False, **kwargs): def summ(num_sides, pruned=False, **kwargs):
row = base_row.copy() row = base_row.copy()
row.update(kwargs) row.update(kwargs)
return a._summarize_nameplate_usage(row, 5, pruned) return a._summarize_nameplate_usage(row, 5, pruned)
self.assertEqual(summ(1), Usage(1, None, 4, u"lonely")) self.assertEqual(summ(1), Usage(1, None, 4, "lonely"))
self.assertEqual(summ(1, crowded=True), Usage(1, None, 4, u"crowded")) self.assertEqual(summ(1, crowded=True), Usage(1, None, 4, "crowded"))
self.assertEqual(summ(2, second=3), Usage(1, 2, 4, u"happy")) self.assertEqual(summ(2, second=3), Usage(1, 2, 4, "happy"))
self.assertEqual(summ(2, second=3, pruned=True), self.assertEqual(summ(2, second=3, pruned=True),
Usage(1, 2, 4, u"pruney")) Usage(1, 2, 4, "pruney"))
def test_blur(self): def test_blur(self):
db = get_db(":memory:") db = get_db(":memory:")
rv = rendezvous.Rendezvous(db, None, 3600) rv = rendezvous.Rendezvous(db, None, 3600)
APPID = u"appid" APPID = "appid"
app = rv.get_app(APPID) app = rv.get_app(APPID)
app.claim_nameplate(u"npid", u"side1", 10) # start time is 10 app.claim_nameplate("npid", "side1", 10) # start time is 10
rv.prune(now=123, old=50) rv.prune(now=123, old=50)
# start time should be rounded to top of the hour (blur_usage=3600) # start time should be rounded to top of the hour (blur_usage=3600)
row = db.execute("SELECT * FROM `nameplate_usage`").fetchone() row = db.execute("SELECT * FROM `nameplate_usage`").fetchone()
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
app = rv.get_app(APPID) app = rv.get_app(APPID)
app.open_mailbox(u"mbid", u"side1", 20) # start time is 20 app.open_mailbox("mbid", "side1", 20) # start time is 20
rv.prune(now=123, old=50) rv.prune(now=123, old=50)
row = db.execute("SELECT * FROM `mailbox_usage`").fetchone() row = db.execute("SELECT * FROM `mailbox_usage`").fetchone()
self.assertEqual(row["started"], 0) self.assertEqual(row["started"], 0)
@ -974,15 +974,15 @@ class Summary(unittest.TestCase):
def test_no_blur(self): def test_no_blur(self):
db = get_db(":memory:") db = get_db(":memory:")
rv = rendezvous.Rendezvous(db, None, None) rv = rendezvous.Rendezvous(db, None, None)
APPID = u"appid" APPID = "appid"
app = rv.get_app(APPID) app = rv.get_app(APPID)
app.claim_nameplate(u"npid", u"side1", 10) # start time is 10 app.claim_nameplate("npid", "side1", 10) # start time is 10
rv.prune(now=123, old=50) rv.prune(now=123, old=50)
row = db.execute("SELECT * FROM `nameplate_usage`").fetchone() row = db.execute("SELECT * FROM `nameplate_usage`").fetchone()
self.assertEqual(row["started"], 10) self.assertEqual(row["started"], 10)
app = rv.get_app(APPID) app = rv.get_app(APPID)
app.open_mailbox(u"mbid", u"side1", 20) # start time is 20 app.open_mailbox("mbid", "side1", 20) # start time is 20
rv.prune(now=123, old=50) rv.prune(now=123, old=50)
row = db.execute("SELECT * FROM `mailbox_usage`").fetchone() row = db.execute("SELECT * FROM `mailbox_usage`").fetchone()
self.assertEqual(row["started"], 20) self.assertEqual(row["started"], 20)

View File

@ -80,7 +80,7 @@ class Highlander(unittest.TestCase):
class Forever(unittest.TestCase): class Forever(unittest.TestCase):
def _forever_setup(self): def _forever_setup(self):
clock = task.Clock() clock = task.Clock()
c = transit.Common(u"", reactor=clock) c = transit.Common("", reactor=clock)
cancelled = [] cancelled = []
result = [] result = []
d0 = defer.Deferred(cancelled.append) d0 = defer.Deferred(cancelled.append)
@ -129,7 +129,7 @@ class Misc(unittest.TestCase):
class Hints(unittest.TestCase): class Hints(unittest.TestCase):
def test_endpoint_from_hint_obj(self): def test_endpoint_from_hint_obj(self):
c = transit.Common(u"") c = transit.Common("")
ep = c._endpoint_from_hint_obj(transit.DirectTCPV1Hint("localhost", 1234)) ep = c._endpoint_from_hint_obj(transit.DirectTCPV1Hint("localhost", 1234))
self.assertIsInstance(ep, endpoints.HostnameEndpoint) self.assertIsInstance(ep, endpoints.HostnameEndpoint)
ep = c._endpoint_from_hint_obj("unknown:stuff:yowza:pivlor") ep = c._endpoint_from_hint_obj("unknown:stuff:yowza:pivlor")
@ -139,12 +139,12 @@ class Hints(unittest.TestCase):
class Basic(unittest.TestCase): class Basic(unittest.TestCase):
@inlineCallbacks @inlineCallbacks
def test_relay_hints(self): def test_relay_hints(self):
URL = u"tcp:host:1234" URL = "tcp:host:1234"
c = transit.Common(URL, no_listen=True) c = transit.Common(URL, no_listen=True)
hints = yield c.get_connection_hints() hints = yield c.get_connection_hints()
self.assertEqual(hints, [{"type": "relay-v1", self.assertEqual(hints, [{"type": "relay-v1",
"hints": [{"type": "direct-tcp-v1", "hints": [{"type": "direct-tcp-v1",
"hostname": u"host", "hostname": "host",
"port": 1234}], "port": 1234}],
}]) }])
self.assertRaises(UsageError, transit.Common, 123) self.assertRaises(UsageError, transit.Common, 123)
@ -156,7 +156,7 @@ class Basic(unittest.TestCase):
self.assertEqual(hints, []) self.assertEqual(hints, [])
def test_ignore_bad_hints(self): def test_ignore_bad_hints(self):
c = transit.Common(u"") c = transit.Common("")
c.add_connection_hints([{"type": "unknown"}]) c.add_connection_hints([{"type": "unknown"}])
c.add_connection_hints([{"type": "relay-v1", c.add_connection_hints([{"type": "relay-v1",
"hints": [{"type": "unknown"}]}]) "hints": [{"type": "unknown"}]}])
@ -165,7 +165,7 @@ class Basic(unittest.TestCase):
def test_ignore_localhost_hint(self): def test_ignore_localhost_hint(self):
# this actually starts the listener # this actually starts the listener
c = transit.TransitSender(u"") c = transit.TransitSender("")
results = [] results = []
d = c.get_connection_hints() d = c.get_connection_hints()
d.addBoth(results.append) d.addBoth(results.append)
@ -174,14 +174,14 @@ class Basic(unittest.TestCase):
# If there are non-localhost hints, then localhost hints should be # If there are non-localhost hints, then localhost hints should be
# removed. But if the only hint is localhost, it should stay. # removed. But if the only hint is localhost, it should stay.
if len(hints) == 1: if len(hints) == 1:
if hints[0][u'hostname'] == u'127.0.0.1': if hints[0]["hostname"] == "127.0.0.1":
return return
for hint in hints: for hint in hints:
self.assertFalse(hint[u'hostname'] == u'127.0.0.1') self.assertFalse(hint["hostname"] == "127.0.0.1")
def test_transit_key_wait(self): def test_transit_key_wait(self):
KEY = b"123" KEY = b"123"
c = transit.Common(u"") c = transit.Common("")
results = [] results = []
d = c._get_transit_key() d = c._get_transit_key()
d.addBoth(results.append) d.addBoth(results.append)
@ -191,7 +191,7 @@ class Basic(unittest.TestCase):
def test_transit_key_already_set(self): def test_transit_key_already_set(self):
KEY = b"123" KEY = b"123"
c = transit.Common(u"") c = transit.Common("")
c.set_transit_key(KEY) c.set_transit_key(KEY)
results = [] results = []
d = c._get_transit_key() d = c._get_transit_key()
@ -200,9 +200,9 @@ class Basic(unittest.TestCase):
def test_transit_keys(self): def test_transit_keys(self):
KEY = b"123" KEY = b"123"
s = transit.TransitSender(u"") s = transit.TransitSender("")
s.set_transit_key(KEY) s.set_transit_key(KEY)
r = transit.TransitReceiver(u"") r = transit.TransitReceiver("")
r.set_transit_key(KEY) r.set_transit_key(KEY)
self.assertEqual(s._send_this(), b"transit sender 559bdeae4b49fa6a23378d2b68f4c7e69378615d4af049c371c6a26e82391089 ready\n\n") self.assertEqual(s._send_this(), b"transit sender 559bdeae4b49fa6a23378d2b68f4c7e69378615d4af049c371c6a26e82391089 ready\n\n")
@ -220,20 +220,20 @@ class Basic(unittest.TestCase):
hexlify(s._receiver_record_key())) hexlify(s._receiver_record_key()))
def test_connection_ready(self): def test_connection_ready(self):
s = transit.TransitSender(u"") s = transit.TransitSender("")
self.assertEqual(s.connection_ready("p1"), "go") self.assertEqual(s.connection_ready("p1"), "go")
self.assertEqual(s._winner, "p1") self.assertEqual(s._winner, "p1")
self.assertEqual(s.connection_ready("p2"), "nevermind") self.assertEqual(s.connection_ready("p2"), "nevermind")
self.assertEqual(s._winner, "p1") self.assertEqual(s._winner, "p1")
r = transit.TransitReceiver(u"") r = transit.TransitReceiver("")
self.assertEqual(r.connection_ready("p1"), "wait-for-decision") self.assertEqual(r.connection_ready("p1"), "wait-for-decision")
self.assertEqual(r.connection_ready("p2"), "wait-for-decision") self.assertEqual(r.connection_ready("p2"), "wait-for-decision")
class Listener(unittest.TestCase): class Listener(unittest.TestCase):
def test_listener(self): def test_listener(self):
c = transit.Common(u"") c = transit.Common("")
hints, ep = c._build_listener() hints, ep = c._build_listener()
self.assertIsInstance(hints, (list, set)) self.assertIsInstance(hints, (list, set))
if hints: if hints:
@ -242,7 +242,7 @@ class Listener(unittest.TestCase):
def test_get_direct_hints(self): def test_get_direct_hints(self):
# this actually starts the listener # this actually starts the listener
c = transit.TransitSender(u"") c = transit.TransitSender("")
results = [] results = []
d = c.get_connection_hints() d = c.get_connection_hints()
@ -1188,25 +1188,25 @@ class FileConsumer(unittest.TestCase):
self.assertEqual(f.getvalue(), b"."*99+b"!") self.assertEqual(f.getvalue(), b"."*99+b"!")
DIRECT_HINT = {u"type": u"direct-tcp-v1", DIRECT_HINT = {"type": "direct-tcp-v1",
u"hostname": u"direct", u"port": 1234} "hostname": "direct", "port": 1234}
RELAY_HINT = {u"type": u"relay-v1", RELAY_HINT = {"type": "relay-v1",
u"hints": [{u"type": u"direct-tcp-v1", "hints": [{"type": "direct-tcp-v1",
u"hostname": u"relay", u"port": 1234}]} "hostname": "relay", "port": 1234}]}
UNUSABLE_HINT = {u"type": u"unknown"} UNUSABLE_HINT = {"type": "unknown"}
RELAY_HINT2 = {u"type": u"relay-v1", RELAY_HINT2 = {"type": "relay-v1",
u"hints": [{u"type": u"direct-tcp-v1", "hints": [{"type": "direct-tcp-v1",
u"hostname": u"relay", u"port": 1234}, "hostname": "relay", "port": 1234},
UNUSABLE_HINT]} UNUSABLE_HINT]}
DIRECT_HINT_INTERNAL = transit.DirectTCPV1Hint(u"direct", 1234) DIRECT_HINT_INTERNAL = transit.DirectTCPV1Hint("direct", 1234)
RELAY_HINT_FIRST = transit.DirectTCPV1Hint(u"relay", 1234) RELAY_HINT_FIRST = transit.DirectTCPV1Hint("relay", 1234)
RELAY_HINT_INTERNAL = transit.RelayV1Hint([RELAY_HINT_FIRST]) RELAY_HINT_INTERNAL = transit.RelayV1Hint([RELAY_HINT_FIRST])
class Transit(unittest.TestCase): class Transit(unittest.TestCase):
@inlineCallbacks @inlineCallbacks
def test_success_direct(self): def test_success_direct(self):
clock = task.Clock() clock = task.Clock()
s = transit.TransitSender(u"", reactor=clock) s = transit.TransitSender("", reactor=clock)
s.set_transit_key(b"key") s.set_transit_key(b"key")
hints = yield s.get_connection_hints() # start the listener hints = yield s.get_connection_hints() # start the listener
del hints del hints
@ -1239,7 +1239,7 @@ class Transit(unittest.TestCase):
@inlineCallbacks @inlineCallbacks
def test_wait_for_relay(self): def test_wait_for_relay(self):
clock = task.Clock() clock = task.Clock()
s = transit.TransitSender(u"", reactor=clock, no_listen=True) s = transit.TransitSender("", reactor=clock, no_listen=True)
s.set_transit_key(b"key") s.set_transit_key(b"key")
hints = yield s.get_connection_hints() # start the listener hints = yield s.get_connection_hints() # start the listener
del hints del hints
@ -1278,7 +1278,7 @@ class Transit(unittest.TestCase):
@inlineCallbacks @inlineCallbacks
def test_no_direct_hints(self): def test_no_direct_hints(self):
clock = task.Clock() clock = task.Clock()
s = transit.TransitSender(u"", reactor=clock, no_listen=True) s = transit.TransitSender("", reactor=clock, no_listen=True)
s.set_transit_key(b"key") s.set_transit_key(b"key")
hints = yield s.get_connection_hints() # start the listener hints = yield s.get_connection_hints() # start the listener
del hints del hints

View File

@ -5,23 +5,23 @@ from .. import util
class Utils(unittest.TestCase): class Utils(unittest.TestCase):
def test_to_bytes(self): def test_to_bytes(self):
b = util.to_bytes(u"abc") b = util.to_bytes("abc")
self.assertIsInstance(b, type(b"")) self.assertIsInstance(b, type(b""))
self.assertEqual(b, b"abc") self.assertEqual(b, b"abc")
A = unicodedata.lookup("LATIN SMALL LETTER A WITH DIAERESIS") A = unicodedata.lookup("LATIN SMALL LETTER A WITH DIAERESIS")
b = util.to_bytes(A + u"bc") b = util.to_bytes(A + "bc")
self.assertIsInstance(b, type(b"")) self.assertIsInstance(b, type(b""))
self.assertEqual(b, b"\xc3\xa4\x62\x63") self.assertEqual(b, b"\xc3\xa4\x62\x63")
def test_bytes_to_hexstr(self): def test_bytes_to_hexstr(self):
b = b"\x00\x45\x91\xfe\xff" b = b"\x00\x45\x91\xfe\xff"
hexstr = util.bytes_to_hexstr(b) hexstr = util.bytes_to_hexstr(b)
self.assertIsInstance(hexstr, type(u"")) self.assertIsInstance(hexstr, type(""))
self.assertEqual(hexstr, u"004591feff") self.assertEqual(hexstr, "004591feff")
def test_hexstr_to_bytes(self): def test_hexstr_to_bytes(self):
hexstr = u"004591feff" hexstr = "004591feff"
b = util.hexstr_to_bytes(hexstr) b = util.hexstr_to_bytes(hexstr)
hexstr = util.bytes_to_hexstr(b) hexstr = util.bytes_to_hexstr(b)
self.assertIsInstance(b, type(b"")) self.assertIsInstance(b, type(b""))
@ -37,4 +37,4 @@ class Utils(unittest.TestCase):
b = b'{"a": "b", "c": 2}' b = b'{"a": "b", "c": 2}'
d = util.bytes_to_dict(b) d = util.bytes_to_dict(b)
self.assertIsInstance(d, dict) self.assertIsInstance(d, dict)
self.assertEqual(d, {u"a": u"b", u"c": 2}) self.assertEqual(d, {"a": "b", "c": 2})

View File

@ -15,7 +15,7 @@ from ..util import (bytes_to_dict, dict_to_bytes,
hexstr_to_bytes, bytes_to_hexstr) hexstr_to_bytes, bytes_to_hexstr)
from nacl.secret import SecretBox from nacl.secret import SecretBox
APPID = u"appid" APPID = "appid"
class MockWebSocket: class MockWebSocket:
def __init__(self): def __init__(self):
@ -37,83 +37,83 @@ def response(w, **kwargs):
class Welcome(unittest.TestCase): class Welcome(unittest.TestCase):
def test_tolerate_no_current_version(self): def test_tolerate_no_current_version(self):
w = wormhole._WelcomeHandler(u"relay_url", u"current_cli_version", None) w = wormhole._WelcomeHandler("relay_url", "current_cli_version", None)
w.handle_welcome({}) w.handle_welcome({})
def test_print_motd(self): def test_print_motd(self):
w = wormhole._WelcomeHandler(u"relay_url", u"current_cli_version", None) w = wormhole._WelcomeHandler("relay_url", "current_cli_version", None)
with mock.patch("sys.stderr") as stderr: with mock.patch("sys.stderr") as stderr:
w.handle_welcome({u"motd": u"message of\nthe day"}) w.handle_welcome({"motd": "message of\nthe day"})
self.assertEqual(stderr.method_calls, self.assertEqual(stderr.method_calls,
[mock.call.write(u"Server (at relay_url) says:\n" [mock.call.write("Server (at relay_url) says:\n"
" message of\n the day"), " message of\n the day"),
mock.call.write(u"\n")]) mock.call.write("\n")])
# motd can be displayed multiple times # motd can be displayed multiple times
with mock.patch("sys.stderr") as stderr2: with mock.patch("sys.stderr") as stderr2:
w.handle_welcome({u"motd": u"second message"}) w.handle_welcome({"motd": "second message"})
self.assertEqual(stderr2.method_calls, self.assertEqual(stderr2.method_calls,
[mock.call.write(u"Server (at relay_url) says:\n" [mock.call.write("Server (at relay_url) says:\n"
" second message"), " second message"),
mock.call.write(u"\n")]) mock.call.write("\n")])
def test_current_version(self): def test_current_version(self):
w = wormhole._WelcomeHandler(u"relay_url", u"2.0", None) w = wormhole._WelcomeHandler("relay_url", "2.0", None)
with mock.patch("sys.stderr") as stderr: with mock.patch("sys.stderr") as stderr:
w.handle_welcome({u"current_cli_version": u"2.0"}) w.handle_welcome({"current_cli_version": "2.0"})
self.assertEqual(stderr.method_calls, []) self.assertEqual(stderr.method_calls, [])
with mock.patch("sys.stderr") as stderr: with mock.patch("sys.stderr") as stderr:
w.handle_welcome({u"current_cli_version": u"3.0"}) w.handle_welcome({"current_cli_version": "3.0"})
exp1 = (u"Warning: errors may occur unless both sides are" exp1 = ("Warning: errors may occur unless both sides are"
" running the same version") " running the same version")
exp2 = (u"Server claims 3.0 is current, but ours is 2.0") exp2 = ("Server claims 3.0 is current, but ours is 2.0")
self.assertEqual(stderr.method_calls, self.assertEqual(stderr.method_calls,
[mock.call.write(exp1), [mock.call.write(exp1),
mock.call.write(u"\n"), mock.call.write("\n"),
mock.call.write(exp2), mock.call.write(exp2),
mock.call.write(u"\n"), mock.call.write("\n"),
]) ])
# warning is only displayed once # warning is only displayed once
with mock.patch("sys.stderr") as stderr: with mock.patch("sys.stderr") as stderr:
w.handle_welcome({u"current_cli_version": u"3.0"}) w.handle_welcome({"current_cli_version": "3.0"})
self.assertEqual(stderr.method_calls, []) self.assertEqual(stderr.method_calls, [])
def test_non_release_version(self): def test_non_release_version(self):
w = wormhole._WelcomeHandler(u"relay_url", u"2.0-dirty", None) w = wormhole._WelcomeHandler("relay_url", "2.0-dirty", None)
with mock.patch("sys.stderr") as stderr: with mock.patch("sys.stderr") as stderr:
w.handle_welcome({u"current_cli_version": u"3.0"}) w.handle_welcome({"current_cli_version": "3.0"})
self.assertEqual(stderr.method_calls, []) self.assertEqual(stderr.method_calls, [])
def test_signal_error(self): def test_signal_error(self):
se = mock.Mock() se = mock.Mock()
w = wormhole._WelcomeHandler(u"relay_url", u"2.0", se) w = wormhole._WelcomeHandler("relay_url", "2.0", se)
w.handle_welcome({}) w.handle_welcome({})
self.assertEqual(se.mock_calls, []) self.assertEqual(se.mock_calls, [])
w.handle_welcome({u"error": u"oops"}) w.handle_welcome({"error": "oops"})
self.assertEqual(len(se.mock_calls), 1) self.assertEqual(len(se.mock_calls), 1)
self.assertEqual(len(se.mock_calls[0][1]), 2) # posargs self.assertEqual(len(se.mock_calls[0][1]), 2) # posargs
we = se.mock_calls[0][1][0] we = se.mock_calls[0][1][0]
self.assertIsInstance(we, WelcomeError) self.assertIsInstance(we, WelcomeError)
self.assertEqual(we.args, (u"oops",)) self.assertEqual(we.args, ("oops",))
mood = se.mock_calls[0][1][1] mood = se.mock_calls[0][1][1]
self.assertEqual(mood, u"unwelcome") self.assertEqual(mood, "unwelcome")
# alas WelcomeError instances don't compare against each other # alas WelcomeError instances don't compare against each other
#self.assertEqual(se.mock_calls, [mock.call(WelcomeError(u"oops"))]) #self.assertEqual(se.mock_calls, [mock.call(WelcomeError("oops"))])
class InputCode(unittest.TestCase): class InputCode(unittest.TestCase):
def test_list(self): def test_list(self):
send_command = mock.Mock() send_command = mock.Mock()
ic = wormhole._InputCode(None, u"prompt", 2, send_command, ic = wormhole._InputCode(None, "prompt", 2, send_command,
DebugTiming()) DebugTiming())
d = ic._list() d = ic._list()
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(send_command.mock_calls, [mock.call(u"list")]) self.assertEqual(send_command.mock_calls, [mock.call("list")])
ic._response_handle_nameplates({u"type": u"nameplates", ic._response_handle_nameplates({"type": "nameplates",
u"nameplates": [{u"id": u"123"}]}) "nameplates": [{"id": "123"}]})
res = self.successResultOf(d) res = self.successResultOf(d)
self.assertEqual(res, [u"123"]) self.assertEqual(res, ["123"])
class GetCode(unittest.TestCase): class GetCode(unittest.TestCase):
def test_get(self): def test_get(self):
@ -121,14 +121,14 @@ class GetCode(unittest.TestCase):
gc = wormhole._GetCode(2, send_command, DebugTiming()) gc = wormhole._GetCode(2, send_command, DebugTiming())
d = gc.go() d = gc.go()
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(send_command.mock_calls, [mock.call(u"allocate")]) self.assertEqual(send_command.mock_calls, [mock.call("allocate")])
# TODO: nameplate attributes get added and checked here # TODO: nameplate attributes get added and checked here
gc._response_handle_allocated({u"type": u"allocated", gc._response_handle_allocated({"type": "allocated",
u"nameplate": u"123"}) "nameplate": "123"})
code = self.successResultOf(d) code = self.successResultOf(d)
self.assertIsInstance(code, type(u"")) self.assertIsInstance(code, type(""))
self.assert_(code.startswith(u"123-")) self.assert_(code.startswith("123-"))
pieces = code.split(u"-") pieces = code.split("-")
self.assertEqual(len(pieces), 3) # nameplate plus two words self.assertEqual(len(pieces), 3) # nameplate plus two words
self.assert_(re.search(r'^\d+-\w+-\w+$', code), code) self.assert_(re.search(r'^\d+-\w+-\w+$', code), code)
@ -148,7 +148,7 @@ class Basic(unittest.TestCase):
out = ws.outbound() out = ws.outbound()
self.assertEqual(len(out), len(types), (out, types)) self.assertEqual(len(out), len(types), (out, types))
for i,t in enumerate(types): for i,t in enumerate(types):
self.assertEqual(out[i][u"type"], t, (i,t,out)) self.assertEqual(out[i]["type"], t, (i,t,out))
return out return out
def make_pake(self, code, side, msg1): def make_pake(self, code, side, msg1):
@ -159,7 +159,7 @@ class Basic(unittest.TestCase):
return key, msg2 return key, msg2
def test_create(self): def test_create(self):
wormhole._Wormhole(APPID, u"relay_url", reactor, None, None) wormhole._Wormhole(APPID, "relay_url", reactor, None, None)
def test_basic(self): def test_basic(self):
# We don't call w._start(), so this doesn't create a WebSocket # We don't call w._start(), so this doesn't create a WebSocket
@ -172,9 +172,9 @@ class Basic(unittest.TestCase):
timing = DebugTiming() timing = DebugTiming()
with mock.patch("wormhole.wormhole._WelcomeHandler") as wh_c: with mock.patch("wormhole.wormhole._WelcomeHandler") as wh_c:
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
wh = wh_c.return_value wh = wh_c.return_value
self.assertEqual(w._ws_url, u"relay_url") self.assertEqual(w._ws_url, "relay_url")
self.assertTrue(w._flag_need_nameplate) self.assertTrue(w._flag_need_nameplate)
self.assertTrue(w._flag_need_to_build_msg1) self.assertTrue(w._flag_need_to_build_msg1)
self.assertTrue(w._flag_need_to_send_PAKE) self.assertTrue(w._flag_need_to_send_PAKE)
@ -190,50 +190,50 @@ class Basic(unittest.TestCase):
w._event_ws_opened(None) w._event_ws_opened(None)
out = ws.outbound() out = ws.outbound()
self.assertEqual(len(out), 1) self.assertEqual(len(out), 1)
self.check_out(out[0], type=u"bind", appid=APPID, side=w._side) self.check_out(out[0], type="bind", appid=APPID, side=w._side)
self.assertIn(u"id", out[0]) self.assertIn("id", out[0])
# WelcomeHandler should get called upon 'welcome' response. Its full # WelcomeHandler should get called upon 'welcome' response. Its full
# behavior is exercised in 'Welcome' above. # behavior is exercised in 'Welcome' above.
WELCOME = {u"foo": u"bar"} WELCOME = {"foo": "bar"}
response(w, type="welcome", welcome=WELCOME) response(w, type="welcome", welcome=WELCOME)
self.assertEqual(wh.mock_calls, [mock.call.handle_welcome(WELCOME)]) self.assertEqual(wh.mock_calls, [mock.call.handle_welcome(WELCOME)])
# because we're connected, setting the code also claims the mailbox # because we're connected, setting the code also claims the mailbox
CODE = u"123-foo-bar" CODE = "123-foo-bar"
w.set_code(CODE) w.set_code(CODE)
self.assertFalse(w._flag_need_to_build_msg1) self.assertFalse(w._flag_need_to_build_msg1)
out = ws.outbound() out = ws.outbound()
self.assertEqual(len(out), 1) self.assertEqual(len(out), 1)
self.check_out(out[0], type=u"claim", nameplate=u"123") self.check_out(out[0], type="claim", nameplate="123")
# the server reveals the linked mailbox # the server reveals the linked mailbox
response(w, type=u"claimed", mailbox=u"mb456") response(w, type="claimed", mailbox="mb456")
# that triggers event_learned_mailbox, which should send open() and # that triggers event_learned_mailbox, which should send open() and
# PAKE # PAKE
self.assertEqual(w._mailbox_state, wormhole.OPEN) self.assertEqual(w._mailbox_state, wormhole.OPEN)
out = ws.outbound() out = ws.outbound()
self.assertEqual(len(out), 2) self.assertEqual(len(out), 2)
self.check_out(out[0], type=u"open", mailbox=u"mb456") self.check_out(out[0], type="open", mailbox="mb456")
self.check_out(out[1], type=u"add", phase=u"pake") self.check_out(out[1], type="add", phase="pake")
self.assertNoResult(v) self.assertNoResult(v)
# server echoes back all "add" messages # server echoes back all "add" messages
response(w, type=u"message", phase=u"pake", body=out[1][u"body"], response(w, type="message", phase="pake", body=out[1]["body"],
side=w._side) side=w._side)
self.assertNoResult(v) self.assertNoResult(v)
# extract our outbound PAKE message # extract our outbound PAKE message
body = bytes_to_dict(hexstr_to_bytes(out[1][u"body"])) body = bytes_to_dict(hexstr_to_bytes(out[1]["body"]))
msg1 = hexstr_to_bytes(body[u"pake_v1"]) msg1 = hexstr_to_bytes(body["pake_v1"])
# next we build the simulated peer's PAKE operation # next we build the simulated peer's PAKE operation
side2 = w._side + u"other" side2 = w._side + "other"
key, msg2 = self.make_pake(CODE, side2, msg1) key, msg2 = self.make_pake(CODE, side2, msg1)
payload = {u"pake_v1": bytes_to_hexstr(msg2)} payload = {"pake_v1": bytes_to_hexstr(msg2)}
body_hex = bytes_to_hexstr(dict_to_bytes(payload)) body_hex = bytes_to_hexstr(dict_to_bytes(payload))
response(w, type=u"message", phase=u"pake", body=body_hex, side=side2) response(w, type="message", phase="pake", body=body_hex, side=side2)
# hearing the peer's PAKE (msg2) makes us release the nameplate, send # hearing the peer's PAKE (msg2) makes us release the nameplate, send
# the confirmation message, and sends any queued phase messages. It # the confirmation message, and sends any queued phase messages. It
@ -243,72 +243,72 @@ class Basic(unittest.TestCase):
self.assertEqual(w._key, key) self.assertEqual(w._key, key)
out = ws.outbound() out = ws.outbound()
self.assertEqual(len(out), 2, out) self.assertEqual(len(out), 2, out)
self.check_out(out[0], type=u"release") self.check_out(out[0], type="release")
self.check_out(out[1], type=u"add", phase=u"version") self.check_out(out[1], type="add", phase="version")
self.assertNoResult(v) self.assertNoResult(v)
# hearing a valid confirmation message doesn't throw an error # hearing a valid confirmation message doesn't throw an error
plaintext = json.dumps({}).encode("utf-8") plaintext = json.dumps({}).encode("utf-8")
data_key = w._derive_phase_key(side2, u"version") data_key = w._derive_phase_key(side2, "version")
confmsg = w._encrypt_data(data_key, plaintext) confmsg = w._encrypt_data(data_key, plaintext)
version2_hex = hexlify(confmsg).decode("ascii") version2_hex = hexlify(confmsg).decode("ascii")
response(w, type=u"message", phase=u"version", body=version2_hex, response(w, type="message", phase="version", body=version2_hex,
side=side2) side=side2)
# and it releases the verifier # and it releases the verifier
verifier = self.successResultOf(v) verifier = self.successResultOf(v)
self.assertEqual(verifier, self.assertEqual(verifier,
w.derive_key(u"wormhole:verifier", SecretBox.KEY_SIZE)) w.derive_key("wormhole:verifier", SecretBox.KEY_SIZE))
# an outbound message can now be sent immediately # an outbound message can now be sent immediately
w.send(b"phase0-outbound") w.send(b"phase0-outbound")
out = ws.outbound() out = ws.outbound()
self.assertEqual(len(out), 1) self.assertEqual(len(out), 1)
self.check_out(out[0], type=u"add", phase=u"0") self.check_out(out[0], type="add", phase="0")
# decrypt+check the outbound message # decrypt+check the outbound message
p0_outbound = unhexlify(out[0][u"body"].encode("ascii")) p0_outbound = unhexlify(out[0]["body"].encode("ascii"))
msgkey0 = w._derive_phase_key(w._side, u"0") msgkey0 = w._derive_phase_key(w._side, "0")
p0_plaintext = w._decrypt_data(msgkey0, p0_outbound) p0_plaintext = w._decrypt_data(msgkey0, p0_outbound)
self.assertEqual(p0_plaintext, b"phase0-outbound") self.assertEqual(p0_plaintext, b"phase0-outbound")
# get() waits for the inbound message to arrive # get() waits for the inbound message to arrive
md = w.get() md = w.get()
self.assertNoResult(md) self.assertNoResult(md)
self.assertIn(u"0", w._receive_waiters) self.assertIn("0", w._receive_waiters)
self.assertNotIn(u"0", w._received_messages) self.assertNotIn("0", w._received_messages)
msgkey1 = w._derive_phase_key(side2, u"0") msgkey1 = w._derive_phase_key(side2, "0")
p0_inbound = w._encrypt_data(msgkey1, b"phase0-inbound") p0_inbound = w._encrypt_data(msgkey1, b"phase0-inbound")
p0_inbound_hex = hexlify(p0_inbound).decode("ascii") p0_inbound_hex = hexlify(p0_inbound).decode("ascii")
response(w, type=u"message", phase=u"0", body=p0_inbound_hex, response(w, type="message", phase="0", body=p0_inbound_hex,
side=side2) side=side2)
p0_in = self.successResultOf(md) p0_in = self.successResultOf(md)
self.assertEqual(p0_in, b"phase0-inbound") self.assertEqual(p0_in, b"phase0-inbound")
self.assertNotIn(u"0", w._receive_waiters) self.assertNotIn("0", w._receive_waiters)
self.assertIn(u"0", w._received_messages) self.assertIn("0", w._received_messages)
# receiving an inbound message will queue it until get() is called # receiving an inbound message will queue it until get() is called
msgkey2 = w._derive_phase_key(side2, u"1") msgkey2 = w._derive_phase_key(side2, "1")
p1_inbound = w._encrypt_data(msgkey2, b"phase1-inbound") p1_inbound = w._encrypt_data(msgkey2, b"phase1-inbound")
p1_inbound_hex = hexlify(p1_inbound).decode("ascii") p1_inbound_hex = hexlify(p1_inbound).decode("ascii")
response(w, type=u"message", phase=u"1", body=p1_inbound_hex, response(w, type="message", phase="1", body=p1_inbound_hex,
side=side2) side=side2)
self.assertIn(u"1", w._received_messages) self.assertIn("1", w._received_messages)
self.assertNotIn(u"1", w._receive_waiters) self.assertNotIn("1", w._receive_waiters)
p1_in = self.successResultOf(w.get()) p1_in = self.successResultOf(w.get())
self.assertEqual(p1_in, b"phase1-inbound") self.assertEqual(p1_in, b"phase1-inbound")
self.assertIn(u"1", w._received_messages) self.assertIn("1", w._received_messages)
self.assertNotIn(u"1", w._receive_waiters) self.assertNotIn("1", w._receive_waiters)
d = w.close() d = w.close()
self.assertNoResult(d) self.assertNoResult(d)
out = ws.outbound() out = ws.outbound()
self.assertEqual(len(out), 1) self.assertEqual(len(out), 1)
self.check_out(out[0], type=u"close", mood=u"happy") self.check_out(out[0], type="close", mood="happy")
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"released") response(w, type="released")
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"closed") response(w, type="closed")
self.assertEqual(w._drop_connection.mock_calls, [mock.call()]) self.assertEqual(w._drop_connection.mock_calls, [mock.call()])
w._ws_closed(True, None, None) w._ws_closed(True, None, None)
self.assertEqual(self.successResultOf(d), None) self.assertEqual(self.successResultOf(d), None)
@ -317,7 +317,7 @@ class Basic(unittest.TestCase):
# Close before the connection is established. The connection still # Close before the connection is established. The connection still
# gets established, but it is then torn down before sending anything. # gets established, but it is then torn down before sending anything.
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
d = w.close() d = w.close()
@ -335,14 +335,14 @@ class Basic(unittest.TestCase):
def test_close_wait_1(self): def test_close_wait_1(self):
# close before even claiming the nameplate # close before even claiming the nameplate
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
ws = MockWebSocket() ws = MockWebSocket()
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
d = w.close() d = w.close()
self.check_outbound(ws, [u"bind"]) self.check_outbound(ws, ["bind"])
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, [mock.call()]) self.assertEqual(w._drop_connection.mock_calls, [mock.call()])
self.assertNoResult(d) self.assertNoResult(d)
@ -354,27 +354,27 @@ class Basic(unittest.TestCase):
# Close after claiming the nameplate, but before opening the mailbox. # Close after claiming the nameplate, but before opening the mailbox.
# The 'claimed' response arrives before we close. # The 'claimed' response arrives before we close.
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
ws = MockWebSocket() ws = MockWebSocket()
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
CODE = u"123-foo-bar" CODE = "123-foo-bar"
w.set_code(CODE) w.set_code(CODE)
self.check_outbound(ws, [u"bind", u"claim"]) self.check_outbound(ws, ["bind", "claim"])
response(w, type=u"claimed", mailbox=u"mb123") response(w, type="claimed", mailbox="mb123")
d = w.close() d = w.close()
self.check_outbound(ws, [u"open", u"add", u"release", u"close"]) self.check_outbound(ws, ["open", "add", "release", "close"])
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"released") response(w, type="released")
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"closed") response(w, type="closed")
self.assertEqual(w._drop_connection.mock_calls, [mock.call()]) self.assertEqual(w._drop_connection.mock_calls, [mock.call()])
self.assertNoResult(d) self.assertNoResult(d)
@ -385,22 +385,22 @@ class Basic(unittest.TestCase):
# close after claiming the nameplate, but before opening the mailbox # close after claiming the nameplate, but before opening the mailbox
# The 'claimed' response arrives after we start to close. # The 'claimed' response arrives after we start to close.
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
ws = MockWebSocket() ws = MockWebSocket()
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
CODE = u"123-foo-bar" CODE = "123-foo-bar"
w.set_code(CODE) w.set_code(CODE)
self.check_outbound(ws, [u"bind", u"claim"]) self.check_outbound(ws, ["bind", "claim"])
d = w.close() d = w.close()
response(w, type=u"claimed", mailbox=u"mb123") response(w, type="claimed", mailbox="mb123")
self.check_outbound(ws, [u"release"]) self.check_outbound(ws, ["release"])
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"released") response(w, type="released")
self.assertEqual(w._drop_connection.mock_calls, [mock.call()]) self.assertEqual(w._drop_connection.mock_calls, [mock.call()])
self.assertNoResult(d) self.assertNoResult(d)
@ -410,26 +410,26 @@ class Basic(unittest.TestCase):
def test_close_wait_4(self): def test_close_wait_4(self):
# close after both claiming the nameplate and opening the mailbox # close after both claiming the nameplate and opening the mailbox
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
ws = MockWebSocket() ws = MockWebSocket()
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
CODE = u"123-foo-bar" CODE = "123-foo-bar"
w.set_code(CODE) w.set_code(CODE)
response(w, type=u"claimed", mailbox=u"mb456") response(w, type="claimed", mailbox="mb456")
self.check_outbound(ws, [u"bind", u"claim", u"open", u"add"]) self.check_outbound(ws, ["bind", "claim", "open", "add"])
d = w.close() d = w.close()
self.check_outbound(ws, [u"release", u"close"]) self.check_outbound(ws, ["release", "close"])
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"released") response(w, type="released")
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"closed") response(w, type="closed")
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, [mock.call()]) self.assertEqual(w._drop_connection.mock_calls, [mock.call()])
@ -440,34 +440,34 @@ class Basic(unittest.TestCase):
# close after claiming the nameplate, opening the mailbox, then # close after claiming the nameplate, opening the mailbox, then
# releasing the nameplate # releasing the nameplate
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
ws = MockWebSocket() ws = MockWebSocket()
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
CODE = u"123-foo-bar" CODE = "123-foo-bar"
w.set_code(CODE) w.set_code(CODE)
response(w, type=u"claimed", mailbox=u"mb456") response(w, type="claimed", mailbox="mb456")
w._key = b"" w._key = b""
msgkey = w._derive_phase_key(u"side2", u"misc") msgkey = w._derive_phase_key("side2", "misc")
p1_inbound = w._encrypt_data(msgkey, b"") p1_inbound = w._encrypt_data(msgkey, b"")
p1_inbound_hex = hexlify(p1_inbound).decode("ascii") p1_inbound_hex = hexlify(p1_inbound).decode("ascii")
response(w, type=u"message", phase=u"misc", side=u"side2", response(w, type="message", phase="misc", side="side2",
body=p1_inbound_hex) body=p1_inbound_hex)
self.check_outbound(ws, [u"bind", u"claim", u"open", u"add", self.check_outbound(ws, ["bind", "claim", "open", "add",
u"release"]) "release"])
d = w.close() d = w.close()
self.check_outbound(ws, [u"close"]) self.check_outbound(ws, ["close"])
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"released") response(w, type="released")
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, []) self.assertEqual(w._drop_connection.mock_calls, [])
response(w, type=u"closed") response(w, type="closed")
self.assertNoResult(d) self.assertNoResult(d)
self.assertEqual(w._drop_connection.mock_calls, [mock.call()]) self.assertEqual(w._drop_connection.mock_calls, [mock.call()])
@ -481,11 +481,11 @@ class Basic(unittest.TestCase):
def test_get_code_mock(self): def test_get_code_mock(self):
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
ws = MockWebSocket() # TODO: mock w._ws_send_command instead ws = MockWebSocket() # TODO: mock w._ws_send_command instead
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
self.check_outbound(ws, [u"bind"]) self.check_outbound(ws, ["bind"])
gc_c = mock.Mock() gc_c = mock.Mock()
gc = gc_c.return_value = mock.Mock() gc = gc_c.return_value = mock.Mock()
@ -494,31 +494,31 @@ class Basic(unittest.TestCase):
d = w.get_code() d = w.get_code()
self.assertNoResult(d) self.assertNoResult(d)
gc_d.callback(u"123-foo-bar") gc_d.callback("123-foo-bar")
code = self.successResultOf(d) code = self.successResultOf(d)
self.assertEqual(code, u"123-foo-bar") self.assertEqual(code, "123-foo-bar")
def test_get_code_real(self): def test_get_code_real(self):
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
ws = MockWebSocket() ws = MockWebSocket()
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
self.check_outbound(ws, [u"bind"]) self.check_outbound(ws, ["bind"])
d = w.get_code() d = w.get_code()
out = ws.outbound() out = ws.outbound()
self.assertEqual(len(out), 1) self.assertEqual(len(out), 1)
self.check_out(out[0], type=u"allocate") self.check_out(out[0], type="allocate")
# TODO: nameplate attributes go here # TODO: nameplate attributes go here
self.assertNoResult(d) self.assertNoResult(d)
response(w, type=u"allocated", nameplate=u"123") response(w, type="allocated", nameplate="123")
code = self.successResultOf(d) code = self.successResultOf(d)
self.assertIsInstance(code, type(u"")) self.assertIsInstance(code, type(""))
self.assert_(code.startswith(u"123-")) self.assert_(code.startswith("123-"))
pieces = code.split(u"-") pieces = code.split("-")
self.assertEqual(len(pieces), 3) # nameplate plus two words self.assertEqual(len(pieces), 3) # nameplate plus two words
self.assert_(re.search(r'^\d+-\w+-\w+$', code), code) self.assert_(re.search(r'^\d+-\w+-\w+$', code), code)
@ -532,11 +532,11 @@ class Basic(unittest.TestCase):
#print(when, order, success) #print(when, order, success)
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
w._ws_send_command = mock.Mock() w._ws_send_command = mock.Mock()
w._mailbox_state = wormhole.OPEN w._mailbox_state = wormhole.OPEN
side2 = u"side2" side2 = "side2"
d = None d = None
if success: if success:
@ -544,7 +544,7 @@ class Basic(unittest.TestCase):
else: else:
w._key = b"wrongkey" w._key = b"wrongkey"
plaintext = json.dumps({}).encode("utf-8") plaintext = json.dumps({}).encode("utf-8")
data_key = w._derive_phase_key(side2, u"version") data_key = w._derive_phase_key(side2, "version")
confmsg = w._encrypt_data(data_key, plaintext) confmsg = w._encrypt_data(data_key, plaintext)
w._key = None w._key = None
@ -595,12 +595,12 @@ class Basic(unittest.TestCase):
# states in which we might see it. # states in which we might see it.
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
ws = MockWebSocket() ws = MockWebSocket()
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
self.check_outbound(ws, [u"bind"]) self.check_outbound(ws, ["bind"])
d1 = w.get() d1 = w.get()
d2 = w.verify() d2 = w.verify()
@ -611,15 +611,15 @@ class Basic(unittest.TestCase):
self.assertNoResult(d2) self.assertNoResult(d2)
self.assertNoResult(d3) self.assertNoResult(d3)
w._signal_error(WelcomeError(u"you are not actually welcome"), u"pouty") w._signal_error(WelcomeError("you are not actually welcome"), "pouty")
self.failureResultOf(d1, WelcomeError) self.failureResultOf(d1, WelcomeError)
self.failureResultOf(d2, WelcomeError) self.failureResultOf(d2, WelcomeError)
self.failureResultOf(d3, WelcomeError) self.failureResultOf(d3, WelcomeError)
# once the error is signalled, all API calls should fail # once the error is signalled, all API calls should fail
self.assertRaises(WelcomeError, w.send, u"foo") self.assertRaises(WelcomeError, w.send, "foo")
self.assertRaises(WelcomeError, self.assertRaises(WelcomeError,
w.derive_key, u"foo", SecretBox.KEY_SIZE) w.derive_key, "foo", SecretBox.KEY_SIZE)
self.failureResultOf(w.get(), WelcomeError) self.failureResultOf(w.get(), WelcomeError)
self.failureResultOf(w.verify(), WelcomeError) self.failureResultOf(w.verify(), WelcomeError)
@ -628,13 +628,13 @@ class Basic(unittest.TestCase):
# PAKE message, by which point we should know the key. If the # PAKE message, by which point we should know the key. If the
# confirmation message doesn't decrypt, we signal an error. # confirmation message doesn't decrypt, we signal an error.
timing = DebugTiming() timing = DebugTiming()
w = wormhole._Wormhole(APPID, u"relay_url", reactor, None, timing) w = wormhole._Wormhole(APPID, "relay_url", reactor, None, timing)
w._drop_connection = mock.Mock() w._drop_connection = mock.Mock()
ws = MockWebSocket() ws = MockWebSocket()
w._event_connected(ws) w._event_connected(ws)
w._event_ws_opened(None) w._event_ws_opened(None)
w.set_code(u"123-foo-bar") w.set_code("123-foo-bar")
response(w, type=u"claimed", mailbox=u"mb456") response(w, type="claimed", mailbox="mb456")
d1 = w.get() d1 = w.get()
d2 = w.verify() d2 = w.verify()
@ -642,33 +642,33 @@ class Basic(unittest.TestCase):
self.assertNoResult(d2) self.assertNoResult(d2)
out = ws.outbound() out = ws.outbound()
# [u"bind", u"claim", u"open", u"add"] # ["bind", "claim", "open", "add"]
self.assertEqual(len(out), 4) self.assertEqual(len(out), 4)
self.assertEqual(out[3][u"type"], u"add") self.assertEqual(out[3]["type"], "add")
sp2 = SPAKE2_Symmetric(b"", idSymmetric=wormhole.to_bytes(APPID)) sp2 = SPAKE2_Symmetric(b"", idSymmetric=wormhole.to_bytes(APPID))
msg2 = sp2.start() msg2 = sp2.start()
payload = {u"pake_v1": bytes_to_hexstr(msg2)} payload = {"pake_v1": bytes_to_hexstr(msg2)}
body_hex = bytes_to_hexstr(dict_to_bytes(payload)) body_hex = bytes_to_hexstr(dict_to_bytes(payload))
response(w, type=u"message", phase=u"pake", body=body_hex, side=u"s2") response(w, type="message", phase="pake", body=body_hex, side="s2")
self.assertNoResult(d1) self.assertNoResult(d1)
self.assertNoResult(d2) # verify() waits for confirmation self.assertNoResult(d2) # verify() waits for confirmation
# sending a random version message will cause a confirmation error # sending a random version message will cause a confirmation error
confkey = w.derive_key(u"WRONG", SecretBox.KEY_SIZE) confkey = w.derive_key("WRONG", SecretBox.KEY_SIZE)
nonce = os.urandom(wormhole.CONFMSG_NONCE_LENGTH) nonce = os.urandom(wormhole.CONFMSG_NONCE_LENGTH)
badversion = wormhole.make_confmsg(confkey, nonce) badversion = wormhole.make_confmsg(confkey, nonce)
badversion_hex = hexlify(badversion).decode("ascii") badversion_hex = hexlify(badversion).decode("ascii")
response(w, type=u"message", phase=u"version", body=badversion_hex, response(w, type="message", phase="version", body=badversion_hex,
side=u"s2") side="s2")
self.failureResultOf(d1, WrongPasswordError) self.failureResultOf(d1, WrongPasswordError)
self.failureResultOf(d2, WrongPasswordError) self.failureResultOf(d2, WrongPasswordError)
# once the error is signalled, all API calls should fail # once the error is signalled, all API calls should fail
self.assertRaises(WrongPasswordError, w.send, u"foo") self.assertRaises(WrongPasswordError, w.send, "foo")
self.assertRaises(WrongPasswordError, self.assertRaises(WrongPasswordError,
w.derive_key, u"foo", SecretBox.KEY_SIZE) w.derive_key, "foo", SecretBox.KEY_SIZE)
self.failureResultOf(w.get(), WrongPasswordError) self.failureResultOf(w.get(), WrongPasswordError)
self.failureResultOf(w.verify(), WrongPasswordError) self.failureResultOf(w.verify(), WrongPasswordError)
@ -757,8 +757,8 @@ class Wormholes(ServerBase, unittest.TestCase):
w1.send(b"data1") w1.send(b"data1")
w2 = wormhole.wormhole(APPID, self.relayurl, reactor) w2 = wormhole.wormhole(APPID, self.relayurl, reactor)
d = w2.get() d = w2.get()
w1.set_code(u"123-abc-def") w1.set_code("123-abc-def")
w2.set_code(u"123-abc-def") w2.set_code("123-abc-def")
dataY = yield d dataY = yield d
self.assertEqual(dataY, b"data1") self.assertEqual(dataY, b"data1")
yield w1.close() yield w1.close()
@ -768,8 +768,8 @@ class Wormholes(ServerBase, unittest.TestCase):
def test_fixed_code(self): def test_fixed_code(self):
w1 = wormhole.wormhole(APPID, self.relayurl, reactor) w1 = wormhole.wormhole(APPID, self.relayurl, reactor)
w2 = wormhole.wormhole(APPID, self.relayurl, reactor) w2 = wormhole.wormhole(APPID, self.relayurl, reactor)
w1.set_code(u"123-purple-elephant") w1.set_code("123-purple-elephant")
w2.set_code(u"123-purple-elephant") w2.set_code("123-purple-elephant")
w1.send(b"data1"), w2.send(b"data2") w1.send(b"data1"), w2.send(b"data2")
dl = yield self.doBoth(w1.get(), w2.get()) dl = yield self.doBoth(w1.get(), w2.get())
(dataX, dataY) = dl (dataX, dataY) = dl
@ -783,8 +783,8 @@ class Wormholes(ServerBase, unittest.TestCase):
def test_multiple_messages(self): def test_multiple_messages(self):
w1 = wormhole.wormhole(APPID, self.relayurl, reactor) w1 = wormhole.wormhole(APPID, self.relayurl, reactor)
w2 = wormhole.wormhole(APPID, self.relayurl, reactor) w2 = wormhole.wormhole(APPID, self.relayurl, reactor)
w1.set_code(u"123-purple-elephant") w1.set_code("123-purple-elephant")
w2.set_code(u"123-purple-elephant") w2.set_code("123-purple-elephant")
w1.send(b"data1"), w2.send(b"data2") w1.send(b"data1"), w2.send(b"data2")
w1.send(b"data3"), w2.send(b"data4") w1.send(b"data3"), w2.send(b"data4")
dl = yield self.doBoth(w1.get(), w2.get()) dl = yield self.doBoth(w1.get(), w2.get())
@ -859,15 +859,15 @@ class Wormholes(ServerBase, unittest.TestCase):
def test_versions(self): def test_versions(self):
# there's no API for this yet, but make sure the internals work # there's no API for this yet, but make sure the internals work
w1 = wormhole.wormhole(APPID, self.relayurl, reactor) w1 = wormhole.wormhole(APPID, self.relayurl, reactor)
w1._my_versions = {u"w1": 123} w1._my_versions = {"w1": 123}
w2 = wormhole.wormhole(APPID, self.relayurl, reactor) w2 = wormhole.wormhole(APPID, self.relayurl, reactor)
w2._my_versions = {u"w2": 456} w2._my_versions = {"w2": 456}
code = yield w1.get_code() code = yield w1.get_code()
w2.set_code(code) w2.set_code(code)
yield w1.verify() yield w1.verify()
self.assertEqual(w1._their_versions, {u"w2": 456}) self.assertEqual(w1._their_versions, {"w2": 456})
yield w2.verify() yield w2.verify()
self.assertEqual(w2._their_versions, {u"w1": 123}) self.assertEqual(w2._their_versions, {"w1": 123})
yield w1.close() yield w1.close()
yield w2.close() yield w2.close()
@ -876,11 +876,11 @@ class Errors(ServerBase, unittest.TestCase):
def test_codes_1(self): def test_codes_1(self):
w = wormhole.wormhole(APPID, self.relayurl, reactor) w = wormhole.wormhole(APPID, self.relayurl, reactor)
# definitely too early # definitely too early
self.assertRaises(UsageError, w.derive_key, u"purpose", 12) self.assertRaises(UsageError, w.derive_key, "purpose", 12)
w.set_code(u"123-purple-elephant") w.set_code("123-purple-elephant")
# code can only be set once # code can only be set once
self.assertRaises(UsageError, w.set_code, u"123-nope") self.assertRaises(UsageError, w.set_code, "123-nope")
yield self.assertFailure(w.get_code(), UsageError) yield self.assertFailure(w.get_code(), UsageError)
yield self.assertFailure(w.input_code(), UsageError) yield self.assertFailure(w.input_code(), UsageError)
yield w.close() yield w.close()
@ -889,7 +889,7 @@ class Errors(ServerBase, unittest.TestCase):
def test_codes_2(self): def test_codes_2(self):
w = wormhole.wormhole(APPID, self.relayurl, reactor) w = wormhole.wormhole(APPID, self.relayurl, reactor)
yield w.get_code() yield w.get_code()
self.assertRaises(UsageError, w.set_code, u"123-nope") self.assertRaises(UsageError, w.set_code, "123-nope")
yield self.assertFailure(w.get_code(), UsageError) yield self.assertFailure(w.get_code(), UsageError)
yield self.assertFailure(w.input_code(), UsageError) yield self.assertFailure(w.input_code(), UsageError)
yield w.close() yield w.close()

View File

@ -1,3 +1,4 @@
# No unicode_literals
import json, unicodedata import json, unicodedata
from binascii import hexlify, unhexlify from binascii import hexlify, unhexlify

View File

@ -77,15 +77,15 @@ class _GetCode:
@inlineCallbacks @inlineCallbacks
def go(self): def go(self):
with self._timing.add("allocate"): with self._timing.add("allocate"):
self._send_command(u"allocate") self._send_command("allocate")
nameplate_id = yield self._allocated_d nameplate_id = yield self._allocated_d
code = codes.make_code(nameplate_id, self._code_length) code = codes.make_code(nameplate_id, self._code_length)
assert isinstance(code, type(u"")), type(code) assert isinstance(code, type("")), type(code)
returnValue(code) returnValue(code)
def _response_handle_allocated(self, msg): def _response_handle_allocated(self, msg):
nid = msg["nameplate"] nid = msg["nameplate"]
assert isinstance(nid, type(u"")), type(nid) assert isinstance(nid, type("")), type(nid)
self._allocated_d.callback(nid) self._allocated_d.callback(nid)
class _InputCode: class _InputCode:
@ -99,7 +99,7 @@ class _InputCode:
@inlineCallbacks @inlineCallbacks
def _list(self): def _list(self):
self._lister_d = defer.Deferred() self._lister_d = defer.Deferred()
self._send_command(u"list") self._send_command("list")
nameplates = yield self._lister_d nameplates = yield self._lister_d
self._lister_d = None self._lister_d = None
returnValue(nameplates) returnValue(nameplates)
@ -135,8 +135,8 @@ class _InputCode:
nids = [] nids = []
for n in nameplates: for n in nameplates:
assert isinstance(n, dict), type(n) assert isinstance(n, dict), type(n)
nameplate_id = n[u"id"] nameplate_id = n["id"]
assert isinstance(nameplate_id, type(u"")), type(nameplate_id) assert isinstance(nameplate_id, type("")), type(nameplate_id)
nids.append(nameplate_id) nids.append(nameplate_id)
self._lister_d.callback(nids) self._lister_d.callback(nids)
@ -202,7 +202,7 @@ class _WelcomeHandler:
if "error" in welcome: if "error" in welcome:
return self._signal_error(WelcomeError(welcome["error"]), return self._signal_error(WelcomeError(welcome["error"]),
u"unwelcome") "unwelcome")
# states for nameplates, mailboxes, and the websocket connection # states for nameplates, mailboxes, and the websocket connection
(CLOSED, OPENING, OPEN, CLOSING) = ("closed", "opening", "open", "closing") (CLOSED, OPENING, OPEN, CLOSING) = ("closed", "opening", "open", "closing")
@ -378,7 +378,7 @@ class _Wormhole:
self._connection_state = OPEN self._connection_state = OPEN
if self._closing: if self._closing:
return self._maybe_finished_closing() return self._maybe_finished_closing()
self._ws_send_command(u"bind", appid=self._appid, side=self._side) self._ws_send_command("bind", appid=self._appid, side=self._side)
self._maybe_claim_nameplate() self._maybe_claim_nameplate()
self._maybe_send_pake() self._maybe_send_pake()
waiters, self._connection_waiters = self._connection_waiters, [] waiters, self._connection_waiters = self._connection_waiters, []
@ -462,7 +462,7 @@ class _Wormhole:
# entry point 3: paste in a fully-formed code # entry point 3: paste in a fully-formed code
def _API_set_code(self, code): def _API_set_code(self, code):
self._timing.add("API set_code") self._timing.add("API set_code")
if not isinstance(code, type(u"")): raise TypeError(type(code)) if not isinstance(code, type("")): raise TypeError(type(code))
if self._code is not None: raise UsageError if self._code is not None: raise UsageError
self._event_learned_code(code) self._event_learned_code(code)
@ -488,7 +488,7 @@ class _Wormhole:
if not mo: if not mo:
raise ValueError("code (%s) must start with NN-" % code) raise ValueError("code (%s) must start with NN-" % code)
nid = mo.group(1) nid = mo.group(1)
assert isinstance(nid, type(u"")), type(nid) assert isinstance(nid, type("")), type(nid)
self._nameplate_id = nid self._nameplate_id = nid
# fire more events # fire more events
self._maybe_build_msg1() self._maybe_build_msg1()
@ -516,12 +516,12 @@ class _Wormhole:
def _maybe_claim_nameplate(self): def _maybe_claim_nameplate(self):
if not (self._nameplate_id and self._connection_state == OPEN): if not (self._nameplate_id and self._connection_state == OPEN):
return return
self._ws_send_command(u"claim", nameplate=self._nameplate_id) self._ws_send_command("claim", nameplate=self._nameplate_id)
self._nameplate_state = OPEN self._nameplate_state = OPEN
def _response_handle_claimed(self, msg): def _response_handle_claimed(self, msg):
mailbox_id = msg["mailbox"] mailbox_id = msg["mailbox"]
assert isinstance(mailbox_id, type(u"")), type(mailbox_id) assert isinstance(mailbox_id, type("")), type(mailbox_id)
self._mailbox_id = mailbox_id self._mailbox_id = mailbox_id
self._event_learned_mailbox() self._event_learned_mailbox()
@ -530,7 +530,7 @@ class _Wormhole:
assert self._mailbox_state == CLOSED, self._mailbox_state assert self._mailbox_state == CLOSED, self._mailbox_state
if self._closing: if self._closing:
return return
self._ws_send_command(u"open", mailbox=self._mailbox_id) self._ws_send_command("open", mailbox=self._mailbox_id)
self._mailbox_state = OPEN self._mailbox_state = OPEN
# causes old messages to be sent now, and subscribes to new messages # causes old messages to be sent now, and subscribes to new messages
self._maybe_send_pake() self._maybe_send_pake()
@ -542,14 +542,14 @@ class _Wormhole:
and self._mailbox_state == OPEN and self._mailbox_state == OPEN
and self._flag_need_to_send_PAKE): and self._flag_need_to_send_PAKE):
return return
body = {u"pake_v1": bytes_to_hexstr(self._msg1)} body = {"pake_v1": bytes_to_hexstr(self._msg1)}
payload = dict_to_bytes(body) payload = dict_to_bytes(body)
self._msg_send(u"pake", payload) self._msg_send("pake", payload)
self._flag_need_to_send_PAKE = False self._flag_need_to_send_PAKE = False
def _event_received_pake(self, pake_msg): def _event_received_pake(self, pake_msg):
payload = bytes_to_dict(pake_msg) payload = bytes_to_dict(pake_msg)
msg2 = hexstr_to_bytes(payload[u"pake_v1"]) msg2 = hexstr_to_bytes(payload["pake_v1"])
with self._timing.add("pake2", waiting="crypto"): with self._timing.add("pake2", waiting="crypto"):
self._key = self._sp.finish(msg2) self._key = self._sp.finish(msg2)
self._event_established_key() self._event_established_key()
@ -571,7 +571,7 @@ class _Wormhole:
# dictionary of version flags to let the other Wormhole know what # dictionary of version flags to let the other Wormhole know what
# we're capable of (for future expansion) # we're capable of (for future expansion)
plaintext = dict_to_bytes(self._my_versions) plaintext = dict_to_bytes(self._my_versions)
phase = u"version" phase = "version"
data_key = self._derive_phase_key(self._side, phase) data_key = self._derive_phase_key(self._side, phase)
encrypted = self._encrypt_data(data_key, plaintext) encrypted = self._encrypt_data(data_key, plaintext)
self._msg_send(phase, encrypted) self._msg_send(phase, encrypted)
@ -616,13 +616,13 @@ class _Wormhole:
self._version_checked = True self._version_checked = True
side, body = self._version_message side, body = self._version_message
data_key = self._derive_phase_key(side, u"version") data_key = self._derive_phase_key(side, "version")
try: try:
plaintext = self._decrypt_data(data_key, body) plaintext = self._decrypt_data(data_key, body)
except CryptoError: except CryptoError:
# this makes all API calls fail # this makes all API calls fail
if self.DEBUG: print("CONFIRM FAILED") if self.DEBUG: print("CONFIRM FAILED")
self._signal_error(WrongPasswordError(), u"scary") self._signal_error(WrongPasswordError(), "scary")
return return
msg = bytes_to_dict(plaintext) msg = bytes_to_dict(plaintext)
self._version_received(msg) self._version_received(msg)
@ -643,8 +643,8 @@ class _Wormhole:
self._maybe_send_phase_messages() self._maybe_send_phase_messages()
def _derive_phase_key(self, side, phase): def _derive_phase_key(self, side, phase):
assert isinstance(side, type(u"")), type(side) assert isinstance(side, type("")), type(side)
assert isinstance(phase, type(u"")), type(phase) assert isinstance(phase, type("")), type(phase)
side_bytes = side.encode("ascii") side_bytes = side.encode("ascii")
phase_bytes = phase.encode("ascii") phase_bytes = phase.encode("ascii")
purpose = (b"wormhole:phase:" purpose = (b"wormhole:phase:"
@ -663,7 +663,7 @@ class _Wormhole:
for pm in plaintexts: for pm in plaintexts:
(phase_int, plaintext) = pm (phase_int, plaintext) = pm
assert isinstance(phase_int, int), type(phase_int) assert isinstance(phase_int, int), type(phase_int)
phase = u"%d" % phase_int phase = "%d" % phase_int
data_key = self._derive_phase_key(self._side, phase) data_key = self._derive_phase_key(self._side, phase)
encrypted = self._encrypt_data(data_key, plaintext) encrypted = self._encrypt_data(data_key, plaintext)
self._msg_send(phase, encrypted) self._msg_send(phase, encrypted)
@ -689,7 +689,7 @@ class _Wormhole:
# TODO: retry on failure, with exponential backoff. We're guarding # TODO: retry on failure, with exponential backoff. We're guarding
# against the rendezvous server being temporarily offline. # against the rendezvous server being temporarily offline.
self._timing.add("add", phase=phase) self._timing.add("add", phase=phase)
self._ws_send_command(u"add", phase=phase, body=bytes_to_hexstr(body)) self._ws_send_command("add", phase=phase, body=bytes_to_hexstr(body))
def _event_mailbox_used(self): def _event_mailbox_used(self):
if self.DEBUG: print("_event_mailbox_used") if self.DEBUG: print("_event_mailbox_used")
@ -701,7 +701,7 @@ class _Wormhole:
if self._error: raise self._error if self._error: raise self._error
if self._key is None: if self._key is None:
raise UsageError # call derive_key after get_verifier() or get() raise UsageError # call derive_key after get_verifier() or get()
if not isinstance(purpose, type(u"")): raise TypeError(type(purpose)) if not isinstance(purpose, type("")): raise TypeError(type(purpose))
return self._derive_key(to_bytes(purpose), length) return self._derive_key(to_bytes(purpose), length)
def _derive_key(self, purpose, length=SecretBox.KEY_SIZE): def _derive_key(self, purpose, length=SecretBox.KEY_SIZE):
@ -713,7 +713,7 @@ class _Wormhole:
def _response_handle_message(self, msg): def _response_handle_message(self, msg):
side = msg["side"] side = msg["side"]
phase = msg["phase"] phase = msg["phase"]
assert isinstance(phase, type(u"")), type(phase) assert isinstance(phase, type("")), type(phase)
body = hexstr_to_bytes(msg["body"]) body = hexstr_to_bytes(msg["body"])
if side == self._side: if side == self._side:
return return
@ -726,9 +726,9 @@ class _Wormhole:
if self._closing: if self._closing:
log.msg("received peer message while closing '%s'" % phase) log.msg("received peer message while closing '%s'" % phase)
if phase == u"pake": if phase == "pake":
return self._event_received_pake(body) return self._event_received_pake(body)
if phase == u"version": if phase == "version":
return self._event_received_version(side, body) return self._event_received_version(side, body)
if re.search(r'^\d+$', phase): if re.search(r'^\d+$', phase):
return self._event_received_phase_message(side, phase, body) return self._event_received_phase_message(side, phase, body)
@ -743,7 +743,7 @@ class _Wormhole:
plaintext = self._decrypt_data(data_key, body) plaintext = self._decrypt_data(data_key, body)
except CryptoError: except CryptoError:
e = WrongPasswordError() e = WrongPasswordError()
self._signal_error(e, u"scary") # flunk all other API calls self._signal_error(e, "scary") # flunk all other API calls
# make tests fail, if they aren't explicitly catching it # make tests fail, if they aren't explicitly catching it
if self.DEBUG: print("CryptoError in msg received") if self.DEBUG: print("CryptoError in msg received")
log.err(e) log.err(e)
@ -764,7 +764,7 @@ class _Wormhole:
def _API_get(self): def _API_get(self):
if self._error: return defer.fail(self._error) if self._error: return defer.fail(self._error)
phase = u"%d" % self._next_receive_phase phase = "%d" % self._next_receive_phase
self._next_receive_phase += 1 self._next_receive_phase += 1
with self._timing.add("API get", phase=phase): with self._timing.add("API get", phase=phase):
if phase in self._received_messages: if phase in self._received_messages:
@ -780,7 +780,7 @@ class _Wormhole:
if self.DEBUG: print("_signal_error done") if self.DEBUG: print("_signal_error done")
@inlineCallbacks @inlineCallbacks
def _API_close(self, res, mood=u"happy"): def _API_close(self, res, mood="happy"):
if self.DEBUG: print("close") if self.DEBUG: print("close")
if self._close_called: raise UsageError if self._close_called: raise UsageError
self._close_called = True self._close_called = True
@ -838,7 +838,7 @@ class _Wormhole:
if self.DEBUG: print("_maybe_release_nameplate", self._nameplate_state) if self.DEBUG: print("_maybe_release_nameplate", self._nameplate_state)
if self._nameplate_state == OPEN: if self._nameplate_state == OPEN:
if self.DEBUG: print(" sending release") if self.DEBUG: print(" sending release")
self._ws_send_command(u"release") self._ws_send_command("release")
self._nameplate_state = CLOSING self._nameplate_state = CLOSING
def _response_handle_released(self, msg): def _response_handle_released(self, msg):
@ -849,7 +849,7 @@ class _Wormhole:
if self.DEBUG: print("_maybe_close_mailbox", self._mailbox_state) if self.DEBUG: print("_maybe_close_mailbox", self._mailbox_state)
if self._mailbox_state == OPEN: if self._mailbox_state == OPEN:
if self.DEBUG: print(" sending close") if self.DEBUG: print(" sending close")
self._ws_send_command(u"close", mood=mood) self._ws_send_command("close", mood=mood)
self._mailbox_state = CLOSING self._mailbox_state = CLOSING
def _response_handle_closed(self, msg): def _response_handle_closed(self, msg):