syncthing/lib/syncthing/auditservice_test.go

71 lines
1.7 KiB
Go
Raw Normal View History

2015-04-25 11:21:47 +02:00
// Copyright (C) 2015 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
2015-04-25 11:21:47 +02:00
package syncthing
2015-04-25 11:21:47 +02:00
import (
"bytes"
2020-11-17 13:19:04 +01:00
"context"
2015-04-25 11:21:47 +02:00
"strings"
"testing"
"time"
2015-08-06 11:29:25 +02:00
"github.com/syncthing/syncthing/lib/events"
2015-04-25 11:21:47 +02:00
)
func TestAuditService(t *testing.T) {
buf := new(bytes.Buffer)
evLogger := events.NewLogger()
2020-11-17 13:19:04 +01:00
ctx, cancel := context.WithCancel(context.Background())
go evLogger.Serve(ctx)
defer cancel()
sub := evLogger.Subscribe(events.AllEvents)
defer sub.Unsubscribe()
// Event sent before start, will not be logged
evLogger.Log(events.ConfigSaved, "the first event")
// Make sure the event goes through before creating the service
<-sub.C()
2020-11-17 13:19:04 +01:00
auditCtx, auditCancel := context.WithCancel(context.Background())
service := newAuditService(buf, evLogger)
2020-11-17 13:19:04 +01:00
done := make(chan struct{})
go func() {
service.Serve(auditCtx)
close(done)
}()
// Subscription needs to happen in service.Serve
time.Sleep(10 * time.Millisecond)
2015-04-25 11:21:47 +02:00
// Event that should end up in the audit log
evLogger.Log(events.ConfigSaved, "the second event")
2015-04-25 11:21:47 +02:00
// We need to give the events time to arrive, since the channels are buffered etc.
time.Sleep(10 * time.Millisecond)
2020-11-17 13:19:04 +01:00
auditCancel()
<-done
2015-04-25 11:21:47 +02:00
// This event should not be logged, since we have stopped.
evLogger.Log(events.ConfigSaved, "the third event")
2015-04-25 11:21:47 +02:00
result := buf.String()
2015-04-25 11:21:47 +02:00
t.Log(result)
if strings.Contains(result, "first event") {
t.Error("Unexpected first event")
}
if !strings.Contains(result, "second event") {
t.Error("Missing second event")
}
if strings.Contains(result, "third event") {
t.Error("Missing third event")
}
}