twitter-cli 0.8.4__tar.gz → 0.8.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/PKG-INFO +13 -1
  2. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/README.md +12 -0
  3. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/pyproject.toml +1 -1
  4. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_auth.py +16 -0
  5. twitter_cli-0.8.5/tests/test_cache.py +101 -0
  6. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_cli.py +90 -2
  7. twitter_cli-0.8.5/tests/test_filter.py +88 -0
  8. twitter_cli-0.8.5/tests/test_output.py +147 -0
  9. twitter_cli-0.8.5/tests/test_timeutil.py +73 -0
  10. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/auth.py +12 -2
  11. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/cli.py +219 -78
  12. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/client.py +54 -1
  13. twitter_cli-0.8.5/twitter_cli/commands/__init__.py +7 -0
  14. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/exceptions.py +30 -1
  15. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/formatter.py +19 -6
  16. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/graphql.py +2 -0
  17. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/models.py +6 -0
  18. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/output.py +22 -0
  19. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/serialization.py +17 -2
  20. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/timeutil.py +11 -0
  21. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/uv.lock +1 -1
  22. twitter_cli-0.8.4/tests/test_filter.py +0 -31
  23. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  24. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
  25. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/.github/workflows/ci.yml +0 -0
  26. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/.github/workflows/publish.yml +0 -0
  27. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/.gitignore +0 -0
  28. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/AGENTS.md +0 -0
  29. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/LICENSE +0 -0
  30. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/SCHEMA.md +0 -0
  31. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/SKILL.md +0 -0
  32. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/config.yaml +0 -0
  33. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/conftest.py +0 -0
  34. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/fixtures/followers_page.json +0 -0
  35. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/fixtures/home_timeline.json +0 -0
  36. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/fixtures/list_timeline.json +0 -0
  37. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/fixtures/search_timeline.json +0 -0
  38. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/fixtures/tweet_detail.json +0 -0
  39. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_client.py +0 -0
  40. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_config.py +0 -0
  41. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_config_normalization.py +0 -0
  42. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_parser_fixtures.py +0 -0
  43. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_search.py +0 -0
  44. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_serialization.py +0 -0
  45. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/tests/test_smoke.py +0 -0
  46. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/__init__.py +0 -0
  47. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/cache.py +0 -0
  48. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/config.py +0 -0
  49. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/constants.py +0 -0
  50. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/filter.py +0 -0
  51. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/parser.py +0 -0
  52. {twitter_cli-0.8.4 → twitter_cli-0.8.5}/twitter_cli/search.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: twitter-cli
3
- Version: 0.8.4
3
+ Version: 0.8.5
4
4
  Summary: A CLI for Twitter/X — feed, bookmarks, and user timeline in terminal
5
5
  Project-URL: Homepage, https://github.com/jackwener/twitter-cli
6
6
  Project-URL: Repository, https://github.com/jackwener/twitter-cli
@@ -330,6 +330,12 @@ Mode behavior:
330
330
  - `Invalid tweet JSON file`
331
331
  - Regenerate input using `twitter feed --json > tweets.json`.
332
332
 
333
+ - **Windows: no output captured by pipe/subprocess** (AI agent integration)
334
+ - This is a **ConPTY** issue, not a twitter-cli bug. Windows Terminal's ConPTY pseudo-terminal can intercept pipe output from commands with network latency.
335
+ - **Fix**: Use **Git Bash** as your terminal shell and set `"windowsEnableConpty": false` in your terminal settings.
336
+ - If disabling ConPTY with PowerShell, emoji output may fail with `UnicodeEncodeError: 'gbk'`. Git Bash handles UTF-8 natively.
337
+ - Standard `subprocess.run(capture_output=True)` and file redirection (`> file 2>&1`) work correctly regardless of ConPTY.
338
+
333
339
 
334
340
 
335
341
  Structured error codes commonly include `not_authenticated`, `not_found`, `invalid_input`, `rate_limited`, and `api_error`.
@@ -585,6 +591,12 @@ score = likes_w * likes
585
591
  - 或在弹出 Keychain 授权时点击 **"始终允许"**。
