Skip to content

Commit

Permalink
pybind/mgr/mgr_util: fix to_pretty_timedelta
Browse files Browse the repository at this point in the history
- total_seconds, not seconds
- int, not float

Added unit tests.

Fixes: https://tracker.ceph.com/issues/53953
Signed-off-by: Sage Weil <[email protected]>
  • Loading branch information
liewegas committed Jan 20, 2022
1 parent 7112b9a commit 538aa10
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/pybind/mgr/mgr_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -768,18 +768,18 @@ def _pairwise(iterable: Iterable[T]) -> Generator[Tuple[Optional[T], T], None, N

def to_pretty_timedelta(n: datetime.timedelta) -> str:
if n < datetime.timedelta(seconds=120):
return str(n.seconds) + 's'
return str(int(n.total_seconds())) + 's'
if n < datetime.timedelta(minutes=120):
return str(n.seconds // 60) + 'm'
return str(int(n.total_seconds()) // 60) + 'm'
if n < datetime.timedelta(hours=48):
return str(n.seconds // 3600) + 'h'
return str(int(n.total_seconds()) // 3600) + 'h'
if n < datetime.timedelta(days=14):
return str(n.days) + 'd'
return str(int(n.total_seconds()) // (3600*24)) + 'd'
if n < datetime.timedelta(days=7*12):
return str(n.days // 7) + 'w'
return str(int(n.total_seconds()) // (3600*24*7)) + 'w'
if n < datetime.timedelta(days=365*2):
return str(n.days // 30) + 'M'
return str(n.days // 365) + 'y'
return str(int(n.total_seconds()) // (3600*24*30)) + 'M'
return str(int(n.total_seconds()) // (3600*24*365)) + 'y'


def profile_method(skip_attribute: bool = False) -> Callable[[Callable[..., T]], Callable[..., T]]:
Expand Down
19 changes: 19 additions & 0 deletions src/pybind/mgr/tests/test_mgr_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import datetime
import mgr_util

import pytest


@pytest.mark.parametrize(
"delta, out",
[
(datetime.timedelta(minutes=90), '90m'),
(datetime.timedelta(minutes=190), '3h'),
(datetime.timedelta(days=3), '3d'),
(datetime.timedelta(hours=3), '3h'),
(datetime.timedelta(days=365 * 3.1), '3y'),
(datetime.timedelta(minutes=90), '90m'),
]
)
def test_pretty_timedelta(delta: datetime.timedelta, out: str):
assert mgr_util.to_pretty_timedelta(delta) == out

0 comments on commit 538aa10

Please sign in to comment.