返回 last30days-skill
test_watchlist_commands.py
根目录 / tests / test_watchlist_commands.py
1 """Tests for watchlist.py command functions."""
2
3 import json
4 import sqlite3
5 import subprocess
6 import tempfile
7 from pathlib import Path
8 from unittest.mock import Mock, patch
9
10 import pytest
11
12 import last30days as cli
13 import store
14 import watchlist
15 from lib import schema
16
17 @pytest.fixture
18
19
20 def temp_db(tmp_path):
21 """Create a temporary database for testing."""
22 db_path = tmp_path / "test_watchlist.db"
23
24 # Override the database path
25 original_override = store._db_override
26 store._db_override = db_path
27
28 # Initialize fresh database
29 store.init_db()
30
31 yield db_path
32
33 # Cleanup
34 store._db_override = original_override
35 if db_path.exists():
36 db_path.unlink()
37
38 # === Tests for cmd_add() ===
39
40
41 def test_cmd_add_basic(temp_db, capsys):
42 """Test adding a topic with default schedule."""
43 args = Mock()
44 args.topic = "Test Topic"
45 args.weekly = False
46 args.schedule = None
47 args.queries = None
48
49 watchlist.cmd_add(args)
50
51 # Verify output
52 captured = capsys.readouterr()
53 output = json.loads(captured.out)
54
55 assert output["action"] == "added"
56 assert output["topic"] == "Test Topic"
57 assert "daily" in output["schedule"]
58
59
60 def test_cmd_add_with_custom_schedule(temp_db, capsys):
61 """Test adding a topic with custom schedule."""
62 args = Mock()
63 args.topic = "Test Topic"
64 args.weekly = False
65 args.schedule = "0 12 * * *"
66 args.queries = None
67
68 watchlist.cmd_add(args)
69
70 # Verify in database
71 topic = store.get_topic("Test Topic")
72 assert topic["schedule"] == "0 12 * * *"
73
74
75 def test_cmd_add_weekly(temp_db, capsys):
76 """Test adding a topic with weekly schedule."""
77 args = Mock()
78 args.topic = "Test Topic"
79 args.weekly = True
80 args.schedule = None
81 args.queries = None
82
83 watchlist.cmd_add(args)
84
85 # Verify weekly schedule
86 topic = store.get_topic("Test Topic")
87 assert topic["schedule"] == "0 8 * * 1" # Monday 8am
88
89
90 def test_cmd_add_with_search_queries(temp_db, capsys):
91 """Test adding a topic with custom search queries."""
92 args = Mock()
93 args.topic = "Test Topic"
94 args.weekly = False
95 args.schedule = None
96 args.queries = "query1, query2, query3"
97
98 watchlist.cmd_add(args)
99
100 # Verify queries stored
101 topic = store.get_topic("Test Topic")
102 queries = json.loads(topic["search_queries"])
103 assert queries == ["query1", "query2", "query3"]
104
105 # === Tests for cmd_remove() ===
106
107
108 def test_cmd_remove_existing_topic(temp_db, capsys):
109 """Test removing an existing topic."""
110 # Add a topic first
111 store.add_topic("Test Topic")
112
113 args = Mock()
114 args.topic = "Test Topic"
115
116 watchlist.cmd_remove(args)
117
118 # Verify output
119 captured = capsys.readouterr()
120 output = json.loads(captured.out)
121
122 assert output["action"] == "removed"
123 assert output["topic"] == "Test Topic"
124
125
126 def test_cmd_remove_nonexistent_topic(temp_db, capsys):
127 """Test removing a topic that doesn't exist."""
128 args = Mock()
129 args.topic = "Nonexistent Topic"
130
131 watchlist.cmd_remove(args)
132
133 # Verify output
134 captured = capsys.readouterr()
135 output = json.loads(captured.out)
136
137 assert output["action"] == "not_found"
138 assert output["topic"] == "Nonexistent Topic"
139
140 # === Tests for cmd_list() ===
141
142
143 def test_cmd_list_empty(temp_db, capsys):
144 """Test listing when no topics exist."""
145 args = Mock()
146
147 watchlist.cmd_list(args)
148
149 # Verify output
150 captured = capsys.readouterr()
151 output = json.loads(captured.out)
152
153 assert output["topics"] == []
154 assert output["budget_used"] == 0.0
155 assert output["budget_limit"] == 5.0
156
157
158 def test_cmd_list_with_topics(temp_db, capsys):
159 """Test listing with multiple topics."""
160 # Add topics
161 store.add_topic("Topic 1")
162 store.add_topic("Topic 2")
163 store.add_topic("Topic 3")
164
165 args = Mock()
166
167 watchlist.cmd_list(args)
168
169 # Verify output
170 captured = capsys.readouterr()
171 output = json.loads(captured.out)
172
173 assert len(output["topics"]) == 3
174 topic_names = {t["name"] for t in output["topics"]}
175 assert topic_names == {"Topic 1", "Topic 2", "Topic 3"}
176
177 # === Tests for cmd_delta() ===
178
179
180 def test_cmd_delta_outputs_topic_delta(temp_db, capsys):
181 """Test printing the latest watchlist delta as JSON."""
182 topic = store.add_topic("Test Topic")
183 previous_run_id = store.record_run(topic["id"], source_mode="v3", status="completed")
184 store.store_findings(previous_run_id, topic["id"], [
185 {
186 "source": "reddit",
187 "source_url": "https://reddit.com/continued",
188 "source_title": "Continued",
189 "content": "Still present",
190 }
191 ])
192 current_run_id = store.record_run(topic["id"], source_mode="v3", status="completed")
193 store.store_findings(current_run_id, topic["id"], [
194 {
195 "source": "reddit",
196 "source_url": "https://reddit.com/continued",
197 "source_title": "Continued",
198 "content": "Still present",
199 },
200 {
201 "source": "github",
202 "source_url": "https://github.com/example/new",
203 "source_title": "New",
204 "content": "New this run",
205 },
206 ])
207
208 args = Mock()
209 args.topic = "Test Topic"
210
211 watchlist.cmd_delta(args)
212
213 captured = capsys.readouterr()
214 output = json.loads(captured.out)
215
216 assert output["topic"] == "Test Topic"
217 assert output["status"] == "ok"
218 assert output["current_run_id"] == current_run_id
219 assert output["previous_run_id"] == previous_run_id
220 assert output["new"] == 1
221 assert output["continued"] == 1
222
223
224 def test_cmd_delta_unknown_topic_exits(temp_db):
225 """Test delta for an unknown topic exits with an error."""
226 args = Mock()
227 args.topic = "Missing Topic"
228
229 with pytest.raises(SystemExit):
230 watchlist.cmd_delta(args)
231
232 # === Tests for cmd_config() ===
233
234
235 def test_cmd_config_delivery(temp_db, capsys):
236 """Test configuring delivery channel."""
237 args = Mock()
238 args.key = "delivery"
239 args.value = "https://hooks.slack.com/services/TEST"
240
241 watchlist.cmd_config(args)
242
243 # Verify setting stored
244 channel = store.get_setting("delivery_channel")
245 assert channel == "https://hooks.slack.com/services/TEST"
246
247 # Verify output
248 captured = capsys.readouterr()
249 output = json.loads(captured.out)
250
251 assert output["action"] == "config"
252 assert output["key"] == "delivery_channel"
253 assert output["configured"] is True
254 assert args.value not in captured.out
255
256
257 def test_cmd_config_delivery_rejects_non_https(temp_db):
258 """A non-https delivery channel is rejected at write time, not stored."""
259 args = Mock()
260 args.key = "delivery"
261 args.value = "http://evil.example/hooks.slack.com"
262
263 with pytest.raises(SystemExit) as failure:
264 watchlist.cmd_config(args)
265
266 assert args.value not in str(failure.value)
267 assert not store.get_setting("delivery_channel")
268
269
270 def test_cmd_config_budget(temp_db, capsys):
271 """Test configuring daily budget."""
272 args = Mock()
273 args.key = "budget"
274 args.value = 10.0
275
276 watchlist.cmd_config(args)
277
278 # Verify setting stored
279 budget = store.get_setting("daily_budget")
280 assert budget == "10.0"
281
282
283 def test_cmd_config_unknown_key(temp_db):
284 """Test that unknown config key raises error."""
285 args = Mock()
286 args.key = "unknown_key"
287 args.value = "value"
288
289 with pytest.raises(SystemExit):
290 watchlist.cmd_config(args)
291
292 # === Tests for _run_topic() ===
293
294 @pytest.mark.parametrize(
295 ("name", "queries"),
296 [
297 pytest.param("search trends", None, id="ordinary"),
298 pytest.param("setup", None, id="reserved"),
299 pytest.param("option names", ["--quick"], id="option-shaped-query"),
300 ],
301 )
302 def test_run_topic_passes_literal_research_topic(temp_db, name, queries):
303 topic = store.add_topic(name, search_queries=queries)
304 expected_topic = queries[0] if queries else name
305 with patch(
306 "watchlist.subprocess.run",
307 autospec=True,
308 return_value=subprocess.CompletedProcess([], 1, "", "offline"),
309 ) as run:
310 watchlist._run_topic(topic)
311
312 run.assert_called_once()
313 argv = run.call_args.args[0]
314 parsed, extra = cli.build_parser().parse_known_args(argv[2:])
315 assert parsed.topic == [expected_topic]
316 assert parsed.research_only is True
317 assert argv[-2:] == ["--", expected_topic]
318 assert not extra
319 assert parsed.emit == "json"
320 assert parsed.json_profile == "raw"
321 assert parsed.quick is True
322 assert parsed.lookback_days == 90
323 assert parsed.no_browser_cookies is True
324 assert run.call_args.kwargs["env"]["LAST30DAYS_STORE"] == "0"
325
326
327 @patch('watchlist.subprocess.run')
328
329
330 def test_run_topic_success(mock_subprocess, temp_db):
331 """Test successful topic run."""
332 topic = store.add_topic("Test Topic")
333
334 # Mock successful subprocess call
335 mock_result = Mock()
336 mock_result.returncode = 0
337 mock_result.stdout = json.dumps({
338 "topic": "Test Topic",
339 "range_from": "2026-01-01",
340 "range_to": "2026-04-03",
341 "generated_at": "2026-04-03T00:00:00Z",
342 "provider_runtime": {
343 "reasoning_provider": "gemini",
344 "planner_model": "gemini-2.0-flash-exp",
345 "rerank_model": "gemini-2.0-flash-exp",
346 },
347 "query_plan": {
348 "intent": "test",
349 "freshness_mode": "recent",
350 "cluster_mode": "standard",
351 "raw_topic": "test",
352 "subqueries": [],
353 "source_weights": {},
354 },
355 "clusters": [],
356 "ranked_candidates": [
357 {
358 "candidate_id": "c-r1",
359 "item_id": "R1",
360 "source": "reddit",
361 "title": "Test",
362 "url": "https://reddit.com/1",
363 "snippet": "Snippet",
364 "subquery_labels": ["primary"],
365 "native_ranks": {"reddit": 1},
366 "local_relevance": 0.8,
367 "freshness": 100,
368 "engagement": 50.0,
369 "source_quality": 0.8,
370 "rrf_score": 1.0,
371 "final_score": 0.8,
372 "explanation": "Snippet",
373 "source_items": [
374 {
375 "item_id": "R1",
376 "source": "reddit",
377 "title": "Test",
378 "body": "Content",
379 "url": "https://reddit.com/1",
380 "author": "user",
381 "engagement_score": 50.0,
382 "local_relevance": 0.8,
383 "snippet": "Snippet",
384 }
385 ],
386 }
387 ],
388 "items_by_source": {
389 "reddit": [
390 {
391 "item_id": "R1",
392 "source": "reddit",
393 "title": "Test",
394 "body": "Content",
395 "url": "https://reddit.com/1",
396 "author": "user",
397 "engagement_score": 50.0,
398 "local_relevance": 0.8,
399 "snippet": "Snippet",
400 }
401 ],
402 },
403 "errors_by_source": {},
404 "warnings": [],
405 })
406 mock_subprocess.return_value = mock_result
407
408 result = watchlist._run_topic(topic)
409
410 assert result["status"] == "completed"
411 assert result["new"] == 1
412 assert result["topic"] == "Test Topic"
413 argv = mock_subprocess.call_args.args[0]
414 assert "--emit=json" in argv
415 assert "--json-profile=raw" in argv
416
417 @patch('watchlist.subprocess.run')
418
419
420 def test_run_topic_failure(mock_subprocess, temp_db):
421 """Test topic run failure."""
422 topic = store.add_topic("Test Topic")
423
424 # Mock failed subprocess call
425 mock_result = Mock()
426 mock_result.returncode = 1
427 mock_result.stderr = "Error message"
428 mock_subprocess.return_value = mock_result
429
430 result = watchlist._run_topic(topic)
431
432 assert result["status"] == "failed"
433 assert "Error message" in result["error"]
434
435 @patch('watchlist.subprocess.run')
436
437
438 def test_run_topic_timeout(mock_subprocess, temp_db):
439 """Test topic run timeout."""
440 topic = store.add_topic("Test Topic")
441
442 # Mock timeout
443 mock_subprocess.side_effect = subprocess.TimeoutExpired("cmd", 300)
444
445 result = watchlist._run_topic(topic)
446
447 assert result["status"] == "failed"
448 assert result["error"] == "timeout"
449
450
451 def test_run_all_continues_after_subprocess_launch_failure(temp_db, monkeypatch, capsys):
452 store.add_topic("A")
453 store.add_topic("B")
454 report = {
455 "topic": "B",
456 "range_from": "2026-11-01",
457 "range_to": "2026-12-01",
458 "generated_at": "2026-12-01T12:00:00Z",
459 "provider_runtime": {
460 "reasoning_provider": "mock", "planner_model": "mock", "rerank_model": "mock",
461 },
462 "query_plan": {
463 "intent": "test", "freshness_mode": "recent",
464 "cluster_mode": "standard", "raw_topic": "B",
465 },
466 }
467 run = Mock(side_effect=[
468 FileNotFoundError("synthetic launch failure"),
469 subprocess.CompletedProcess([], 0, json.dumps(report), ""),
470 ])
471 monkeypatch.setattr(watchlist.subprocess, "run", run)
472
473 watchlist.cmd_run_all(Mock())
474
475 results = json.loads(capsys.readouterr().out)["results"]
476 assert [(item["topic"], item["status"]) for item in results] == [
477 ("A", "failed"), ("B", "completed"),
478 ]
479 assert [topic["last_status"] for topic in store.list_topics()] == ["failed", "completed"]
480 assert store.get_daily_usage() == (0.0, 0)
481
482
483 def test_undecodable_child_output_leaves_failed_run_with_unknown_cost(temp_db, monkeypatch):
484 topic = store.add_topic("A")
485 run = Mock(side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid byte"))
486 monkeypatch.setattr(watchlist.subprocess, "run", run)
487
488 result = watchlist._run_topic(topic)
489
490 assert result["status"] == "failed"
491 assert "UnicodeDecodeError" in result["error"]
492 assert store.list_topics()[0]["last_status"] == "failed"
493 assert store.get_daily_usage() == (0.0, 1)
494
495 @patch('watchlist.subprocess.run')
496 @patch('watchlist._deliver_findings')
497
498
499 def test_run_topic_calls_delivery(mock_deliver, mock_subprocess, temp_db):
500 """Test that successful run calls delivery."""
501 topic = store.add_topic("Test Topic")
502
503 # Mock successful subprocess call with findings
504 mock_result = Mock()
505 mock_result.returncode = 0
506 mock_result.stdout = json.dumps({
507 "topic": "Test Topic",
508 "range_from": "2026-01-01",
509 "range_to": "2026-04-03",
510 "generated_at": "2026-04-03T00:00:00Z",
511 "provider_runtime": {
512 "reasoning_provider": "gemini",
513 "planner_model": "gemini-2.0-flash-exp",
514 "rerank_model": "gemini-2.0-flash-exp",
515 },
516 "query_plan": {
517 "intent": "test",
518 "freshness_mode": "recent",
519 "cluster_mode": "standard",
520 "raw_topic": "test",
521 "subqueries": [],
522 "source_weights": {},
523 },
524 "clusters": [],
525 "ranked_candidates": [
526 {
527 "candidate_id": "c-r1",
528 "item_id": "R1",
529 "source": "reddit",
530 "title": "Test",
531 "url": "https://reddit.com/1",
532 "snippet": "Snippet",
533 "subquery_labels": ["primary"],
534 "native_ranks": {"reddit": 1},
535 "local_relevance": 0.8,
536 "freshness": 100,
537 "engagement": 50.0,
538 "source_quality": 0.8,
539 "rrf_score": 1.0,
540 "final_score": 0.8,
541 "explanation": "Snippet",
542 "source_items": [
543 {
544 "item_id": "R1",
545 "source": "reddit",
546 "title": "Test",
547 "body": "Content",
548 "url": "https://reddit.com/1",
549 "author": "user",
550 "engagement_score": 50.0,
551 "local_relevance": 0.8,
552 "snippet": "Snippet",
553 }
554 ],
555 }
556 ],
557 "items_by_source": {
558 "reddit": [
559 {
560 "item_id": "R1",
561 "source": "reddit",
562 "title": "Test",
563 "body": "Content",
564 "url": "https://reddit.com/1",
565 "author": "user",
566 "engagement_score": 50.0,
567 "local_relevance": 0.8,
568 "snippet": "Snippet",
569 }
570 ],
571 },
572 "errors_by_source": {},
573 "warnings": [],
574 })
575 mock_subprocess.return_value = mock_result
576
577 watchlist._run_topic(topic)
578
579 # Verify delivery was called
580 assert mock_deliver.called
581 call_args = mock_deliver.call_args[0]
582 assert call_args[0] == "Test Topic"
583 assert call_args[1]["new"] == 1
584
585 # === Tests for cmd_run_one() ===
586
587 @patch('watchlist._run_topic')
588
589
590 def test_cmd_run_one(mock_run, temp_db, capsys):
591 """Test running a single topic."""
592 topic = store.add_topic("Test Topic")
593
594 mock_run.return_value = {
595 "topic": "Test Topic",
596 "status": "completed",
597 "new": 5,
598 "updated": 2,
599 "duration": 60.0,
600 }
601
602 args = Mock()
603 args.topic = "Test Topic"
604
605 watchlist.cmd_run_one(args)
606
607 # Verify output
608 captured = capsys.readouterr()
609 output = json.loads(captured.out)
610
611 assert output["status"] == "completed"
612 assert output["new"] == 5
613
614
615 def test_cmd_run_one_nonexistent_topic(temp_db, capsys):
616 """Test running a nonexistent topic."""
617 args = Mock()
618 args.topic = "Nonexistent Topic"
619
620 with pytest.raises(SystemExit):
621 watchlist.cmd_run_one(args)
622
623 # === Tests for cmd_run_all() ===
624
625 @patch('watchlist._run_topic')
626
627
628 def test_cmd_run_all_no_topics(mock_run, temp_db, capsys):
629 """Test running all topics when none exist."""
630 args = Mock()
631
632 watchlist.cmd_run_all(args)
633
634 # Verify output
635 captured = capsys.readouterr()
636 output = json.loads(captured.out)
637
638 assert "No enabled topics" in output["message"]
639
640 @patch('watchlist._run_topic')
641
642
643 def test_cmd_run_all_multiple_topics(mock_run, temp_db, capsys):
644 """Test running multiple topics."""
645 # Add topics
646 store.add_topic("Topic 1")
647 store.add_topic("Topic 2")
648
649 mock_run.return_value = {
650 "topic": "Test",
651 "status": "completed",
652 "new": 5,
653 "updated": 2,
654 "duration": 60.0,
655 }
656
657 args = Mock()
658
659 watchlist.cmd_run_all(args)
660
661 # Verify output
662 captured = capsys.readouterr()
663 output = json.loads(captured.out)
664
665 assert output["action"] == "run_all"
666 assert len(output["results"]) == 2
667
668 @patch('watchlist._run_topic')
669 def test_cmd_run_all_respects_budget(mock_run, temp_db, capsys):
670 """Test that run-all respects daily budget."""
671 # Add topics
672 first = store.add_topic("Topic 1")
673 store.add_topic("Topic 2")
674 store.add_topic("Topic 3")
675
676 store.record_run(first["id"], token_cost=6.0)
677
678 mock_run.return_value = {
679 "topic": "Test",
680 "status": "completed",
681 "new": 5,
682 "updated": 2,
683 "duration": 60.0,
684 }
685
686 args = Mock()
687
688 watchlist.cmd_run_all(args)
689
690 # Verify output
691 captured = capsys.readouterr()
692 output = json.loads(captured.out)
693
694 # All topics should be skipped due to budget
695 results = output["results"]
696 skipped = [r for r in results if r["status"] == "skipped"]
697
698 assert len(skipped) == 3 # All 3 topics skipped
699 mock_run.assert_not_called()
700
701 if __name__ == "__main__":
702 pytest.main([__file__, "-v"])
703
703 lines PYTHON