Should we introduce a wrapper around the time() function to support testing

Should we introduce a wrapper around the time() function to support testing

by Tim Hunt -
Number of replies: 1
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

At the moment, it is quite hard to test time-related functionality in Moodle. For example, in the OU's course format, it hilights the current week, and we want to Behat test that.

One work around is to make your test set-up use relative dates/times. E.g. something like

And the "C100" course start date is "2 weeks ago"

However, a better idea (See e.g. Time section in https://martinfowler.com/articles/nonDeterminism.html) is to put a wrapper around the system clock. So that, instead of calling the PHP time() function directly, you call something like core_time::get(), which, outside test scenarios, just calls time(). Then you can have a Behat step like

And the OU study planner thinks the date is "2018-02-08"
and an equivalent API for PHP unit.

We have doen this in OU code, but we were wondering if we should put this into Moodle core.

Of course, it would be a large change, but one that could mostly be done with search-and-replace, to change time() -> core_time::get() everywhere. Then, we could add a CodeChecker rule, to help ensure that all new code used core_time::get().

Anyway, what do people think?

Average of ratings: Useful (1)
In reply to Tim Hunt

Re: Should we introduce a wrapper around the time() function to support testing

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Dan P reminded me that the relative date thing was already done in Moodle: MDL-55522 for details.