MCPcopy Index your code
hub / github.com/coder/coder / TestCron

Function TestCron

enterprise/coderd/usage/cron_test.go:25–81  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

23)
24
25func TestCron(t *testing.T) {
26 t.Parallel()
27
28 t.Run("BasicTick", func(t *testing.T) {
29 t.Parallel()
30
31 ctx := testutil.Context(t, testutil.WaitLong)
32 ctrl := gomock.NewController(t)
33 db := dbmock.NewMockStore(ctrl)
34 clock := quartz.NewMock(t)
35
36 // The existence check should return false so the event gets
37 // inserted.
38 db.EXPECT().UsageEventExistsByID(gomock.Any(), gomock.Any()).
39 Return(false, nil).AnyTimes()
40
41 inserted := make(chan database.InsertUsageEventParams, 1)
42 db.EXPECT().InsertUsageEvent(gomock.Any(), gomock.Any()).
43 DoAndReturn(func(_ context.Context, params database.InsertUsageEventParams) error {
44 inserted <- params
45 return nil
46 }).AnyTimes()
47
48 inserter := usage.NewDBInserter(usage.InserterWithClock(clock))
49 cron := usage.NewCron(clock, slogtest.Make(t, nil), db, inserter)
50 require.NoError(t, cron.Register(usage.CronJob{
51 Name: "test-job",
52 Interval: 5 * time.Minute,
53 EventType: usagetypes.UsageEventTypeHBAISeatsV1,
54 Fn: func(_ context.Context) (usagetypes.HeartbeatEvent, error) {
55 return usagetypes.HBAISeats{Count: 42}, nil
56 },
57 }))
58
59 timerTrap := clock.Trap().NewTimer("test-job")
60
61 cron.Start(ctx)
62 defer cron.Close()
63 defer timerTrap.Close()
64
65 // Wait for timer creation, then fire it. The delay is the
66 // time until the next epoch-aligned boundary for the 5-minute
67 // interval — we don't assert the exact value since it depends
68 // on the mock clock's current time.
69 timerCall := timerTrap.MustWait(ctx)
70 timerCall.MustRelease(ctx)
71 clock.Advance(timerCall.Duration)
72
73 // Verify the event was inserted with an epoch-aligned ID.
74 select {
75 case params := <-inserted:
76 assert.Contains(t, params.ID, "hb_ai_seats_v1:")
77 case <-ctx.Done():
78 t.Fatal("timed out waiting for insert")
79 }
80 })
81}
82

Callers

nothing calls this directly

Calls 15

EXPECTMethod · 0.95
RegisterMethod · 0.95
StartMethod · 0.95
CloseMethod · 0.95
ContextFunction · 0.92
NewMockStoreFunction · 0.92
NewDBInserterFunction · 0.92
InserterWithClockFunction · 0.92
NewCronFunction · 0.92
FatalMethod · 0.80
RunMethod · 0.65
UsageEventExistsByIDMethod · 0.65

Tested by

no test coverage detected