NEW: WithMockTime callback.

This commit is contained in:
Mojmir Fendek 2020-08-06 10:19:03 +12:00
parent a166ba0ebd
commit c2ed6a4cd6
2 changed files with 37 additions and 0 deletions

View File

@ -209,6 +209,27 @@ class DBDatetime extends DBDate implements TemplateGlobalProvider
self::$mock_now = null;
}
/**
* Run a callback with specific time, original mock value is retained after callback
*
* @param DBDatetime|string $time
* @param callable $callback
* @return mixed
* @throws Exception
*/
public static function withFixedNow($time, $callback)
{
$original = self::$mock_now;
try {
self::set_mock_now($time);
return $callback();
} finally {
self::$mock_now = $original;
}
}
public static function get_template_global_variables()
{
return [

View File

@ -42,6 +42,22 @@ class DBDatetimeTest extends SapphireTest
$this->assertEquals($systemDatetime->Date(), $nowDatetime->Date());
}
public function testFixedNow()
{
$mockDate1 = '2010-01-01 10:00:00';
$mockDate2 = '2011-01-01 10:00:00';
DBDatetime::withFixedNow($mockDate1, function () use ($mockDate1, $mockDate2) {
$this->assertEquals($mockDate1, DBDatetime::now()->Rfc2822());
DBDatetime::withFixedNow($mockDate2, function () use ($mockDate2) {
$this->assertEquals($mockDate2, DBDatetime::now()->Rfc2822());
});
$this->assertEquals($mockDate1, DBDatetime::now()->Rfc2822());
});
}
public function testSetNullAndZeroValues()
{
$date = DBDatetime::create_field('Datetime', '');