github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/version/version_test.go (about)

     1  // Copyright (C) 2025 Grafana Labs.
     2  // SPDX-License-Identifier: AGPL-3.0-only
     3  
     4  package version
     5  
     6  import (
     7  	"runtime/debug"
     8  	"slices"
     9  	"sync"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  // TestAll validates that the various function are returning _something_.
    16  func TestAll(t *testing.T) {
    17  	t.Parallel()
    18  
    19  	const (
    20  		versionValue  = "(devel)"
    21  		revisionValue = "test-revision"
    22  		timeValue     = "test-time"
    23  	)
    24  
    25  	// Override the getBuildInfo variable to ensure that we can test the
    26  	// functions without having to rely on the actual build information.
    27  	//
    28  	// Before Go 1.24, test binaries would get their buildinfo populated in
    29  	// the same way as regular packages. Starting with 1.24, that
    30  	// information is no longer available, so the only possible test is to
    31  	// ensure that the functions return _something_. This is basically
    32  	// another instance of Hyrum's Law.
    33  	//
    34  	// Note that instead of simply returning a fixed value for the
    35  	// buildinfo, this modifies the actual value returned by
    36  	// debug.ReadBuildInfo. In this way if the behavior changes again, e.g.
    37  	// it starts to return a value when running as part of a test, the test
    38  	// will fail and we can decide what to do with that.
    39  	//
    40  	// See https://github.com/golang/go/issues/33976, sort of.
    41  	getBuildInfo = sync.OnceValue(func() *debug.BuildInfo {
    42  		bi, ok := debug.ReadBuildInfo()
    43  		if !ok {
    44  			return nil
    45  		}
    46  
    47  		slices.SortFunc(bi.Settings, cmpBuildSettings)
    48  
    49  		if _, found := slices.BinarySearchFunc(bi.Settings, revisionKey, isKey); !found {
    50  			bi.Settings = append(bi.Settings, debug.BuildSetting{Key: revisionKey, Value: revisionValue})
    51  		}
    52  
    53  		if _, found := slices.BinarySearchFunc(bi.Settings, timeKey, isKey); !found {
    54  			bi.Settings = append(bi.Settings, debug.BuildSetting{Key: timeKey, Value: timeValue})
    55  		}
    56  
    57  		slices.SortFunc(bi.Settings, cmpBuildSettings)
    58  
    59  		return bi
    60  	})
    61  
    62  	require.Equal(t, versionValue, Short())
    63  	require.Equal(t, revisionValue, Commit())
    64  	require.Equal(t, timeValue, Buildstamp())
    65  	require.NotEmpty(t, UserAgent())
    66  }