Skip to content

Commit c34d08b

Browse files
Refactor timeago and add tests
_timeago is not specialized for mesh interfaces so it is factored out into a private function
1 parent b5d1b76 commit c34d08b

2 files changed

Lines changed: 36 additions & 17 deletions

File tree

meshtastic/mesh_interface.py

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,29 @@
4141
)
4242

4343

44+
def _timeago(delta_secs: int) -> str:
45+
"""Convert a number of seconds in the past into a short, friendly string
46+
e.g. "now", "30 sec ago", "1 hour ago"
47+
Zero or negative intervals simply return "now"
48+
"""
49+
intervals = (
50+
("year", 60 * 60 * 24 * 365),
51+
("month", 60 * 60 * 24 * 30),
52+
("day", 60 * 60 * 24),
53+
("hour", 60 * 60),
54+
("min", 60),
55+
("sec", 1),
56+
)
57+
for name, interval_duration in intervals:
58+
if delta_secs < interval_duration:
59+
continue
60+
x = delta_secs // interval_duration
61+
plur = "s" if x > 1 else ""
62+
return f"{x} {name}{plur} ago"
63+
64+
return "now"
65+
66+
4467
class MeshInterface: # pylint: disable=R0902
4568
"""Interface class for meshtastic devices
4669
@@ -163,22 +186,7 @@ def getTimeAgo(ts) -> Optional[str]:
163186
delta_secs = int(delta.total_seconds())
164187
if delta_secs < 0:
165188
return None # not handling a timestamp from the future
166-
intervals = (
167-
("year", 60 * 60 * 24 * 365),
168-
("month", 60 * 60 * 24 * 30),
169-
("day", 60 * 60 * 24),
170-
("hour", 60 * 60),
171-
("min", 60),
172-
("sec", 1),
173-
)
174-
for name, interval_duration in intervals:
175-
if delta_secs < interval_duration:
176-
continue
177-
x = delta_secs // interval_duration
178-
plur = "s" if x > 1 else ""
179-
return f"{x} {name}{plur} ago"
180-
181-
return "now"
189+
return _timeago(delta_secs)
182190

183191
rows: List[Dict[str, Any]] = []
184192
if self.nodesByNum:

meshtastic/tests/test_mesh_interface.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import pytest
88

99
from .. import mesh_pb2, config_pb2, BROADCAST_ADDR, LOCAL_ADDR
10-
from ..mesh_interface import MeshInterface
10+
from ..mesh_interface import MeshInterface, _timeago
1111
from ..node import Node
1212

1313
# TODO
@@ -684,3 +684,14 @@ def test_waitConnected_isConnected_timeout(capsys):
684684
out, err = capsys.readouterr()
685685
assert re.search(r"warn about something", err, re.MULTILINE)
686686
assert out == ""
687+
688+
689+
@pytest.mark.unit
690+
def test_timeago():
691+
assert _timeago(0) == "now"
692+
assert _timeago(1) == "1 sec ago"
693+
assert _timeago(15) == "15 secs ago"
694+
assert _timeago(333) == "5 mins ago"
695+
assert _timeago(99999) == "1 day ago"
696+
assert _timeago(9999999) == "3 months ago"
697+
assert _timeago(-999) == "now"

0 commit comments

Comments
 (0)