How to test the current time with Go (I made a very thin library)

What kind of article?

I wondered what to do with Golang for tests involving the current time. I didn't get it right, so I made a library with only the functions I wanted.

What I checked

@ tomtwinkle's article: [Golang] Create a testable current time acquisition process introduced the following three methods.

In addition, Kentaro Kawano's material was also helpful.

But, I hope it's easier like this. .. ..

What I made

I thought, I made a very thin library. https://github.com/bubusuke/xtime

Thoughts

It's the same as trying to do flextime and clock. You can wrap and replace time.Now (). But these two weren't quite right for me.

flextime is a little worrisome because it is exclusively controlled. (Also described in this article) Also, flextime has a long name (I want to shorten the coding). clock is a little worrisome because the name is too different from time.

Feature

Name: Time-like, but let's make it a short name. → xtime Function: Aperture! → Only two. Just use xtime.Now (). ~~ At the time of testing, just change the time with xtime.Mock (value returned by $ {xtime.Now ()}). ~~ At the time of testing, just change the time with xtime.Mock (function executed by $ {xtime.Now ()}). How to use: You can use it by replacing the part that uses time.Now () in the existing source with this.

git is open to the public, but the source is also posted below.


Source

xtime.go


package xtime

import (
	"time"
)

var now func() time.Time = time.Now

// Mock overwrites return value of xtime.Now().
// You must not use this function except for in test.
func Mock(fn func() time.Time) {
	now = fn
}

// Now returns the value of time.Now().
// If the Mock function has been executed in advance, the value set by Mock is returned.
func Now() time.Time {
	return now()
}


test

xtime_test.go


package xtime_test

import (
	"testing"
	"time"
	"xtime"
)

type incrementalMock struct {
	i time.Duration
	t time.Time
}

func (m *incrementalMock) Now() time.Time {
	m.i++
	return m.t.Add(time.Second * m.i)
}

func TestNow(t *testing.T) {
	// case 1.
	// Default xtime.Now behavior
	// 'xtime.Now() == time.Now()' become false due to the μ second level execution time difference.
	if !(xtime.Now().Sub(time.Now()) <= time.Second*1) {
		t.Error("Default xtime.Now() must be same to time.Now().")
	}

	// case 2.
	// Constant value Mock
	mockTime := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)
	xtime.Mock(func() time.Time { return mockTime })
	if xtime.Now() != mockTime {
		t.Error("xtime.Now() must be same to MockTime.")
	}

	// case 3.
	// Incremental value Mock
	incMock := &incrementalMock{
		i: 0,
		t: mockTime,
	}
	xtime.Mock(incMock.Now)
	if xtime.Now().Sub(mockTime) != time.Second*1 {
		t.Error("xtime.Now() must be same to MockTime+1sec.")
	}
	if xtime.Now().Sub(mockTime) != time.Second*2 {
		t.Error("xtime.Now() must be same to MockTime+2sec.")
	}

	// case 4.
	// reset
	xtime.Mock(time.Now)
	// Same to 1st test case.
	if !(xtime.Now().Sub(time.Now()) <= time.Second*1) {
		t.Error("Default xtime.Now() must be same to time.Now().")
	}

}

Recommended Posts

How to test the current time with Go (I made a very thin library)
I made a package to filter time series with python
How to unit test a function containing the current time using freezegun in python
I made a library to easily read config files with Python
[Django] I made a field to enter the date with 4 digit numbers
I made a library konoha that switches the tokenizer to a nice feeling
I made a tool to estimate the execution time of cron (+ PyPI debut)
I made a library to separate Japanese sentences nicely
How to create a submenu with the [Blender] plugin
I made a vim learning game "PacVim" with Go
I made a command to markdown the table clipboard
I made a python library to do rolling rank
I wrote you to watch the signal with Go
How to deploy a web app made with Flask to Heroku
I tried to simulate how the infection spreads with Python
I made a LINE BOT that returns parrots with Go
I made a function to check the model of DCGAN
To write a test in Go, first design the interface
I want to create a Dockerfile for the time being.
How to write offline real time I tried to solve the problem of F02 with Python
I made a program to solve (hint) Saizeriya's spot the difference
I want to record the execution time and keep a log.
I tried to describe the traffic in real time with WebSocket
[Introduction to Python] How to split a character string with the split function
I made a web server with Raspberry Pi to watch anime
I created a Python library to call the LINE WORKS API
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
How to make a command to read the configuration file with pyramid
I made a fortune with Python.
I made a Twitter Bot with Go x Qiita API x Lambda
[Python] How to import the library
I made a function to check if the webhook is received in Lambda for the time being
I made a library that adds docstring to a Python stub file.
I made a command to display a colorful calendar in the terminal
I made a daemon with Python
How to send a request to the DMM (FANZA) API with python
I made a program that automatically calculates the zodiac with tkinter
I made a chatbot with Tensor2Tensor and this time it worked
I tried to make a mechanism of exclusive control with Go
I started to work at different times, so I made a bot that tells me the time to leave
[Python] Explains how to use the range function with a concrete example
How to write offline real time I tried to solve E11 with python
How to get the date and time difference in seconds with python
I made a kitchen timer to be displayed on the status bar!
Setting to debug test by entering the contents of the library with pytest
How to fix the initial population with a genetic algorithm using DEAP
[Introduction to Python] How to write a character string with the format function
I made a GAN with Keras, so I made a video of the learning process.
I installed the library with Visual Studio Code, but Unable to import
I made a tool to convert Jupyter py to ipynb with VS Code
I tried to visualize the model with the low-code machine learning library "PyCaret"
I made a program to check the size of a file in Python
I made a mistake in fetching the hierarchy with MultiIndex of pandas
Python: I want to measure the processing time of a function neatly
How to write offline real time I tried to solve E12 with python
I made a function to see the movement of a two-dimensional array (Python)
How to add a package with PyCharm
How to set the server time to Japanese time
I made a character counter with Python
How to do portmanteau test with python
I made a script to display emoji