[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: New to go packaging. Need help with a test that has hard coded date value...



Hi Scarlett,

Welcome to the team!

On 20.02.23 11:16, Scarlett Moore wrote:
func TestTitleHeading(t *testing.T) {
    doc := NewDocument()
    doc.Heading(1, "Title", "A short description", time.Now())

    if doc.String() != `.TH TITLE 1 "2022-01-11" "Title" "A short description"` {
        t.Error("Expected title heading, got:", doc.String())

Obviously, the test fails as the date there is today. So patching the test with todays date passes it, but this is a maintenance nightmare. Is there a better way?

Since you are in control of the time.Time that is passed to doc.Heading(), I think the simplest approach would be to replace the time.Now() param with a static timestamp, e.g.:

doc.Heading(1, "Title", "A short description", time.Date(2022, 1, 11, 0, 0, 0, 0, time.UTC))

It's curious that upstream (https://github.com/muesli/roff) would publish code containing such a test, as it would only have passed on that particular day. Or perhaps they run tests in a VM which has its clock set to that date prior to running the tests...? In any case, such a test would be worth forwarding upstream, since a vanilla checkout of that code is obviously never (again) going to pass tests successfully in its current state.

I have seen trickier cases where the time.Now() call is _inside_ the function being tested, which necessitates overriding the time.Now() function with a mock variant, designed to return a specific timestamp when called.

HTH.

Attachment: OpenPGP_signature
Description: OpenPGP digital signature


Reply to: