Skip to content

Commit

Permalink
Add rendering of the remaining time
Browse files Browse the repository at this point in the history
  • Loading branch information
vaclav-2012 committed May 30, 2020
1 parent 151fbfa commit 613bd3d
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ We follow [Semantic Versions](https://semver.org/).

- Add class `Timer` - responsible for waiting until the scheduled time
- Add the `Timer` to the `App`
- Add rendering of the remaining time during the countdown


## Version 0.1.2
Expand Down
18 changes: 18 additions & 0 deletions slow_start_rewatch/timer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-

import math
import time
from datetime import datetime
from typing import Iterator, Optional
Expand Down Expand Up @@ -64,6 +65,9 @@ def countdown(self) -> None:
self.ticks(),
label="Waiting to submit the post (press Ctrl+C to quit):",
fill_char=click.style("#", fg="bright_magenta"),
item_show_func=self.time_left,
show_eta=False,
show_percent=False,
) as progressbar:
for tick in progressbar:
current_timestamp = datetime.now().timestamp() * 1000
Expand Down Expand Up @@ -94,3 +98,17 @@ def ticks(self) -> Iterator[int]:
start_timestamp,
-self.refresh_interval,
))

def time_left(self, tick: Optional[int]) -> str:
"""Render remaining time."""
if self.target_time is None:
raise AttributeError(
"'target_time' must be set to render remaning time.",
)

if tick is None:
return ""

current_timestamp = datetime.fromtimestamp(math.floor(tick / 1000))

return str(self.target_time - current_timestamp)
29 changes: 29 additions & 0 deletions tests/test_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,35 @@ def test_ticks(timer_config):
assert generated_ticks == expected_ticks


@pytest.mark.parametrize(("tick_datetime", "expected_time_left"), [
(datetime(2018, 1, 6, 10, 59, 59, 100 * 1000), "1:00:01"),
(datetime(2018, 1, 6, 11, 59, 59, 900 * 1000), "0:00:01"),
(datetime(2018, 1, 6, 12), "0:00:00"),
(None, ""),
],
)
def test_time_left(tick_datetime, expected_time_left, timer_config):
"""Test that the remaining time is rendered correctly."""
timer = Timer(
config=timer_config,
target_time=datetime(2018, 1, 6, 12, 0, 0),
)

tick = int(tick_datetime.timestamp() * 1000) if tick_datetime else None

time_left = timer.time_left(tick)

assert time_left == expected_time_left


def test_time_left_invalid_call(timer_config):
"""Test calling :meth:`Timer.time_left()` without required attributes."""
timer = Timer(timer_config)

with pytest.raises(AttributeError):
timer.time_left(1000)


@pytest.fixture()
def timer_config():
"""Return mock Config for testing Timer."""
Expand Down

0 comments on commit 613bd3d

Please sign in to comment.