fix stats-writing bug on py3

refs #67
This commit is contained in:
Brian Warner 2016-08-01 16:31:05 -07:00
parent 094a121f3a
commit dc6416a257
2 changed files with 28 additions and 4 deletions

View File

@ -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)

View File

@ -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):