586
592
  - 报错 `Twitter API error 404`:通常是 queryId 轮换,重试即可。
587
593
 
594
+ - **Windows 下 pipe/subprocess 无法捕获输出**(AI agent 集成场景)
595
+ - 这是 **ConPTY** 伪终端的问题,不是 twitter-cli 的 bug。Windows Terminal 的 ConPTY 可能拦截有网络延迟的命令的管道输出。
596
+ - **解决方案**:使用 **Git Bash** 并在终端设置中设置 `"windowsEnableConpty": false`。
597
+ - ConPTY 关闭后如用 PowerShell,emoji 可能会报 `UnicodeEncodeError: 'gbk'`。Git Bash 原生支持 UTF-8。
598
+ - 标准 `subprocess.run(capture_output=True)` 和文件重定向 (`> file 2>&1`) 不受此问题影响。
599
+
588
600
 
589
601
 
590
602
  - 结构化错误码通常会区分 `not_authenticated`、`not_found`、`invalid_input`、`rate_limited`、`api_error`。
@@ -298,6 +298,12 @@ Mode behavior:
298
298
  - `Invalid tweet JSON file`
299
299
  - Regenerate input using `twitter feed --json > tweets.json`.
300
300
 
301
+ - **Windows: no output captured by pipe/subprocess** (AI agent integration)
302
+ - This is a **ConPTY** issue, not a twitter-cli bug. Windows Terminal's ConPTY pseudo-terminal can intercept pipe output from commands with network latency.
303
+ - **Fix**: Use **Git Bash** as your terminal shell and set `"windowsEnableConpty": false` in your terminal settings.
304
+ - If disabling ConPTY with PowerShell, emoji output may fail with `UnicodeEncodeError: 'gbk'`. Git Bash handles UTF-8 natively.
305
+ - Standard `subprocess.run(capture_output=True)` and file redirection (`> file 2>&1`) work correctly regardless of ConPTY.
306
+
301
307
 
302
308
 
303
309
  Structured error codes commonly include `not_authenticated`, `not_found`, `invalid_input`, `rate_limited`, and `api_error`.
@@ -553,6 +559,12 @@ score = likes_w * likes
553
559
  - 或在弹出 Keychain 授权时点击 **"始终允许"**。
554
560
  - 报错 `Twitter API error 404`:通常是 queryId 轮换,重试即可。
555
561
 
562
+ - **Windows 下 pipe/subprocess 无法捕获输出**(AI agent 集成场景)
563
+ - 这是 **ConPTY** 伪终端的问题,不是 twitter-cli 的 bug。Windows Terminal 的 ConPTY 可能拦截有网络延迟的命令的管道输出。
564
+ - **解决方案**:使用 **Git Bash** 并在终端设置中设置 `"windowsEnableConpty": false`。
565
+ - ConPTY 关闭后如用 PowerShell,emoji 可能会报 `UnicodeEncodeError: 'gbk'`。Git Bash 原生支持 UTF-8。
566
+ - 标准 `subprocess.run(capture_output=True)` 和文件重定向 (`> file 2>&1`) 不受此问题影响。
567
+
556
568
 
557
569
 
558
570
  - 结构化错误码通常会区分 `not_authenticated`、`not_found`、`invalid_input`、`rate_limited`、`api_error`。
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "twitter-cli"
7
- version = "0.8.4"
7
+ version = "0.8.5"
8
8
  description = "A CLI for Twitter/X — feed, bookmarks, and user timeline in terminal"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -349,6 +349,22 @@ def test_diagnose_keychain_issues_ssh_hint(monkeypatch) -> None:
349
349
  assert "security unlock-keychain" in hint
350
350
 
351
351
 
352
+ def test_diagnose_keychain_issues_windows_hint(monkeypatch) -> None:
353
+ """On Windows, hint should mention DPAPI and environment variable workaround."""
354
+ monkeypatch.setattr("sys.platform", "win32")
355
+ monkeypatch.delenv("SSH_CLIENT", raising=False)
356
+ monkeypatch.delenv("SSH_TTY", raising=False)
357
+ monkeypatch.delenv("SSH_CONNECTION", raising=False)
358
+
359
+ diagnostics = ["chrome: Unable to get key for cookie decryption"]
360
+ hint = auth._diagnose_keychain_issues(diagnostics)
361
+
362
+ assert hint is not None
363
+ assert "DPAPI" in hint
364
+ assert "TWITTER_AUTH_TOKEN" in hint
365
+ assert "shadowcopy" in hint
366
+
367
+
352
368
  def test_diagnose_keychain_issues_returns_none_for_unrelated_errors() -> None:
353
369
  """Should return None when diagnostics don't mention Keychain."""
354
370
  diagnostics = ["chrome[Default]=no-cookies", "firefox: profile not found"]
@@ -0,0 +1,101 @@
1
+ """Tests for twitter_cli.cache module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+
8
+
9
+ from twitter_cli.cache import resolve_cached_tweet, save_tweet_cache
10
+ from twitter_cli.models import Author, Metrics, Tweet
11
+
12
+
13
+ def _make_tweet(tweet_id: str, text: str = "hello") -> Tweet:
14
+ return Tweet(
15
+ id=tweet_id,
16
+ text=text,
17
+ author=Author(id="u1", name="Alice", screen_name="alice"),
18
+ metrics=Metrics(likes=1),
19
+ created_at="2025-01-01",
20
+ )
21
+
22
+
23
+ class TestSaveAndResolve:
24
+ """save_tweet_cache → resolve_cached_tweet round-trip."""
25
+
26
+ def test_round_trip(self, tmp_path, monkeypatch) -> None:
27
+ cache_file = tmp_path / "last_results.json"
28
+ monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
29
+ monkeypatch.setattr("twitter_cli.cache._CACHE_DIR", tmp_path)
30
+
31
+ tweets = [_make_tweet("100"), _make_tweet("200"), _make_tweet("300")]
32
+ save_tweet_cache(tweets)
33
+
34
+ assert cache_file.exists()
35
+ tweet_id, size = resolve_cached_tweet(1)
36
+ assert tweet_id == "100"
37
+ assert size == 3
38
+
39
+ tweet_id, size = resolve_cached_tweet(3)
40
+ assert tweet_id == "300"
41
+ assert size == 3
42
+
43
+ def test_out_of_range_returns_none(self, tmp_path, monkeypatch) -> None:
44
+ cache_file = tmp_path / "last_results.json"
45
+ monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
46
+ monkeypatch.setattr("twitter_cli.cache._CACHE_DIR", tmp_path)
47
+
48
+ save_tweet_cache([_make_tweet("100")])
49
+
50
+ tweet_id, size = resolve_cached_tweet(99)
51
+ assert tweet_id is None
52
+ assert size == 1
53
+
54
+
55
+ class TestCacheExpiry:
56
+ """TTL expiration behavior."""
57
+
58
+ def test_expired_cache_returns_none(self, tmp_path, monkeypatch) -> None:
59
+ cache_file = tmp_path / "last_results.json"
60
+ monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
61
+
62
+ # Write cache with old timestamp
63
+ payload = {
64
+ "created_at": time.time() - 7200, # 2 hours ago
65
+ "tweets": [{"index": 1, "id": "100", "author": "alice", "text": "hi"}],
66
+ }
67
+ cache_file.write_text(json.dumps(payload), encoding="utf-8")
68
+
69
+ tweet_id, size = resolve_cached_tweet(1)
70
+ assert tweet_id is None
71
+ assert size == 0
72
+
73
+
74
+ class TestCacheEdgeCases:
75
+ """Corrupted and missing cache files."""
76
+
77
+ def test_missing_file(self, tmp_path, monkeypatch) -> None:
78
+ cache_file = tmp_path / "does_not_exist.json"
79
+ monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
80
+
81
+ tweet_id, size = resolve_cached_tweet(1)
82
+ assert tweet_id is None
83
+ assert size == 0
84
+
85
+ def test_corrupted_json(self, tmp_path, monkeypatch) -> None:
86
+ cache_file = tmp_path / "last_results.json"
87
+ cache_file.write_text("{{invalid json", encoding="utf-8")
88
+ monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
89
+
90
+ tweet_id, size = resolve_cached_tweet(1)
91
+ assert tweet_id is None
92
+ assert size == 0
93
+
94
+ def test_wrong_structure(self, tmp_path, monkeypatch) -> None:
95
+ cache_file = tmp_path / "last_results.json"
96
+ cache_file.write_text('"just a string"', encoding="utf-8")
97
+ monkeypatch.setattr("twitter_cli.cache._CACHE_FILE", cache_file)
98
+
99
+ tweet_id, size = resolve_cached_tweet(1)
100
+ assert tweet_id is None
101
+ assert size == 0
@@ -10,7 +10,7 @@ import yaml
10
10
 
11
11
  from twitter_cli.cli import cli
12
12
  from twitter_cli.formatter import article_to_markdown, print_tweet_table
13
- from twitter_cli.models import Author, Metrics, Tweet, UserProfile
13
+ from twitter_cli.models import Author, BookmarkFolder, Metrics, Tweet, UserProfile
14
14
  from twitter_cli.serialization import tweets_to_json
15
15
 
16
16
 
@@ -104,10 +104,11 @@ def test_cli_commands_wrap_client_creation_errors(monkeypatch, args) -> None:
104
104
 
105
105
 
106
106
  def test_cli_user_error_yaml(monkeypatch) -> None:
107
+ from twitter_cli.exceptions import NotFoundError
107
108
  monkeypatch.setenv("OUTPUT", "auto")
108
109
  monkeypatch.setattr(
109
110
  "twitter_cli.cli._get_client",
110
- lambda config=None, quiet=False: (_ for _ in ()).throw(RuntimeError("User not found")),
111
+ lambda config=None, quiet=False: (_ for _ in ()).throw(NotFoundError("User not found")),
111
112
  )
112
113
  runner = CliRunner()
113
114
 
@@ -253,6 +254,93 @@ def test_cli_bookmark_alias_works(monkeypatch) -> None:
253
254
  assert calls == ["123"]
254
255
 
255
256
 
257
+ def test_cli_bookmarks_folders_inherits_parent_options(monkeypatch) -> None:
258
+ calls = []
259
+
260
+ def fake_folder_timeline(
261
+ folder_id: str,
262
+ max_count: int | None,
263
+ since: str | None,
264
+ as_json: bool,
265
+ as_yaml: bool,
266
+ output_file: str | None,
267
+ do_filter: bool,
268
+ compact: bool,
269
+ full_text: bool,
270
+ ) -> None:
271
+ calls.append(
272
+ (
273
+ folder_id,
274
+ max_count,
275
+ since,
276
+ as_json,
277
+ as_yaml,
278
+ output_file,
279
+ do_filter,
280
+ compact,
281
+ full_text,
282
+ )
283
+ )
284
+
285
+ monkeypatch.setattr("twitter_cli.cli._run_bookmark_folder_timeline", fake_folder_timeline)
286
+ runner = CliRunner()
287
+
288
+ result = runner.invoke(
289
+ cli,
290
+ ["bookmarks", "--json", "--full-text", "-n", "7", "-o", "root.json", "--filter", "folders", "123"],
291
+ )
292
+
293
+ assert result.exit_code == 0
294
+ assert calls == [("123", 7, None, True, False, "root.json", True, False, True)]
295
+
296
+
297
+ def test_cli_bookmarks_folders_list_inherits_parent_output_options(monkeypatch) -> None:
298
+ calls = []
299
+
300
+ def fake_list_bookmark_folders(
301
+ as_json: bool,
302
+ as_yaml: bool,
303
+ compact: bool,
304
+ output_file: str | None,
305
+ ) -> None:
306
+ calls.append((as_json, as_yaml, compact, output_file))
307
+
308
+ monkeypatch.setattr("twitter_cli.cli._run_list_bookmark_folders", fake_list_bookmark_folders)
309
+ runner = CliRunner()
310
+
311
+ result = runner.invoke(cli, ["bookmarks", "--json", "-o", "folders.json", "folders"])
312
+
313
+ assert result.exit_code == 0
314
+ assert calls == [(True, False, False, "folders.json")]
315
+
316
+
317
+ def test_cli_bookmarks_folders_list_writes_output_file(monkeypatch, tmp_path) -> None:
318
+ class FakeClient:
319
+ def fetch_bookmark_folders(self) -> list[BookmarkFolder]:
320
+ return [BookmarkFolder(id="f1", name="Reading"), BookmarkFolder(id="f2", name="Research")]
321
+
322
+ monkeypatch.setattr("twitter_cli.cli._get_client", lambda config=None, quiet=False: FakeClient())
323
+ monkeypatch.setattr("twitter_cli.cli.load_config", lambda: {})
324
+ output_path = tmp_path / "folders.json"
325
+ runner = CliRunner()
326
+
327
+ result = runner.invoke(
328
+ cli,
329
+ ["bookmarks", "folders", "--json", "--output", str(output_path)],
330
+ )
331
+
332
+ assert result.exit_code == 0
333
+ payload = json.loads(result.output)
334
+ assert payload["ok"] is True
335
+ assert payload["data"][0]["id"] == "f1"
336
+
337
+ saved = json.loads(output_path.read_text(encoding="utf-8"))
338
+ assert saved == [
339
+ {"id": "f1", "name": "Reading"},
340
+ {"id": "f2", "name": "Research"},
341
+ ]
342
+
343
+
256
344
  def test_cli_whoami_command(monkeypatch) -> None:
257
345
  from twitter_cli.models import UserProfile
258
346
 
@@ -0,0 +1,88 @@
1
+ """Tests for twitter_cli.filter module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from twitter_cli.filter import filter_tweets, score_tweet
6
+
7
+
8
+ def test_filter_tweets_does_not_mutate_input(tweet_factory) -> None:
9
+ tweet = tweet_factory("1", score=0.0)
10
+ output = filter_tweets([tweet], {"mode": "all", "weights": {}})
11
+
12
+ assert tweet.score == 0.0
13
+ assert output[0].score > 0.0
14
+ assert output[0] is not tweet
15
+
16
+
17
+ def test_filter_tweets_applies_language_and_retweet_filters(tweet_factory) -> None:
18
+ tweets = [
19
+ tweet_factory("1", lang="en", is_retweet=False),
20
+ tweet_factory("2", lang="zh", is_retweet=False),
21
+ tweet_factory("3", lang="en", is_retweet=True),
22
+ ]
23
+ output = filter_tweets(
24
+ tweets,
25
+ {
26
+ "mode": "all",
27
+ "lang": ["en"],
28
+ "excludeRetweets": True,
29
+ "weights": {},
30
+ },
31
+ )
32
+
33
+ assert [tweet.id for tweet in output] == ["1"]
34
+
35
+
36
+ def test_filter_topn_mode(tweet_factory) -> None:
37
+ tweets = [tweet_factory(str(i)) for i in range(10)]
38
+ output = filter_tweets(tweets, {"mode": "topN", "topN": 3})
39
+ assert len(output) == 3
40
+
41
+
42
+ def test_filter_topn_default(tweet_factory) -> None:
43
+ """Default topN is 20, so 5 tweets should all be returned."""
44
+ tweets = [tweet_factory(str(i)) for i in range(5)]
45
+ output = filter_tweets(tweets, {"mode": "topN"})
46
+ assert len(output) == 5
47
+
48
+
49
+ def test_filter_score_mode(tweet_factory) -> None:
50
+ from twitter_cli.models import Metrics
51
+
52
+ tweets = [
53
+ tweet_factory("high", metrics=Metrics(likes=1000, retweets=500, replies=200, views=100000, bookmarks=50)),
54
+ tweet_factory("low", metrics=Metrics(likes=0, retweets=0, replies=0, views=1, bookmarks=0)),
55
+ ]
56
+ output = filter_tweets(tweets, {"mode": "score", "minScore": 100.0})
57
+ assert len(output) == 1
58
+ assert output[0].id == "high"
59
+
60
+
61
+ def test_filter_empty_input() -> None:
62
+ output = filter_tweets([], {"mode": "all"})
63
+ assert output == []
64
+
65
+
66
+ def test_score_tweet_basic(tweet_factory) -> None:
67
+ tweet = tweet_factory("1")
68
+ score = score_tweet(tweet)
69
+ assert isinstance(score, float)
70
+ assert score > 0
71
+
72
+
73
+ def test_score_tweet_custom_weights(tweet_factory) -> None:
74
+ tweet = tweet_factory("1")
75
+ weights = {"likes": 0, "retweets": 0, "replies": 0, "bookmarks": 0, "views_log": 0}
76
+ assert score_tweet(tweet, weights) == 0.0
77
+
78
+
79
+ def test_filter_all_mode_sorts_by_score(tweet_factory) -> None:
80
+ from twitter_cli.models import Metrics
81
+
82
+ tweets = [
83
+ tweet_factory("low", metrics=Metrics(likes=1)),
84
+ tweet_factory("high", metrics=Metrics(likes=100)),
85
+ ]
86
+ output = filter_tweets(tweets, {"mode": "all"})
87
+ assert output[0].id == "high"
88
+ assert output[1].id == "low"
@@ -0,0 +1,147 @@
1
+ """Tests for twitter_cli.output module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ import click
8
+ import pytest
9
+ import yaml
10
+
11
+ from twitter_cli.output import (
12
+ default_structured_format,
13
+ emit_structured,
14
+ ensure_utf8_streams,
15
+ error_payload,
16
+ success_payload,
17
+ use_rich_output,
18
+ )
19
+
20
+
21
+ # ── ensure_utf8_streams ─────────────────────────────────────────────────
22
+
23
+
24
+ def test_ensure_utf8_streams_no_error() -> None:
25
+ """ensure_utf8_streams should not raise on any platform."""
26
+ ensure_utf8_streams()
27
+
28
+
29
+ # ── success_payload / error_payload ──────────────────────────────────────
30
+
31
+
32
+ def test_success_payload_structure() -> None:
33
+ payload = success_payload({"key": "value"})
34
+ assert payload["ok"] is True
35
+ assert payload["schema_version"] == "1"
36
+ assert payload["data"] == {"key": "value"}
37
+
38
+
39
+ def test_success_payload_with_list() -> None:
40
+ payload = success_payload([1, 2, 3])
41
+ assert payload["ok"] is True
42
+ assert payload["data"] == [1, 2, 3]
43
+
44
+
45
+ def test_error_payload_structure() -> None:
46
+ payload = error_payload("not_found", "User not found")
47
+ assert payload["ok"] is False
48
+ assert payload["schema_version"] == "1"
49
+ assert payload["error"]["code"] == "not_found"
50
+ assert payload["error"]["message"] == "User not found"
51
+ assert "details" not in payload["error"]
52
+
53
+
54
+ def test_error_payload_with_details() -> None:
55
+ payload = error_payload("api_error", "oops", details={"id": "123"})
56
+ assert payload["error"]["details"] == {"id": "123"}
57
+
58
+
59
+ # ── default_structured_format ────────────────────────────────────────────
60
+
61
+
62
+ def test_format_json_flag() -> None:
63
+ assert default_structured_format(as_json=True, as_yaml=False) == "json"
64
+
65
+
66
+ def test_format_yaml_flag() -> None:
67
+ assert default_structured_format(as_json=False, as_yaml=True) == "yaml"
68
+
69
+
70
+ def test_format_both_flags_raises() -> None:
71
+ with pytest.raises(click.UsageError):
72
+ default_structured_format(as_json=True, as_yaml=True)
73
+
74
+
75
+ def test_format_env_yaml(monkeypatch) -> None:
76
+ monkeypatch.setenv("OUTPUT", "yaml")
77
+ assert default_structured_format(as_json=False, as_yaml=False) == "yaml"
78
+
79
+
80
+ def test_format_env_json(monkeypatch) -> None:
81
+ monkeypatch.setenv("OUTPUT", "json")
82
+ assert default_structured_format(as_json=False, as_yaml=False) == "json"
83
+
84
+
85
+ def test_format_env_rich(monkeypatch) -> None:
86
+ monkeypatch.setenv("OUTPUT", "rich")
87
+ assert default_structured_format(as_json=False, as_yaml=False) is None
88
+
89
+
90
+ def test_format_auto_non_tty(monkeypatch) -> None:
91
+ monkeypatch.setenv("OUTPUT", "auto")
92
+ monkeypatch.setattr("sys.stdout", type("FakeStdout", (), {"isatty": lambda self: False})())
93
+ assert default_structured_format(as_json=False, as_yaml=False) == "yaml"
94
+
95
+
96
+ # ── use_rich_output ──────────────────────────────────────────────────────
97
+
98
+
99
+ def test_use_rich_when_no_structured(monkeypatch) -> None:
100
+ monkeypatch.setenv("OUTPUT", "rich")
101
+ assert use_rich_output(as_json=False, as_yaml=False) is True
102
+
103
+
104
+ def test_no_rich_when_json() -> None:
105
+ assert use_rich_output(as_json=True, as_yaml=False) is False
106
+
107
+
108
+ def test_no_rich_when_compact(monkeypatch) -> None:
109
+ monkeypatch.setenv("OUTPUT", "rich")
110
+ assert use_rich_output(as_json=False, as_yaml=False, compact=True) is False
111
+
112
+
113
+ # ── emit_structured ──────────────────────────────────────────────────────
114
+
115
+
116
+ def test_emit_structured_json(capsys) -> None:
117
+ result = emit_structured({"key": "val"}, as_json=True, as_yaml=False)
118
+ assert result is True
119
+ captured = capsys.readouterr()
120
+ parsed = json.loads(captured.out)
121
+ assert parsed["ok"] is True
122
+ assert parsed["data"]["key"] == "val"
123
+
124
+
125
+ def test_emit_structured_yaml(capsys) -> None:
126
+ result = emit_structured({"key": "val"}, as_json=False, as_yaml=True)
127
+ assert result is True
128
+ captured = capsys.readouterr()
129
+ parsed = yaml.safe_load(captured.out)
130
+ assert parsed["ok"] is True
131
+ assert parsed["data"]["key"] == "val"
132
+
133
+
134
+ def test_emit_structured_returns_false_when_rich(monkeypatch) -> None:
135
+ monkeypatch.setenv("OUTPUT", "rich")
136
+ result = emit_structured({"key": "val"}, as_json=False, as_yaml=False)
137
+ assert result is False
138
+
139
+
140
+ def test_emit_structured_wraps_already_wrapped_payload(capsys) -> None:
141
+ """If data is already in the agent schema, it should not be double-wrapped."""
142
+ already_wrapped = {"ok": True, "schema_version": "1", "data": "hello"}
143
+ emit_structured(already_wrapped, as_json=True, as_yaml=False)
144
+ captured = capsys.readouterr()
145
+ parsed = json.loads(captured.out)
146
+ assert parsed["data"] == "hello"
147
+ assert "data" not in str(parsed.get("data", {}) if isinstance(parsed.get("data"), dict) else "")
@@ -0,0 +1,73 @@
1
+ """Tests for twitter_cli.timeutil module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from twitter_cli.timeutil import format_iso8601, format_local_time, format_relative_time
6
+
7
+
8
+ SAMPLE_TIMESTAMP = "Sat Mar 08 12:00:00 +0000 2026"
9
+
10
+
11
+ # ── format_local_time ────────────────────────────────────────────────────
12
+
13
+
14
+ def test_format_local_time_valid() -> None:
15
+ result = format_local_time(SAMPLE_TIMESTAMP)
16
+ # Should be in YYYY-MM-DD HH:MM format (local timezone)
17
+ assert result.startswith("2026-03-")
18
+ assert ":" in result
19
+
20
+
21
+ def test_format_local_time_empty() -> None:
22
+ assert format_local_time("") == ""
23
+
24
+
25
+ def test_format_local_time_invalid() -> None:
26
+ assert format_local_time("not a date") == "not a date"
27
+
28
+
29
+ # ── format_relative_time ─────────────────────────────────────────────────
30
+
31
+
32
+ def test_format_relative_time_old() -> None:
33
+ # A timestamp from 2020 should show years ago
34
+ old_ts = "Sat Jan 01 00:00:00 +0000 2020"
35
+ result = format_relative_time(old_ts)
36
+ assert result.endswith("ago")
37
+ assert "y" in result or "mo" in result or "d" in result
38
+
39
+
40
+ def test_format_relative_time_empty() -> None:
41
+ assert format_relative_time("") == ""
42
+
43
+
44
+ def test_format_relative_time_invalid() -> None:
45
+ assert format_relative_time("garbage") == "garbage"
46
+
47
+
48
+ # ── format_iso8601 ───────────────────────────────────────────────────────
49
+
50
+
51
+ def test_format_iso8601_valid() -> None:
52
+ result = format_iso8601(SAMPLE_TIMESTAMP)
53
+ assert result.startswith("2026-03-08T12:00:00")
54
+ assert "+00:00" in result or "Z" in result
55
+
56
+
57
+ def test_format_iso8601_empty() -> None:
58
+ assert format_iso8601("") == ""
59
+
60
+
61
+ def test_format_iso8601_invalid() -> None:
62
+ assert format_iso8601("not a date") == "not a date"
63
+
64
+
65
+ def test_format_iso8601_roundtrip() -> None:
66
+ """ISO 8601 output should be parseable by datetime.fromisoformat."""
67
+ from datetime import datetime
68
+
69
+ result = format_iso8601(SAMPLE_TIMESTAMP)
70
+ dt = datetime.fromisoformat(result)
71
+ assert dt.year == 2026
72
+ assert dt.month == 3
73
+ assert dt.day == 8
@@ -19,6 +19,7 @@ import sys
19
19
  from typing import Any, Dict, List, Optional, Tuple
