Merge pull request #9630 from silverstripe-terraformers/feature/with-time

NEW: WithMockTime callback.
This commit is contained in:
Sam Minnée 2020-08-07 10:16:30 +12:00 committed by GitHub
commit 8195bb480d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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', '');