testingflaskpytestapscheduler

Testing Scheduled Tasks in Python/Flask


I'm building a small Flask app the runs a job every so often, say once a month. I'm using apschduler for this. Is there a way to set up a test for this? I'm using py.test.

Something like:

def test_cron(self, app):
    wait(months=1)
    assert cron_has_run

Any suggestions?


Solution

  • You shouldn't need to test that the job actually runs, since that is handled by apscheduler, which is already tested. Instead, test the task itself and test that you scheduled it as expected.

    You can inspect the scheduled jobs using get_jobs. If you want to test that you scheduled a job correctly, schedule it then find its job in the list. You can test if next_run_time is a month out, for example.

    for job in get_jobs():
        if name != 'name of job you care about':
            continue
    
        assert job.next_run_time >= datetime.utcnow() + timedelta(days=30)
        assert job.next_run_time <= datetime.utcnow() + timedelta(days=32)
    

    If you're interested in how apscheduler tests its scheduler, you can look at the code: https://github.com/agronholm/apscheduler/blob/master/tests/test_schedulers.py. It's using mocks and dates in the past.