Re: [go-nuts] Mocking out time.Now "globally"

6,738 views
Skip to first unread message

David Symonds

unread,
Dec 28, 2012, 12:47:07 AM12/28/12
to Holger Rapp, golan...@googlegroups.com
On Thu, Dec 27, 2012 at 9:41 PM, Holger Rapp <sir...@gmx.de> wrote:

> So here is my problem: I can provide an interface to my own code that I can
> mock out and that handles time stuff, but how can I mock out e.g. time.After
> or time.Now, so that the timeout code in net.Conn also works with my
> synthetic time?

You can't mock out time.Now and friends; they are functions. You can,
however, define your own interface, like

type Clock interface {
Now() time.Time
After(d time.Duration) <-chan time.Time
}

and provide a concrete implementation

type realClock struct{}
func (realClock) Now() time.Time { return time.Now() }
func (realClock) After(d time.Duration) <-chan time.Time { return
time.After(d) }

and a testing implementation.

Holger Rapp

unread,
Dec 28, 2012, 6:47:35 AM12/28/12
to golan...@googlegroups.com, Holger Rapp
Thanks for the answer.


On Friday, December 28, 2012 6:47:07 AM UTC+1, David Symonds wrote:
On Thu, Dec 27, 2012 at 9:41 PM, Holger Rapp <sir...@gmx.de> wrote:

> So here is my problem: I can provide an interface to my own code that I can
> mock out and that handles time stuff, but how can I mock out e.g. time.After
> or time.Now, so that the timeout code in net.Conn also works with my
> synthetic time?

You can't mock out time.Now and friends; they are functions. You can,
however, define your own interface, like
I understand that. But this won't help me as net.Conn.Read still times out after real seconds because I cannot control this code. And as far as I understand I cannot inject my interface into net somehow, right?

So I think I try to write everything using channels then - I can then control better when and how time is sampled. Is there a io.Reader -> channel construct somewhere in the standard library?

Kyle Lemons

unread,
Dec 29, 2012, 3:38:32 AM12/29/12
to Holger Rapp, golang-nuts
net.Conn is an interface as well.  You can provide your own implementation, possibly leveraging net.Pipe or iotest.TimeoutReader.


--
 
 

Holger Rapp

unread,
Dec 30, 2012, 2:05:33 PM12/30/12
to golan...@googlegroups.com, Holger Rapp
Thanks, I actually went that route and did exactly as you suggested.
Reply all
Reply to author
Forward
0 new messages