diff --git a/src/wormhole/server/server.py b/src/wormhole/server/server.py index bddf4a4..6b2419f 100644 --- a/src/wormhole/server/server.py +++ b/src/wormhole/server/server.py @@ -131,6 +131,7 @@ class RelayServer(service.MultiService): log.msg("get_stats took:", time.time() - start) with open(tmpfn, "wb") as f: - json.dump(data, f, indent=1) - f.write("\n") + # json.dump(f) has str-vs-unicode issues on py2-vs-py3 + f.write(json.dumps(data, indent=1).encode("utf-8")) + f.write(b"\n") os.rename(tmpfn, self._stats_file) diff --git a/src/wormhole/test/test_server.py b/src/wormhole/test/test_server.py index c79ebf0..89092b1 100644 --- a/src/wormhole/test/test_server.py +++ b/src/wormhole/test/test_server.py @@ -1,5 +1,5 @@ from __future__ import print_function, unicode_literals -import json, itertools, time +import os, json, itertools, time from binascii import hexlify import mock from twisted.trial import unittest @@ -11,7 +11,7 @@ from twisted.web import client from autobahn.twisted import websocket from .. import __version__ from .common import ServerBase -from ..server import rendezvous, transit_server +from ..server import server, rendezvous, transit_server from ..server.rendezvous import Usage, SidedMessage from ..server.database import get_db @@ -1043,6 +1043,29 @@ class Summary(unittest.TestCase): row = db.execute("SELECT * FROM `mailbox_usage`").fetchone() self.assertEqual(row["started"], 20) +class DumpStats(unittest.TestCase): + def test_nostats(self): + rs = server.RelayServer(str("tcp:0"), str("tcp:0"), None) + # with no ._stats_file, this should do nothing + rs.dump_stats(1, 1) + + def test_empty(self): + basedir = self.mktemp() + os.mkdir(basedir) + fn = os.path.join(basedir, "stats.json") + rs = server.RelayServer(str("tcp:0"), str("tcp:0"), None, + stats_file=fn) + now = 1234 + validity = 500 + rs.dump_stats(now, validity) + with open(fn, "rb") as f: + data_bytes = f.read() + data = json.loads(data_bytes.decode("utf-8")) + self.assertEqual(data["created"], now) + self.assertEqual(data["valid_until"], now+validity) + self.assertEqual(data["rendezvous"]["all_time"]["mailboxes_total"], 0) + self.assertEqual(data["transit"]["all_time"]["total"], 0) + class Accumulator(protocol.Protocol): def __init__(self):