20
20
 
21
21
  from .constants import BEARER_TOKEN, get_user_agent
22
+ from .exceptions import AuthenticationError
22
23
 
23
24
  logger = logging.getLogger(__name__)
24
25
 
@@ -65,6 +66,15 @@ def _diagnose_keychain_issues(diagnostics: List[str]) -> Optional[str]:
65
66
  " Fix: Open Keychain Access → search for \"<Browser> Safe Storage\" → Access Control → add your Terminal app.\n"
66
67
  " Or click \"Always Allow\" when the Keychain authorization popup appears."
67
68
  )
69
+ if sys.platform == "win32":
70
+ return (
71
+ "Windows DPAPI cookie decryption failed.\n"
72
+ " Possible causes:\n"
73
+ " 1. Chrome is running (locks the cookie database). Try closing Chrome first.\n"
74
+ " 2. browser_cookie3 may not support the latest Chrome cookie encryption format.\n"
75
+ " 3. If Chrome was running, admin privileges may be required for VSS shadowcopy.\n"
76
+ " Workaround: Set TWITTER_AUTH_TOKEN and TWITTER_CT0 environment variables manually."
77
+ )
68
78
  # Linux: gnome-keyring / SecretStorage issues
69
79
  return (
70
80
  "System keyring access failed — the cookie encryption key could not be retrieved.\n"
@@ -127,7 +137,7 @@ def verify_cookies(auth_token: str, ct0: str, cookie_string: Optional[str] = Non
127
137
  try:
128
138
  resp = session.get(url, headers=headers, timeout=5)
129
139
  if resp.status_code in (401, 403):
130
- raise RuntimeError(
140
+ raise AuthenticationError(
131
141
  "Cookie expired or invalid (HTTP %d). Please re-login to x.com in your browser." % resp.status_code
132
142
  )
133
143
  if resp.status_code == 200:
@@ -607,7 +617,7 @@ def get_cookies() -> Dict[str, str]:
607
617
  lines.append("Option 2: Make sure you are logged into x.com in your browser (Arc/Chrome/Edge/Firefox/Brave)")
608
618
  lines.append("")
609
619
  lines.append("Run 'twitter -v <command>' for debug diagnostics.")
610
- raise RuntimeError("\n".join(lines))
620
+ raise AuthenticationError("\n".join(lines))
611
621
 
612
622
  # Verify only for explicit auth failures; transient endpoint issues are tolerated.
613
623
  try: