Skip to content

Commit c4970f4

Browse files
committed
fix #210: Initialize clock before using it in SensingBlocks
1 parent 841bbb8 commit c4970f4

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/blocks/sensingblocks.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
using namespace libscratchcpp;
1212

13-
IClock *SensingBlocks::clock = Clock::instance().get();
13+
IClock *SensingBlocks::clock = nullptr;
1414

1515
std::string SensingBlocks::name() const
1616
{
@@ -54,6 +54,9 @@ unsigned int SensingBlocks::resetTimer(VirtualMachine *vm)
5454

5555
unsigned int SensingBlocks::daysSince2000(VirtualMachine *vm)
5656
{
57+
if (!clock)
58+
clock = Clock::instance().get();
59+
5760
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(clock->currentSystemTime().time_since_epoch()).count();
5861
vm->addReturnValue(ms / 86400000.0 - 10957);
5962

test/blocks/sensing_blocks_test.cpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,15 +138,22 @@ TEST_F(SensingBlocksTest, DaysSince2000Impl)
138138

139139
VirtualMachine vm(nullptr, &m_engineMock, nullptr);
140140
vm.setFunctions(functions);
141+
vm.setBytecode(bytecode);
141142

142143
std::chrono::system_clock::time_point time(std::chrono::milliseconds(1011243120562)); // Jan 17 2002 04:52:00
143144
EXPECT_CALL(m_clockMock, currentSystemTime()).WillOnce(Return(time));
144145

146+
vm.run(); // Test with the default clock - shouldn't crash (see #210)
147+
148+
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
149+
ASSERT_EQ(vm.registerCount(), 1);
150+
ASSERT_EQ(std::round(vm.getInput(0, 1)->toDouble() * 100) / 100, std::round((ms / 86400000.0 - 10957) * 100) / 100);
151+
145152
SensingBlocks::clock = &m_clockMock;
146-
vm.setBytecode(bytecode);
153+
vm.reset();
147154
vm.run();
148-
SensingBlocks::clock = Clock::instance().get();
155+
SensingBlocks::clock = nullptr;
149156

150-
ASSERT_EQ(vm.registerCount(), 1);
157+
ASSERT_EQ(vm.registerCount(), 2); // TODO: Change this to 1 after task #215 is completed
151158
ASSERT_EQ(vm.getInput(0, 1)->toDouble(), 747.20278428240817);
152159
}

0 commit comments

Comments
 (0)