~james/core

core/spindle/observability/logging_test.go -rw-r--r-- 1.8 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package observability

import (
	"context"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"sync"
	"testing"
	"time"

	"tangled.org/core/spindle/config"
)

func TestInitLoggingDisabled(t *testing.T) {
	ctx := context.Background()
	cfg := config.Logging{
		Endpoint: "",
	}

	handler, shutdown, err := InitLogging(ctx, cfg)
	if err != nil {
		t.Fatalf("InitLogging returned error: %v", err)
	}
	if handler != nil {
		t.Error("expected handler to be nil when logging is disabled")
	}
	if shutdown == nil {
		t.Error("expected shutdown to be a no-op function, not nil")
	}
	if err := shutdown(ctx); err != nil {
		t.Errorf("no-op shutdown returned error: %v", err)
	}
}

func TestInitLoggingEnabled(t *testing.T) {
	var mu sync.Mutex
	var logReceived bool

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/otlp/v1/logs" {
			mu.Lock()
			logReceived = true
			mu.Unlock()
			w.WriteHeader(http.StatusOK)
		}
	}))
	defer server.Close()

	ctx := context.Background()
	endpoint := server.Listener.Addr().String()

	cfg := config.Logging{
		Endpoint:    endpoint,
		ServiceName: "spindle-test-service",
		Insecure:    true,
	}

	handler, shutdown, err := InitLogging(ctx, cfg)
	if err != nil {
		t.Fatalf("InitLogging returned error: %v", err)
	}
	if handler == nil {
		t.Fatal("expected handler to be non-nil when logging is enabled")
	}

	logger := slog.New(handler)
	logger.Info("hello from test log exporter")

	shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	if err := shutdown(shutdownCtx); err != nil {
		t.Errorf("shutdown returned error: %v", err)
	}

	mu.Lock()
	received := logReceived
	mu.Unlock()

	if !received {
		t.Error("expected mock collector to receive the log request on /otlp/v1/logs")
	}
}