| 1 |
"""Tests clock timing between frames and estimations |
| 2 |
of frames per second. |
| 3 |
""" |
| 4 |
import time |
| 5 |
import pytest |
| 6 |
|
| 7 |
from pyglet import clock |
| 8 |
|
| 9 |
from ..annotations import skip_if_continuous_integration |
| 10 |
|
| 11 |
|
| 12 |
def sleep(seconds): |
| 13 |
"""Busy sleep on the CPU which is very precise""" |
| 14 |
start = time.perf_counter() |
| 15 |
while time.perf_counter() - start < seconds: |
| 16 |
pass |
| 17 |
|
| 18 |
|
| 19 |
@pytest.fixture |
| 20 |
def newclock(): |
| 21 |
clock.set_default(clock.Clock()) |
| 22 |
yield clock |
| 23 |
|
| 24 |
|
| 25 |
def test_first_tick_is_delta_zero(newclock): |
| 26 |
""" |
| 27 |
Tests that the first tick is dt = 0. |
| 28 |
""" |
| 29 |
dt = newclock.tick() |
| 30 |
assert dt == 0 |
| 31 |
|
| 32 |
|
| 33 |
def test_start_at_zero_fps(newclock): |
| 34 |
""" |
| 35 |
Tests that the default clock starts |
| 36 |
with zero fps. |
| 37 |
""" |
| 38 |
fps = newclock.get_frequency() |
| 39 |
assert fps == 0 |
| 40 |
|
| 41 |
|
| 42 |
@skip_if_continuous_integration() |
| 43 |
def test_elapsed_time_between_tick(): |
| 44 |
""" |
| 45 |
Test that the tick function returns the correct elapsed |
| 46 |
time between frames, in seconds. |
| 47 |
|
| 48 |
Because we are measuring time differences, we |
| 49 |
expect a small error (1%) from the expected value. |
| 50 |
""" |
| 51 |
sleep_time = 0.2 |
| 52 |
|
| 53 |
|
| 54 |
clock.tick() |
| 55 |
|
| 56 |
|
| 57 |
sleep(sleep_time) |
| 58 |
delta_time_1 = clock.tick() |
| 59 |
|
| 60 |
|
| 61 |
sleep(sleep_time) |
| 62 |
delta_time_2 = clock.tick() |
| 63 |
|
| 64 |
assert delta_time_1 == pytest.approx(sleep_time, rel=0.01*sleep_time) |
| 65 |
assert delta_time_2 == pytest.approx(sleep_time, rel=0.01*sleep_time) |
| 66 |
|
| 67 |
|
| 68 |
@skip_if_continuous_integration() |
| 69 |
def test_compute_fps(): |
| 70 |
""" |
| 71 |
Test that the clock computes a reasonable value of |
| 72 |
frames per second when simulated for 120 ticks at 60 frames per second. |
| 73 |
|
| 74 |
Because sleep is not very precise and fps are unbounded, we |
| 75 |
expect a moderate error (10%) from the expected value. |
| 76 |
""" |
| 77 |
ticks = 120 |
| 78 |
expected_fps = 60 |
| 79 |
seconds_per_tick = 1./expected_fps |
| 80 |
|
| 81 |
for i in range(ticks): |
| 82 |
time.sleep(seconds_per_tick) |
| 83 |
clock.tick() |
| 84 |
computed_fps = clock.get_frequency() |
| 85 |
|
| 86 |
assert computed_fps == pytest.approx(expected_fps, rel=0.1*expected_fps) |