-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_collab.py
More file actions
1952 lines (1596 loc) · 82.2 KB
/
test_collab.py
File metadata and controls
1952 lines (1596 loc) · 82.2 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Comprehensive test suite for the Claude Code Collaboration Harness (collab.py).
Covers: utilities, signal files, file locking, state management,
all commands (nodes, messages, context, tasks, locks, poll, pending,
log, request, reset, whoami), and the CLI parser.
Run: python -m pytest test_collab.py -v
"""
import json
import os
import shutil
import sys
import tempfile
import time
from datetime import datetime, timezone, timedelta
from io import StringIO
from pathlib import Path
from unittest import mock
import pytest
# Ensure the project root is on the path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import collab
# ── Fixtures ─────────────────────────────────────────────────────
@pytest.fixture
def state_dir(tmp_path):
"""Create a fresh temporary state directory for each test."""
d = tmp_path / "state"
d.mkdir()
return d
@pytest.fixture
def state(state_dir):
"""Return a State instance backed by a temp directory."""
return collab.State(state_dir)
@pytest.fixture
def populated_state(state):
"""State with two registered nodes, a task, and a message."""
collab.cmd_join(state, "alice", "architect")
collab.cmd_join(state, "bob", "developer")
return state
@pytest.fixture
def capture_stdout():
"""Context-manager helper to capture stdout."""
class Capture:
def __enter__(self):
self.buf = StringIO()
self._patch = mock.patch("sys.stdout", self.buf)
self._patch.start()
return self
def __exit__(self, *exc):
self._patch.stop()
@property
def text(self):
return self.buf.getvalue()
return Capture
# ══════════════════════════════════════════════════════════════════
# UTILITY TESTS
# ══════════════════════════════════════════════════════════════════
class TestUtilities:
def test_utcnow_is_isoformat(self):
ts = collab.utcnow()
dt = datetime.fromisoformat(ts)
assert dt.tzinfo is not None # timezone-aware
def test_parse_ts_roundtrip(self):
ts = collab.utcnow()
dt = collab.parse_ts(ts)
assert isinstance(dt, datetime)
assert dt.tzinfo is not None
def test_ago_just_now(self):
ts = collab.utcnow()
result = collab.ago(ts)
assert result in ("just now", "0s ago", "1s ago", "2s ago")
def test_ago_minutes(self):
past = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()
result = collab.ago(past)
assert "m ago" in result
def test_ago_hours(self):
past = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()
result = collab.ago(past)
assert "h ago" in result
def test_ago_days(self):
past = (datetime.now(timezone.utc) - timedelta(days=2)).isoformat()
result = collab.ago(past)
assert "d ago" in result
def test_ago_bad_input(self):
result = collab.ago("not-a-timestamp")
assert result == "?"
def test_short_time_format(self):
ts = "2025-01-15T14:30:45+00:00"
result = collab.short_time(ts)
assert result == "14:30:45"
def test_short_time_bad_input(self):
result = collab.short_time("bad")
assert result == "??:??:??"
def test_trunc_short_string(self):
assert collab.trunc("hello", 10) == "hello"
def test_trunc_exact_length(self):
assert collab.trunc("12345", 5) == "12345"
def test_trunc_long_string(self):
result = collab.trunc("hello world, this is a long string", 15)
assert len(result) == 15
assert result.endswith("...")
def test_trunc_default_limit(self):
short = "x" * 60
assert collab.trunc(short) == short
long = "x" * 100
assert len(collab.trunc(long)) == 60
# ══════════════════════════════════════════════════════════════════
# SIGNAL FILE TESTS
# ══════════════════════════════════════════════════════════════════
class TestSignalFiles:
def test_signal_creates_file(self, state_dir):
collab.signal_node(state_dir, "alice", "test reason")
path = state_dir / "_signal_alice"
assert path.exists()
content = path.read_text(encoding="utf-8")
assert "test reason" in content
def test_signal_appends(self, state_dir):
collab.signal_node(state_dir, "alice", "reason1")
collab.signal_node(state_dir, "alice", "reason2")
content = (state_dir / "_signal_alice").read_text(encoding="utf-8")
assert "reason1" in content
assert "reason2" in content
def test_read_and_clear_signal(self, state_dir):
collab.signal_node(state_dir, "bob", "wake up")
lines = collab.read_and_clear_signal(state_dir, "bob")
assert len(lines) == 1
assert "wake up" in lines[0]
# File should be deleted
assert not (state_dir / "_signal_bob").exists()
def test_read_and_clear_no_signal(self, state_dir):
lines = collab.read_and_clear_signal(state_dir, "nobody")
assert lines == []
def test_signal_multiple_then_clear(self, state_dir):
for i in range(5):
collab.signal_node(state_dir, "alice", f"reason {i}")
lines = collab.read_and_clear_signal(state_dir, "alice")
assert len(lines) == 5
# ══════════════════════════════════════════════════════════════════
# FILE LOCK TESTS
# ══════════════════════════════════════════════════════════════════
class TestFileLock:
def test_lock_acquire_release(self, tmp_path):
target = tmp_path / "data.json"
target.write_text("{}")
lock = collab.FileLock(target)
with lock:
assert lock.lockpath.exists()
assert not lock.lockpath.exists()
def test_lock_stale_cleanup(self, tmp_path):
target = tmp_path / "data.json"
target.write_text("{}")
lock = collab.FileLock(target)
# Create a stale lock file manually
lock.lockpath.write_text("12345")
# Set mtime far in the past
old_time = time.time() - collab.STALE_LOCK_SEC - 5
os.utime(str(lock.lockpath), (old_time, old_time))
# Should succeed because the stale lock gets cleaned up
with lock:
pass
def test_lock_timeout(self, tmp_path):
target = tmp_path / "data.json"
target.write_text("{}")
lock = collab.FileLock(target)
# Create a fresh lock file (not stale)
lock.lockpath.write_text("99999")
# Temporarily reduce timeout
orig = collab.LOCK_TIMEOUT
collab.LOCK_TIMEOUT = 0.1
try:
with pytest.raises(TimeoutError):
with lock:
pass
finally:
collab.LOCK_TIMEOUT = orig
lock.lockpath.unlink(missing_ok=True)
# ══════════════════════════════════════════════════════════════════
# STATE MANAGER TESTS
# ══════════════════════════════════════════════════════════════════
class TestState:
def test_init_creates_default_files(self, state_dir):
s = collab.State(state_dir)
for name in collab._DEFAULTS:
assert (state_dir / f"{name}.json").exists()
def test_read_write_roundtrip(self, state):
state.write("context", {"key": "value"})
data = state.read("context")
assert data == {"key": "value"}
def test_update_atomicity(self, state):
state.write("nodes", {"a": 1})
def add_b(nodes):
nodes["b"] = 2
return "done"
result = state.update("nodes", add_b)
assert result == "done"
nodes = state.read("nodes")
assert nodes == {"a": 1, "b": 2}
def test_append_log(self, state):
state.append_log("alice", "test", "Alice did something")
log = state.read("log")
assert len(log) == 1
assert log[0]["actor"] == "alice"
assert log[0]["summary"] == "Alice did something"
def test_append_log_truncation(self, state):
orig = collab.LOG_MAX
collab.LOG_MAX = 5
try:
for i in range(10):
state.append_log("bot", "action", f"entry {i}")
log = state.read("log")
assert len(log) == 5
assert log[0]["summary"] == "entry 5" # oldest kept
finally:
collab.LOG_MAX = orig
def test_next_task_id_increments(self, state):
id1 = state.next_task_id()
id2 = state.next_task_id()
id3 = state.next_task_id()
assert id1 == 1
assert id2 == 2
assert id3 == 3
def test_read_corrupt_file_returns_default(self, state_dir):
s = collab.State(state_dir)
# Corrupt the nodes file
(state_dir / "nodes.json").write_text("NOT JSON!", encoding="utf-8")
data = s.read("nodes")
assert data == {} # default for nodes is {}
def test_state_creates_parent_dirs(self, tmp_path):
deep = tmp_path / "a" / "b" / "c" / "state"
s = collab.State(deep)
assert deep.exists()
def test_write_raw_atomic(self, state):
"""Ensure write uses tmp + rename pattern."""
path = state._path("nodes")
state.write("nodes", {"test": True})
# tmp file should not remain
assert not path.with_suffix(".tmp").exists()
assert state.read("nodes") == {"test": True}
# ══════════════════════════════════════════════════════════════════
# NODE COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestNodeCommands:
def test_join(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_join(state, "alice", "architect")
assert "[OK]" in cap.text
assert "alice" in cap.text
nodes = state.read("nodes")
assert "alice" in nodes
assert nodes["alice"]["role"] == "architect"
assert nodes["alice"]["status"] == "active"
def test_join_rejoin(self, state, capture_stdout):
collab.cmd_join(state, "alice", "architect")
with capture_stdout() as cap:
collab.cmd_join(state, "alice", "lead architect")
assert "Rejoined" in cap.text
nodes = state.read("nodes")
assert nodes["alice"]["role"] == "lead architect"
def test_leave(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_leave(populated_state, "alice")
assert "[OK]" in cap.text
nodes = populated_state.read("nodes")
assert "alice" not in nodes
def test_leave_releases_locks(self, populated_state, capture_stdout):
collab.cmd_lock(populated_state, "alice", "main.py")
with capture_stdout() as cap:
collab.cmd_leave(populated_state, "alice")
assert "Released 1 file lock" in cap.text
locks = populated_state.read("locks")
assert "main.py" not in locks
def test_leave_unknown_node(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_leave(state, "nobody")
assert "WARN" in cap.text
def test_heartbeat(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_heartbeat(populated_state, "alice",
working_on="refactoring", node_status="busy")
assert "[OK]" in cap.text
nodes = populated_state.read("nodes")
assert nodes["alice"]["working_on"] == "refactoring"
assert nodes["alice"]["status"] == "busy"
def test_heartbeat_unknown_node(self, state, capture_stdout):
with pytest.raises(SystemExit):
collab.cmd_heartbeat(state, "ghost")
# ══════════════════════════════════════════════════════════════════
# MESSAGE COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestMessageCommands:
def test_send(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_send(populated_state, "alice", "bob", "Hello Bob!")
assert "[OK]" in cap.text
messages = populated_state.read("messages")
assert len(messages) == 1
assert messages[0]["content"] == "Hello Bob!"
assert messages[0]["from"] == "alice"
assert messages[0]["to"] == "bob"
def test_send_signals_recipient(self, populated_state):
collab.cmd_send(populated_state, "alice", "bob", "Heads up!")
# Signal file should exist for bob
signals = collab.read_and_clear_signal(populated_state.dir, "bob")
assert any("alice" in s for s in signals)
def test_send_to_unknown_node(self, populated_state):
with pytest.raises(SystemExit):
collab.cmd_send(populated_state, "alice", "ghost", "Hi")
def test_broadcast(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_broadcast(populated_state, "alice", "Everyone listen!")
assert "[OK]" in cap.text
assert "1 other node" in cap.text
messages = populated_state.read("messages")
assert messages[-1]["to"] == "all"
assert messages[-1]["type"] == "broadcast"
def test_inbox_new_messages(self, populated_state, capture_stdout):
collab.cmd_send(populated_state, "alice", "bob", "Message 1")
collab.cmd_send(populated_state, "alice", "bob", "Message 2")
with capture_stdout() as cap:
collab.cmd_inbox(populated_state, "bob")
assert "Message 1" in cap.text
assert "Message 2" in cap.text
def test_inbox_no_messages(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_inbox(populated_state, "alice")
assert "No new messages" in cap.text
def test_inbox_all_flag(self, populated_state, capture_stdout):
collab.cmd_send(populated_state, "alice", "bob", "Old message")
# Advance bob's last_poll so the message is "old"
collab.cmd_poll(populated_state, "bob")
with capture_stdout() as cap:
collab.cmd_inbox(populated_state, "bob", show_all=True)
assert "Old message" in cap.text
def test_message_truncation(self, populated_state):
"""Messages list shouldn't exceed MSG_MAX."""
orig = collab.MSG_MAX
collab.MSG_MAX = 3
try:
for i in range(5):
collab.cmd_send(populated_state, "alice", "bob", f"msg {i}")
messages = populated_state.read("messages")
assert len(messages) == 3
finally:
collab.MSG_MAX = orig
# ══════════════════════════════════════════════════════════════════
# CONTEXT COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestContextCommands:
def test_context_set_and_get(self, state, capture_stdout):
collab.cmd_context_set(state, "db_type", "postgres", by="alice")
with capture_stdout() as cap:
collab.cmd_context_get(state, "db_type")
assert "postgres" in cap.text
assert "alice" in cap.text
def test_context_get_all(self, state, capture_stdout):
collab.cmd_context_set(state, "key1", "val1", by="a")
collab.cmd_context_set(state, "key2", "val2", by="b")
with capture_stdout() as cap:
collab.cmd_context_get(state)
assert "key1" in cap.text
assert "key2" in cap.text
def test_context_get_missing_key(self, state):
with pytest.raises(SystemExit):
collab.cmd_context_get(state, "nonexistent")
def test_context_get_empty(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_context_get(state)
assert "No shared context" in cap.text
def test_context_del(self, state, capture_stdout):
collab.cmd_context_set(state, "temp", "value", by="alice")
with capture_stdout() as cap:
collab.cmd_context_del(state, "temp")
assert "[OK]" in cap.text
ctx = state.read("context")
assert "temp" not in ctx
def test_context_del_missing(self, state):
with pytest.raises(SystemExit):
collab.cmd_context_del(state, "ghost")
def test_context_append(self, state, capture_stdout):
collab.cmd_context_set(state, "notes", "line1", by="alice")
with capture_stdout() as cap:
collab.cmd_context_append(state, "notes", "line2", by="bob")
assert "[OK]" in cap.text
ctx = state.read("context")
assert "line1\nline2" == ctx["notes"]["value"]
assert ctx["notes"]["set_by"] == "bob"
def test_context_append_new_key(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_context_append(state, "new_key", "first", by="alice")
assert "[OK]" in cap.text
ctx = state.read("context")
assert ctx["new_key"]["value"] == "first"
# ══════════════════════════════════════════════════════════════════
# TASK COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestTaskCommands:
def test_task_add_unassigned(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_task_add(state, "Build API", by="alice")
assert "Task #1" in cap.text
tasks = state.read("tasks")
assert "1" in tasks
assert tasks["1"]["status"] == "open"
assert tasks["1"]["assigned_to"] is None
def test_task_add_assigned(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_task_add(populated_state, "Write tests",
assign="bob", priority="high", by="alice")
assert "assigned to bob" in cap.text
tasks = populated_state.read("tasks")
t = tasks["1"]
assert t["status"] == "claimed"
assert t["assigned_to"] == "bob"
assert t["priority"] == "high"
def test_task_add_signals_assignee(self, populated_state):
collab.cmd_task_add(populated_state, "Do something",
assign="bob", by="alice")
signals = collab.read_and_clear_signal(populated_state.dir, "bob")
assert any("Task #" in s for s in signals)
def test_task_list(self, state, capture_stdout):
collab.cmd_task_add(state, "Task A", by="alice")
collab.cmd_task_add(state, "Task B", by="alice")
with capture_stdout() as cap:
collab.cmd_task_list(state)
assert "Task A" in cap.text
assert "Task B" in cap.text
def test_task_list_empty(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_task_list(state)
assert "No tasks found" in cap.text
def test_task_list_filter_status(self, state, capture_stdout):
collab.cmd_task_add(state, "Open task", by="a")
collab.cmd_task_add(state, "Done task", by="a")
collab.cmd_task_update(state, 2, "done", by="a")
with capture_stdout() as cap:
collab.cmd_task_list(state, status_filter="done")
assert "Done task" in cap.text
assert "Open task" not in cap.text
def test_task_list_filter_assigned(self, populated_state, capture_stdout):
collab.cmd_task_add(populated_state, "For bob", assign="bob", by="alice")
collab.cmd_task_add(populated_state, "For alice", assign="alice", by="bob")
with capture_stdout() as cap:
collab.cmd_task_list(populated_state, assigned_filter="bob")
assert "For bob" in cap.text
assert "For alice" not in cap.text
def test_task_claim(self, populated_state, capture_stdout):
collab.cmd_task_add(populated_state, "Open task", by="alice")
with capture_stdout() as cap:
collab.cmd_task_claim(populated_state, "bob", 1)
assert "[OK]" in cap.text
tasks = populated_state.read("tasks")
assert tasks["1"]["assigned_to"] == "bob"
assert tasks["1"]["status"] == "claimed"
def test_task_claim_not_found(self, state):
with pytest.raises(SystemExit):
collab.cmd_task_claim(state, "alice", 999)
def test_task_claim_already_done(self, state, capture_stdout):
collab.cmd_task_add(state, "Done task", by="a")
collab.cmd_task_update(state, 1, "done", by="a")
with pytest.raises(SystemExit):
collab.cmd_task_claim(state, "bob", 1)
def test_task_update(self, state, capture_stdout):
collab.cmd_task_add(state, "A task", by="alice")
with capture_stdout() as cap:
collab.cmd_task_update(state, 1, "active", by="alice")
assert "active" in cap.text
tasks = state.read("tasks")
assert tasks["1"]["status"] == "active"
def test_task_update_with_result(self, state, capture_stdout):
collab.cmd_task_add(state, "A task", by="alice")
with capture_stdout() as cap:
collab.cmd_task_update(state, 1, "done",
result_text="Completed successfully", by="alice")
tasks = state.read("tasks")
assert tasks["1"]["result"] == "Completed successfully"
def test_task_update_not_found(self, state):
with pytest.raises(SystemExit):
collab.cmd_task_update(state, 999, "done", by="alice")
def test_task_show(self, state, capture_stdout):
collab.cmd_task_add(state, "Show me", desc="A detailed description",
assign="bob", priority="high", by="alice")
with capture_stdout() as cap:
collab.cmd_task_show(state, 1)
assert "Show me" in cap.text
assert "high" in cap.text
assert "bob" in cap.text
assert "A detailed description" in cap.text
assert "History:" in cap.text
def test_task_show_not_found(self, state):
with pytest.raises(SystemExit):
collab.cmd_task_show(state, 999)
def test_task_history_tracking(self, state):
collab.cmd_task_add(state, "Track me", by="alice")
collab.cmd_task_update(state, 1, "active", by="alice")
collab.cmd_task_update(state, 1, "done", result_text="Done!", by="alice")
tasks = state.read("tasks")
history = tasks["1"]["history"]
assert len(history) == 3 # created, open->active, active->done
assert history[0]["action"] == "created"
assert "active" in history[1]["action"]
assert "done" in history[2]["action"]
# ══════════════════════════════════════════════════════════════════
# FILE LOCK COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestLockCommands:
def test_lock(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_lock(populated_state, "alice", "main.py")
assert "[OK]" in cap.text
locks = populated_state.read("locks")
assert "main.py" in locks
assert locks["main.py"]["held_by"] == "alice"
def test_lock_already_held_by_self(self, populated_state, capture_stdout):
collab.cmd_lock(populated_state, "alice", "main.py")
with capture_stdout() as cap:
collab.cmd_lock(populated_state, "alice", "main.py")
assert "Already locked by you" in cap.text
def test_lock_held_by_other(self, populated_state):
collab.cmd_lock(populated_state, "alice", "main.py")
with pytest.raises(SystemExit):
collab.cmd_lock(populated_state, "bob", "main.py")
def test_unlock(self, populated_state, capture_stdout):
collab.cmd_lock(populated_state, "alice", "main.py")
with capture_stdout() as cap:
collab.cmd_unlock(populated_state, "alice", "main.py")
assert "[OK]" in cap.text
assert populated_state.read("locks") == {}
def test_unlock_not_locked(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_unlock(populated_state, "alice", "main.py")
assert "was not locked" in cap.text
def test_unlock_held_by_other(self, populated_state):
collab.cmd_lock(populated_state, "alice", "main.py")
with pytest.raises(SystemExit):
collab.cmd_unlock(populated_state, "bob", "main.py")
def test_locks_list(self, populated_state, capture_stdout):
collab.cmd_lock(populated_state, "alice", "file1.py")
collab.cmd_lock(populated_state, "bob", "file2.py")
with capture_stdout() as cap:
collab.cmd_locks(populated_state)
assert "file1.py" in cap.text
assert "file2.py" in cap.text
assert "alice" in cap.text
assert "bob" in cap.text
def test_locks_empty(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_locks(state)
assert "No active file locks" in cap.text
# ══════════════════════════════════════════════════════════════════
# POLL & PENDING COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestPollAndPending:
def test_poll_no_updates(self, populated_state, capture_stdout):
# Poll immediately after join — should see no updates from "others"
with capture_stdout() as cap:
collab.cmd_poll(populated_state, "alice")
# alice's join created activity, but poll filters out own activity
# bob's join activity might be visible though
# Either way, it should not error
assert "alice" not in cap.text or "Updates" in cap.text or "No updates" in cap.text
def test_poll_sees_new_messages(self, populated_state, capture_stdout):
# Reset alice's poll timestamp
collab.cmd_poll(populated_state, "alice")
collab.cmd_send(populated_state, "bob", "alice", "Check this out!")
with capture_stdout() as cap:
collab.cmd_poll(populated_state, "alice")
assert "Check this out!" in cap.text
def test_poll_advances_last_poll(self, populated_state):
nodes_before = populated_state.read("nodes")
t1 = nodes_before["alice"]["last_poll"]
time.sleep(0.05)
collab.cmd_poll(populated_state, "alice")
nodes_after = populated_state.read("nodes")
t2 = nodes_after["alice"]["last_poll"]
assert t2 > t1
def test_poll_clears_signals(self, populated_state):
collab.signal_node(populated_state.dir, "alice", "wake up")
assert (populated_state.dir / "_signal_alice").exists()
collab.cmd_poll(populated_state, "alice")
assert not (populated_state.dir / "_signal_alice").exists()
def test_poll_unknown_node(self, state):
with pytest.raises(SystemExit):
collab.cmd_poll(state, "ghost")
def test_pending_nothing(self, populated_state, capture_stdout):
# First clear any existing signals from join
collab.read_and_clear_signal(populated_state.dir, "alice")
collab.cmd_poll(populated_state, "alice") # reset last_poll
with capture_stdout() as cap:
collab.cmd_pending(populated_state, "alice")
assert "Nothing pending" in cap.text
def test_pending_with_signals(self, populated_state, capture_stdout):
collab.cmd_poll(populated_state, "alice") # reset
collab.signal_node(populated_state.dir, "alice", "new task")
with capture_stdout() as cap:
collab.cmd_pending(populated_state, "alice")
assert "signal" in cap.text.lower()
def test_pending_with_messages(self, populated_state, capture_stdout):
collab.cmd_poll(populated_state, "alice") # reset
collab.cmd_send(populated_state, "bob", "alice", "Hey!")
# Clear the signal so we only test message detection
collab.read_and_clear_signal(populated_state.dir, "alice")
with capture_stdout() as cap:
collab.cmd_pending(populated_state, "alice")
assert "message" in cap.text.lower()
def test_pending_unknown_node(self, state):
with pytest.raises(SystemExit):
collab.cmd_pending(state, "ghost")
# ══════════════════════════════════════════════════════════════════
# LOG COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestLogCommand:
def test_log_empty(self, state, capture_stdout):
# Clear the default log
state.write("log", [])
with capture_stdout() as cap:
collab.cmd_log(state)
assert "No activity" in cap.text
def test_log_shows_entries(self, state, capture_stdout):
state.append_log("alice", "test", "Alice did something")
state.append_log("bob", "test", "Bob did something")
with capture_stdout() as cap:
collab.cmd_log(state)
assert "Alice did something" in cap.text
assert "Bob did something" in cap.text
def test_log_limit(self, state, capture_stdout):
for i in range(10):
state.append_log("bot", "test", f"Entry {i}")
with capture_stdout() as cap:
collab.cmd_log(state, limit=3)
assert "Entry 9" in cap.text
assert "Entry 7" in cap.text
assert "Entry 0" not in cap.text
# ══════════════════════════════════════════════════════════════════
# REQUEST COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestRequestCommand:
def test_request_creates_task_and_message(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_request(populated_state, "alice", "bob", "Review PR #42")
assert "[OK]" in cap.text
# Should have created a task
tasks = populated_state.read("tasks")
assert len(tasks) == 1
t = list(tasks.values())[0]
assert t["title"] == "Review PR #42"
assert t["assigned_to"] == "bob"
assert t["priority"] == "high"
assert t["status"] == "claimed"
# Should have sent a message
messages = populated_state.read("messages")
assert any("Review PR #42" in m["content"] for m in messages)
def test_request_signals_target(self, populated_state):
collab.cmd_request(populated_state, "alice", "bob", "Help me")
signals = collab.read_and_clear_signal(populated_state.dir, "bob")
assert len(signals) > 0
def test_request_to_unknown_node(self, populated_state):
with pytest.raises(SystemExit):
collab.cmd_request(populated_state, "alice", "ghost", "Help")
# ══════════════════════════════════════════════════════════════════
# STATUS COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestStatusCommand:
def test_status_empty(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_status(state)
assert "Collaboration Status" in cap.text
assert "0 node(s)" in cap.text
def test_status_with_data(self, populated_state, capture_stdout):
collab.cmd_task_add(populated_state, "A task", by="alice")
collab.cmd_context_set(populated_state, "key", "val", by="alice")
collab.cmd_lock(populated_state, "alice", "test.py")
with capture_stdout() as cap:
collab.cmd_status(populated_state)
assert "2 node(s)" in cap.text
assert "alice" in cap.text
assert "bob" in cap.text
assert "A task" in cap.text
assert "key" in cap.text
assert "test.py" in cap.text
# ══════════════════════════════════════════════════════════════════
# RESET COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestResetCommand:
def test_reset_without_confirm(self, state):
with pytest.raises(SystemExit):
collab.cmd_reset(state, confirm=False)
def test_reset_with_confirm(self, populated_state, capture_stdout):
collab.cmd_task_add(populated_state, "A task", by="alice")
with capture_stdout() as cap:
collab.cmd_reset(populated_state, confirm=True)
assert "[OK]" in cap.text
# Everything should be cleared
assert populated_state.read("nodes") == {}
assert populated_state.read("tasks") == {}
assert populated_state.read("messages") == []
# ══════════════════════════════════════════════════════════════════
# WHOAMI COMMAND TESTS
# ══════════════════════════════════════════════════════════════════
class TestWhoamiCommand:
def test_whoami_registered(self, populated_state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_whoami(populated_state, "alice")
assert "architect" in cap.text
assert "alice" in cap.text
def test_whoami_unregistered(self, state, capture_stdout):
with capture_stdout() as cap:
collab.cmd_whoami(state, "nobody")
assert "not registered" in cap.text
# ══════════════════════════════════════════════════════════════════
# CLI PARSER TESTS
# ══════════════════════════════════════════════════════════════════
class TestCLIParser:
@pytest.fixture
def parser(self):
return collab.build_parser()
def test_join_command(self, parser):
args = parser.parse_args(["join", "alice", "--role", "architect"])
assert args.command == "join"
assert args.name == "alice"
assert args.role == "architect"
def test_leave_command(self, parser):
args = parser.parse_args(["leave", "alice"])
assert args.command == "leave"
assert args.name == "alice"
def test_status_command(self, parser):
args = parser.parse_args(["status"])
assert args.command == "status"
def test_heartbeat_command(self, parser):
args = parser.parse_args(["heartbeat", "alice", "--working-on", "tests",
"--status", "busy"])
assert args.command == "heartbeat"
assert args.working_on == "tests"
assert args.node_status == "busy"
def test_send_command(self, parser):
args = parser.parse_args(["send", "alice", "bob", "hello"])
assert args.command == "send"
assert args.from_node == "alice"
assert args.to == "bob"
assert args.message == "hello"
def test_broadcast_command(self, parser):
args = parser.parse_args(["broadcast", "alice", "Attention!"])
assert args.command == "broadcast"
assert args.from_node == "alice"
assert args.message == "Attention!"
def test_inbox_command(self, parser):
args = parser.parse_args(["inbox", "alice", "--all", "--limit", "50"])
assert args.command == "inbox"
assert args.name == "alice"
assert args.show_all is True
assert args.limit == 50
def test_context_set_command(self, parser):
args = parser.parse_args(["context", "set", "db", "pg", "--by", "alice"])
assert args.command == "context"
assert args.context_cmd == "set"
assert args.key == "db"
assert args.value == "pg"
assert args.by == "alice"
def test_context_get_command(self, parser):
args = parser.parse_args(["context", "get", "db"])
assert args.context_cmd == "get"
assert args.key == "db"
def test_context_get_all_command(self, parser):
args = parser.parse_args(["context", "get"])
assert args.context_cmd == "get"
assert args.key is None
def test_context_del_command(self, parser):
args = parser.parse_args(["context", "del", "db"])
assert args.context_cmd == "del"
assert args.key == "db"
def test_context_append_command(self, parser):
args = parser.parse_args(["context", "append", "notes", "line2", "--by", "bob"])
assert args.context_cmd == "append"
assert args.key == "notes"
assert args.value == "line2"
def test_task_add_command(self, parser):
args = parser.parse_args(["task", "add", "Build API", "--assign", "bob",
"--priority", "high", "--by", "alice"])
assert args.task_cmd == "add"
assert args.title == "Build API"
assert args.assign == "bob"
assert args.priority == "high"
def test_task_list_command(self, parser):
args = parser.parse_args(["task", "list", "--status", "done", "--assigned", "alice"])
assert args.task_cmd == "list"
assert args.status == "done"
assert args.assigned == "alice"
def test_task_claim_command(self, parser):
args = parser.parse_args(["task", "claim", "bob", "5"])
assert args.task_cmd == "claim"
assert args.name == "bob"
assert args.task_id == 5
def test_task_update_command(self, parser):
args = parser.parse_args(["task", "update", "3", "done", "--result", "All good",
"--by", "alice"])
assert args.task_cmd == "update"
assert args.task_id == 3
assert args.new_status == "done"
assert args.result == "All good"
def test_task_show_command(self, parser):
args = parser.parse_args(["task", "show", "7"])
assert args.task_cmd == "show"
assert args.task_id == 7
def test_lock_command(self, parser):
args = parser.parse_args(["lock", "alice", "main.py"])
assert args.command == "lock"
assert args.name == "alice"
assert args.file == "main.py"
def test_unlock_command(self, parser):
args = parser.parse_args(["unlock", "alice", "main.py"])
assert args.command == "unlock"
def test_locks_command(self, parser):
args = parser.parse_args(["locks"])
assert args.command == "locks"
def test_pending_command(self, parser):