apscheduler icon indicating copy to clipboard operation
apscheduler copied to clipboard

help: use the schedulers with simulated time for tests

Open liordon opened this issue 6 years ago • 4 comments

I want to use the apscheduler in a module I am developing but I don't understand how to make it run with a simulated clock. If I could run it in simulated time I could test periodic events and long waits without actually putthing the thread into long sleeps. Is there any possibility to create such a simulated scheduler? if not, how were the different scheduler modules tested?

Thanks in advance!

liordon avatar Mar 12 '18 18:03 liordon

This is not a Q&A forum, use stackoverflow or the mailinglist for that. Just a hint as to a possibility why there's been no response here..

kaos avatar Jun 25 '19 07:06 kaos

For testing purposes, you can run the jobs with a custom trigger, as it is the trigger that decides when it is time to run a particular job. If you base it on another trigger that you actually want to use, you can rely on its implementation, and simply tweak the output times to shrink the times as needed.

The different scheduler modules are tested in isolation, so triggers are tested with, "given these inputs, what are your outputs", no need to actually wait for those conditions to actually occur (they're date time in, date time out) while the executors are tested for how they execute a job, no need to "wait" for a condition to execute the job to occur. This is basic unit testing strategy.

Integration tests on the other hand, take the system as a whole and tests it. I haven't looked too close at the test suite to find if there are also integration tests.

kaos avatar Aug 13 '19 18:08 kaos

i have a related issue. i currently would want to write unit tests for scheduler's event listeners. to do so, i would need to invent a whole set of mock classes, b/c everything is so intertwined. and this is too much effort for my case where i'm fixing a c&p error. as an example this how a test could look like:

from apscheduler.events import EVENT_JOB_ERROR
from apscheduler.mocks import Job, JobExecutionEvent

from myapp import on_error


def _pass():
    pass


def test_scheduler_listener():
    job = Job(func=_pass)
    event = JobExecutionEvent(code=EVENT_JOB_ERROR, job=job)
    on_error(event)

my point is that i think a set of utilities to facilitate better testing would be a great addition to a great lib.

funkyfuture avatar Apr 04 '20 11:04 funkyfuture

You can use freezegun to advance the time

# Setup scheduler and add job with trigger in 5 seconds
ts_advance = datetime.now() + timedelta(seconds=5)
with freezegun.freeze_time(ts_advance, tick=True):
    await asyncio.sleep(0.2)
    # The job should now have been executed

bendikro avatar Apr 28 '20 11:04 bendikro

Closing as stale/QA.

agronholm avatar Aug 17 '22 22:08 agronholm