Pass a time function instead of patching the global

This commit is contained in:
Jean-Paul Calderone 2023-03-28 08:52:31 -04:00
parent 6b7ea29d88
commit 32cd54501d
2 changed files with 4 additions and 4 deletions

View File

@ -105,8 +105,7 @@ class Status(unittest.TestCase):
ri.nextAttempt = 20 ri.nextAttempt = 20
ri.connectionInfo = ci ri.connectionInfo = ci
rc = reconnector(ri) rc = reconnector(ri)
with mock.patch("time.time", return_value=12): cs = connection_status.from_foolscap_reconnector(rc, 5, time=lambda: 12)
cs = connection_status.from_foolscap_reconnector(rc, 5)
self.assertEqual(cs.connected, False) self.assertEqual(cs.connected, False)
self.assertEqual(cs.summary, self.assertEqual(cs.summary,
"Reconnecting in 8 seconds (last attempt 2s ago)") "Reconnecting in 8 seconds (last attempt 2s ago)")

View File

@ -16,6 +16,7 @@ if PY2:
import time import time
from zope.interface import implementer from zope.interface import implementer
from ..interfaces import IConnectionStatus from ..interfaces import IConnectionStatus
from foolscap.reconnector import Reconnector
@implementer(IConnectionStatus) @implementer(IConnectionStatus)
class ConnectionStatus(object): class ConnectionStatus(object):
@ -50,7 +51,7 @@ def _hint_statuses(which, handlers, statuses):
non_connected_statuses["%s%s" % (hint, handler_dsc)] = dsc non_connected_statuses["%s%s" % (hint, handler_dsc)] = dsc
return non_connected_statuses return non_connected_statuses
def from_foolscap_reconnector(rc, last_received): def from_foolscap_reconnector(rc: Reconnector, last_received: int, time=time.time) -> ConnectionStatus:
ri = rc.getReconnectionInfo() ri = rc.getReconnectionInfo()
# See foolscap/reconnector.py, ReconnectionInfo, for details about possible # See foolscap/reconnector.py, ReconnectionInfo, for details about possible
# states. The returned result is a native string, it seems, so convert to # states. The returned result is a native string, it seems, so convert to
@ -80,7 +81,7 @@ def from_foolscap_reconnector(rc, last_received):
# ci describes the current in-progress attempt # ci describes the current in-progress attempt
summary = "Trying to connect" summary = "Trying to connect"
elif state == "waiting": elif state == "waiting":
now = time.time() now = time()
elapsed = now - ri.lastAttempt elapsed = now - ri.lastAttempt
delay = ri.nextAttempt - now delay = ri.nextAttempt - now
summary = "Reconnecting in %d seconds (last attempt %ds ago)" % \ summary = "Reconnecting in %d seconds (last attempt %ds ago)" % \