(t *testing.T)
| 17 | ) |
| 18 | |
| 19 | func TestAuditService(t *testing.T) { |
| 20 | buf := new(bytes.Buffer) |
| 21 | evLogger := events.NewLogger() |
| 22 | ctx, cancel := context.WithCancel(context.Background()) |
| 23 | go evLogger.Serve(ctx) |
| 24 | defer cancel() |
| 25 | sub := evLogger.Subscribe(events.AllEvents) |
| 26 | defer sub.Unsubscribe() |
| 27 | |
| 28 | // Event sent before start, will not be logged |
| 29 | evLogger.Log(events.ConfigSaved, "the first event") |
| 30 | // Make sure the event goes through before creating the service |
| 31 | <-sub.C() |
| 32 | |
| 33 | auditCtx, auditCancel := context.WithCancel(context.Background()) |
| 34 | service := newAuditService(buf, evLogger) |
| 35 | done := make(chan struct{}) |
| 36 | go func() { |
| 37 | service.Serve(auditCtx) |
| 38 | close(done) |
| 39 | }() |
| 40 | |
| 41 | // Subscription needs to happen in service.Serve |
| 42 | time.Sleep(10 * time.Millisecond) |
| 43 | |
| 44 | // Event that should end up in the audit log |
| 45 | evLogger.Log(events.ConfigSaved, "the second event") |
| 46 | |
| 47 | // We need to give the events time to arrive, since the channels are buffered etc. |
| 48 | time.Sleep(10 * time.Millisecond) |
| 49 | |
| 50 | auditCancel() |
| 51 | <-done |
| 52 | |
| 53 | // This event should not be logged, since we have stopped. |
| 54 | evLogger.Log(events.ConfigSaved, "the third event") |
| 55 | |
| 56 | result := buf.String() |
| 57 | t.Log(result) |
| 58 | |
| 59 | if strings.Contains(result, "first event") { |
| 60 | t.Error("Unexpected first event") |
| 61 | } |
| 62 | |
| 63 | if !strings.Contains(result, "second event") { |
| 64 | t.Error("Missing second event") |
| 65 | } |
| 66 | |
| 67 | if strings.Contains(result, "third event") { |
| 68 | t.Error("Missing third event") |
| 69 | } |
| 70 | } |
nothing calls this directly
no test coverage detected