Fixing TestQueries/Delete flaky tests. (#15838)

When deleting queries, associated query stats and aggregated stats are
deleted with separate SQL statements. When testing, we need to wait in a
for loop for both of these to be deleted before continuing with the
test.
This commit is contained in:
Victor Lyuboslavsky 2023-12-27 15:22:18 -06:00 committed by GitHub
parent d4a99f164c
commit 289eb271a6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -3,6 +3,7 @@ package mysql
import (
"context"
"database/sql"
"errors"
"fmt"
"math"
"math/rand"
@ -205,18 +206,20 @@ func testQueriesDelete(t *testing.T, ds *Datastore) {
stats, err := ds.GetLiveQueryStats(context.Background(), query.ID, []uint{hostID})
require.NoError(t, err)
if len(stats) == 0 {
statsGone <- true
break
_, err = GetAggregatedStats(context.Background(), ds, fleet.AggregatedStatsTypeScheduledQuery, query.ID)
if errors.Is(err, sql.ErrNoRows) {
statsGone <- true
break
}
}
}
}()
select {
case <-statsGone:
case <-time.After(2 * time.Second):
case <-time.After(10 * time.Second):
t.Error("Timeout: stats not deleted for testQueriesDelete")
}
_, err = GetAggregatedStats(context.Background(), ds, fleet.AggregatedStatsTypeScheduledQuery, query.ID)
require.ErrorIs(t, err, sql.ErrNoRows)
}
func testQueriesGetByName(t *testing.T, ds *Datastore) {
@ -311,21 +314,22 @@ func testQueriesDeleteMany(t *testing.T, ds *Datastore) {
stats, err := ds.GetLiveQueryStats(context.Background(), q1.ID, hostIDs)
require.NoError(t, err)
if len(stats) == 0 {
statsGone <- true
break
_, err = GetAggregatedStats(context.Background(), ds, fleet.AggregatedStatsTypeScheduledQuery, q1.ID)
if errors.Is(err, sql.ErrNoRows) {
statsGone <- true
break
}
}
}
}()
select {
case <-statsGone:
case <-time.After(2 * time.Second):
case <-time.After(10 * time.Second):
t.Error("Timeout: stats not deleted for testQueriesDeleteMany")
}
stats, err := ds.GetLiveQueryStats(context.Background(), q3.ID, hostIDs)
require.NoError(t, err)
require.Equal(t, 0, len(stats))
_, err = GetAggregatedStats(context.Background(), ds, fleet.AggregatedStatsTypeScheduledQuery, q1.ID)
require.ErrorIs(t, err, sql.ErrNoRows)
_, err = GetAggregatedStats(context.Background(), ds, fleet.AggregatedStatsTypeScheduledQuery, q3.ID)
require.ErrorIs(t, err, sql.ErrNoRows)
@ -389,7 +393,7 @@ func testQueriesSave(t *testing.T, ds *Datastore) {
require.Equal(t, "Zach", actual.AuthorName)
require.Equal(t, "zwass@fleet.co", actual.AuthorEmail)
// Now save again and delete stats.
// Now save again and delete old stats.
// First we create stats which will be deleted.
const hostID = 1
err = ds.UpdateLiveQueryStats(
@ -423,7 +427,7 @@ func testQueriesSave(t *testing.T, ds *Datastore) {
}()
select {
case <-aggStatsGone:
case <-time.After(2 * time.Second):
case <-time.After(10 * time.Second):
t.Error("Timeout: aggregated stats not deleted for query")
}
test.QueriesMatch(t, query, actual)