Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7878167

Browse files
committed
fix tests
1 parent 28f7a13 commit 7878167

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

coderd/prometheusmetrics/prometheusmetrics_test.go

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -373,11 +373,7 @@ func TestAgentStats(t *testing.T) {
373373
registry := prometheus.NewRegistry()
374374

375375
// given
376-
cancel, err := prometheusmetrics.AgentStats(context.Background(), slogtest.Make(t, nil), registry, db, time.Now(), time.Second)
377-
require.NoError(t, err)
378-
t.Cleanup(cancel)
379-
380-
// when
376+
var err error
381377
var i int64
382378
for i = 0; i < 3; i++ {
383379
_, err = agent1.PostStats(context.Background(), &agentsdk.Stats{
@@ -405,19 +401,22 @@ func TestAgentStats(t *testing.T) {
405401
require.NoError(t, err)
406402
}
407403

404+
// when
405+
//
406+
// Set initialCreateAfter to some time in the past, so that AgentStats would include all above PostStats,
407+
// and it doesn't depend on the real time.
408+
cancel, err := prometheusmetrics.AgentStats(context.Background(), slogtest.Make(t, nil), registry, db, time.Now().Add(-time.Minute), time.Millisecond)
409+
require.NoError(t, err)
410+
t.Cleanup(cancel)
411+
408412
// then
409413
goldenFile, err := os.ReadFile("testdata/agent-stats.json")
410414
require.NoError(t, err)
411-
areMetricsValid := func(collected map[string]int) bool {
412-
out, err := json.MarshalIndent(collected, " ", " ")
413-
require.NoError(t, err)
414-
os.WriteFile("testdata/agent-stats.json", out, 0644)
415-
return string(goldenFile) == string(out)
416-
}
417415

418416
collected := map[string]int{}
417+
var out []byte
419418
var executionSeconds bool
420-
require.Eventually(t, func() bool {
419+
assert.Eventually(t, func() bool {
421420
metrics, err := registry.Gather()
422421
assert.NoError(t, err)
423422

@@ -445,8 +444,15 @@ func TestAgentStats(t *testing.T) {
445444
require.FailNowf(t, "unexpected metric collected", "metric: %s", metric.GetName())
446445
}
447446
}
448-
return executionSeconds && areMetricsValid(collected)
449-
}, testutil.WaitLong, testutil.IntervalMedium)
447+
448+
out, err = json.MarshalIndent(collected, " ", " ")
449+
require.NoError(t, err)
450+
451+
return executionSeconds && string(goldenFile) == string(out)
452+
}, testutil.WaitShort, testutil.IntervalFast)
453+
454+
// Keep this assertion, so that "go test" can print differences instead of "Condition never satisfied"
455+
assert.Equal(t, string(goldenFile), string(out))
450456
}
451457

452458
func prepareWorkspaceAndAgent(t *testing.T, client *codersdk.Client, user codersdk.CreateFirstUserResponse, workspaceNum int) (*agentsdk.Client, codersdk.Workspace) {

0 commit comments

Comments
 (0)