package dockerevents import ( "context" "io" "log/slog" "net" "net/http" "net/http/httptest" "path/filepath" "strings" "sync/atomic" "testing" "time" ) func quiet() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } func waitFor(t *testing.T, cond func() bool) { t.Helper() deadline := time.Now().Add(3 * time.Second) for time.Now().Before(deadline) { if cond() { return } time.Sleep(10 * time.Millisecond) } t.Fatal("условие не выполнено за отведённое время") } func TestTriggerOnEventsTCP(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/events" || !strings.Contains(r.URL.Query().Get("filters"), "container") { t.Errorf("url = %s", r.URL) } _, _ = w.Write([]byte(`{"Type":"container","Action":"start"}` + "\n" + `{"Type":"container","Action":"die"}` + "\n")) w.(http.Flusher).Flush() <-r.Context().Done() })) defer srv.Close() var n int32 w := New("tcp://"+strings.TrimPrefix(srv.URL, "http://"), quiet(), func() { atomic.AddInt32(&n, 1) }) ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { w.Run(ctx); close(done) }() waitFor(t, func() bool { return atomic.LoadInt32(&n) >= 2 }) cancel() <-done } func TestUnixSocketAndReconnect(t *testing.T) { sock := filepath.Join(t.TempDir(), "d.sock") l, err := net.Listen("unix", sock) if err != nil { t.Skipf("unix сокеты недоступны: %v", err) } var conns int32 srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { atomic.AddInt32(&conns, 1) _, _ = w.Write([]byte(`{"Type":"container","Action":"start"}` + "\n")) // поток закрывается сразу — ждём переподключения })} go srv.Serve(l) defer srv.Close() var n int32 w := New("unix://"+sock, quiet(), func() { atomic.AddInt32(&n, 1) }) w.minBackoff, w.maxBackoff = 10*time.Millisecond, 20*time.Millisecond ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { w.Run(ctx); close(done) }() waitFor(t, func() bool { return atomic.LoadInt32(&conns) >= 2 && atomic.LoadInt32(&n) >= 2 }) cancel() <-done } func TestUnavailableSocketDoesNotPanicOrExit(t *testing.T) { w := New("unix:///nonexistent/docker.sock", quiet(), func() { t.Error("trigger не ожидался") }) w.minBackoff, w.maxBackoff = 5*time.Millisecond, 10*time.Millisecond ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() done := make(chan struct{}) go func() { w.Run(ctx); close(done) }() select { case <-done: case <-time.After(2 * time.Second): t.Fatal("Run не завершился после отмены контекста") } } func TestInvalidHostScheme(t *testing.T) { w := New("ftp://x", quiet(), func() {}) if _, _, err := w.client(); err == nil { t.Fatal("ожидалась ошибка") } // Run на невалидном host возвращается сразу done := make(chan struct{}) go func() { w.Run(context.Background()); close(done) }() select { case <-done: case <-time.After(time.Second): t.Fatal("Run должен вернуться при невалидном host") } }