Refactor timeago and add tests

_timeago is not specialized for mesh interfaces so it is factored
out into a private function
This commit is contained in:
Federico Ceratto
2024-06-21 10:28:45 +02:00
parent b5d1b7612f
commit c34d08b0e5
2 changed files with 36 additions and 17 deletions

View File

@@ -41,6 +41,29 @@ from meshtastic.util import (
)
def _timeago(delta_secs: int) -> str:
"""Convert a number of seconds in the past into a short, friendly string
e.g. "now", "30 sec ago", "1 hour ago"
Zero or negative intervals simply return "now"
"""
intervals = (
("year", 60 * 60 * 24 * 365),
("month", 60 * 60 * 24 * 30),
("day", 60 * 60 * 24),
("hour", 60 * 60),
("min", 60),
("sec", 1),
)
for name, interval_duration in intervals:
if delta_secs < interval_duration:
continue
x = delta_secs // interval_duration
plur = "s" if x > 1 else ""
return f"{x} {name}{plur} ago"
return "now"
class MeshInterface: # pylint: disable=R0902
"""Interface class for meshtastic devices
@@ -163,22 +186,7 @@ class MeshInterface: # pylint: disable=R0902
delta_secs = int(delta.total_seconds())
if delta_secs < 0:
return None # not handling a timestamp from the future
intervals = (
("year", 60 * 60 * 24 * 365),
("month", 60 * 60 * 24 * 30),
("day", 60 * 60 * 24),
("hour", 60 * 60),
("min", 60),
("sec", 1),
)
for name, interval_duration in intervals:
if delta_secs < interval_duration:
continue
x = delta_secs // interval_duration
plur = "s" if x > 1 else ""
return f"{x} {name}{plur} ago"
return "now"
return _timeago(delta_secs)
rows: List[Dict[str, Any]] = []
if self.nodesByNum:

View File

@@ -7,7 +7,7 @@ from unittest.mock import MagicMock, patch
import pytest
from .. import mesh_pb2, config_pb2, BROADCAST_ADDR, LOCAL_ADDR
from ..mesh_interface import MeshInterface
from ..mesh_interface import MeshInterface, _timeago
from ..node import Node
# TODO
@@ -684,3 +684,14 @@ def test_waitConnected_isConnected_timeout(capsys):
out, err = capsys.readouterr()
assert re.search(r"warn about something", err, re.MULTILINE)
assert out == ""
@pytest.mark.unit
def test_timeago():
assert _timeago(0) == "now"
assert _timeago(1) == "1 sec ago"
assert _timeago(15) == "15 secs ago"
assert _timeago(333) == "5 mins ago"
assert _timeago(99999) == "1 day ago"
assert _timeago(9999999) == "3 months ago"
assert _timeago(-999) == "now"