doc_manager_test.go
1package rtw
2
3import (
4 "testing"
5 "time"
6)
7
8func TestNewDocManager(t *testing.T) {
9 dm := NewDocManager("ws://localhost:8080", nil)
10 if dm == nil {
11 t.Fatal("NewDocManager returned nil")
12 }
13 if dm.targetURL != "ws://localhost:8080" {
14 t.Errorf("expected targetURL ws://localhost:8080, got %s", dm.targetURL)
15 }
16 if dm.sessions == nil {
17 t.Error("sessions map is nil")
18 }
19}
20
21func TestDocManagerClientConnect(t *testing.T) {
22 dm := NewDocManager("ws://localhost:8080", nil)
23
24 // Connect first client
25 dm.ClientConnect("doc1")
26
27 dm.mu.RLock()
28 session, exists := dm.sessions["doc1"]
29 dm.mu.RUnlock()
30
31 if !exists {
32 t.Fatal("session not created for doc1")
33 }
34
35 // Wait for goroutine to start
36 time.Sleep(100 * time.Millisecond)
37
38 // Check that session was initialized
39 if session.docID != "doc1" {
40 t.Errorf("expected docID doc1, got %s", session.docID)
41 }
42
43 // Clean up
44 dm.Shutdown()
45}
46
47func TestDocManagerMultipleClients(t *testing.T) {
48 dm := NewDocManager("ws://localhost:8080", nil)
49
50 // Connect multiple clients to same doc
51 dm.ClientConnect("doc2")
52 dm.ClientConnect("doc2")
53 dm.ClientConnect("doc2")
54
55 time.Sleep(100 * time.Millisecond)
56
57 dm.mu.RLock()
58 _ = dm.sessions["doc2"]
59 dm.mu.RUnlock()
60
61 // Disconnect one client
62 dm.ClientDisconnect("doc2")
63
64 time.Sleep(100 * time.Millisecond)
65
66 // Session should still exist
67 dm.mu.RLock()
68 _, exists := dm.sessions["doc2"]
69 dm.mu.RUnlock()
70
71 if !exists {
72 t.Error("session should still exist after one disconnect")
73 }
74
75 // Clean up
76 dm.Shutdown()
77}
78
79func TestDocManagerShutdown(t *testing.T) {
80 dm := NewDocManager("ws://localhost:8080", nil)
81
82 // Create a few sessions
83 dm.ClientConnect("doc3")
84 dm.ClientConnect("doc4")
85
86 time.Sleep(100 * time.Millisecond)
87
88 // Shutdown should clean up all sessions
89 dm.Shutdown()
90
91 // Verify all sessions are cleaned up
92 dm.mu.RLock()
93 count := len(dm.sessions)
94 dm.mu.RUnlock()
95
96 // Sessions remain in map but goroutines are stopped
97 if count != 2 {
98 t.Errorf("expected 2 sessions, got %d", count)
99 }
100}
101
102func TestDocManagerClientDisconnectUnknownDoc(t *testing.T) {
103 dm := NewDocManager("ws://localhost:8080", nil)
104
105 // Disconnect from unknown doc should not panic
106 dm.ClientDisconnect("unknown-doc")
107
108 // Clean up
109 dm.Shutdown()
110}