@@ -373,11 +373,7 @@ func TestAgentStats(t *testing.T) {
373
373
registry := prometheus .NewRegistry ()
374
374
375
375
// 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
381
377
var i int64
382
378
for i = 0 ; i < 3 ; i ++ {
383
379
_ , err = agent1 .PostStats (context .Background (), & agentsdk.Stats {
@@ -405,19 +401,22 @@ func TestAgentStats(t *testing.T) {
405
401
require .NoError (t , err )
406
402
}
407
403
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
+
408
412
// then
409
413
goldenFile , err := os .ReadFile ("testdata/agent-stats.json" )
410
414
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
- }
417
415
418
416
collected := map [string ]int {}
417
+ var out []byte
419
418
var executionSeconds bool
420
- require .Eventually (t , func () bool {
419
+ assert .Eventually (t , func () bool {
421
420
metrics , err := registry .Gather ()
422
421
assert .NoError (t , err )
423
422
@@ -445,8 +444,15 @@ func TestAgentStats(t *testing.T) {
445
444
require .FailNowf (t , "unexpected metric collected" , "metric: %s" , metric .GetName ())
446
445
}
447
446
}
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 ))
450
456
}
451
457
452
458
func prepareWorkspaceAndAgent (t * testing.T , client * codersdk.Client , user codersdk.CreateFirstUserResponse , workspaceNum int ) (* agentsdk.Client , codersdk.Workspace ) {
0 commit comments