diff --git a/netTime/timeNow.go b/netTime/timeNow.go new file mode 100644 index 0000000000000000000000000000000000000000..a024cc7ffa7c9c7344cdd7497fba8d56a9a76966 --- /dev/null +++ b/netTime/timeNow.go @@ -0,0 +1,20 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright © 2020 xx network SEZC // +// // +// Use of this source code is governed by a license that can be found in the // +// LICENSE file // +/////////////////////////////////////////////////////////////////////////////// + +// Package netTime provides a custom time function that should provide the +// current accurate time used by the network from a custom time service. +package netTime + +import ( + "time" +) + +type NowFunc func() time.Time + +// Now returns the current accurate time. The function must be set an accurate +// time service that returns the current time with an accuracy of +/- 300 ms. +var Now NowFunc = time.Now diff --git a/netTime/timeNow_test.go b/netTime/timeNow_test.go new file mode 100644 index 0000000000000000000000000000000000000000..6c648569cf158dcc2d32e65d75c4bbae8a9a60c7 --- /dev/null +++ b/netTime/timeNow_test.go @@ -0,0 +1,40 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright © 2020 xx network SEZC // +// // +// Use of this source code is governed by a license that can be found in the // +// LICENSE file // +/////////////////////////////////////////////////////////////////////////////// + +package netTime + +import ( + "testing" + "time" +) + +// Happy path: tests that Now() returns time.Now() if it is unset. +func TestNow(t *testing.T) { + expectedTime := time.Now().Round(time.Millisecond) + receivedTime := Now().Round(time.Millisecond) + + if !expectedTime.Equal(receivedTime) { + t.Errorf("Returned incorrect time.\nexpected: %s\nreceived: %s", + expectedTime, receivedTime) + } +} + +// Happy path: tests that setting Now works. +func TestNow_Set(t *testing.T) { + expectedTime := time.Now() + testNow := func() time.Time { + return expectedTime + } + + Now = testNow + + now := Now() + if !Now().Equal(expectedTime) { + t.Errorf("Returned incorrect time.\nexpected: %s\nreceived: %s", + expectedTime, now) + } +}