返回 last30days-skill
test_truthsocial.py
根目录 / tests / test_truthsocial.py
1 """Tests for Truth Social source module."""
2 import unittest
3 from unittest.mock import patch, MagicMock
4
5 from lib import truthsocial
6
7
8 class TestStripHtml(unittest.TestCase):
9 """Test HTML tag stripping."""
10
11 def test_basic_paragraph(self):
12 self.assertEqual(truthsocial._strip_html("<p>Hello world</p>"), "Hello world")
13
14 def test_br_tags(self):
15 self.assertEqual(truthsocial._strip_html("Line 1<br>Line 2"), "Line 1\nLine 2")
16 self.assertEqual(truthsocial._strip_html("Line 1<br/>Line 2"), "Line 1\nLine 2")
17 self.assertEqual(truthsocial._strip_html("Line 1<br />Line 2"), "Line 1\nLine 2")
18
19 def test_nested_tags(self):
20 self.assertEqual(truthsocial._strip_html("<p>Hello <a href='#'>world</a></p>"), "Hello world")
21
22 def test_empty_string(self):
23 self.assertEqual(truthsocial._strip_html(""), "")
24
25 def test_no_tags(self):
26 self.assertEqual(truthsocial._strip_html("plain text"), "plain text")
27
28 def test_entities_unescaped(self):
29 self.assertEqual(truthsocial._strip_html("<p>&amp; test</p>"), "& test")
30 self.assertEqual(
31 truthsocial._strip_html(
32 "<p>We&#39;re &quot;winning&quot; on tariffs &amp; trade &gt; anyone thought</p>"
33 ),
34 'We\'re "winning" on tariffs & trade > anyone thought',
35 )
36
37 def test_escaped_markup_is_kept_as_text(self):
38 # Entities are decoded after tags are stripped, so an escaped tag in
39 # the post text survives as text instead of being removed.
40 self.assertEqual(
41 truthsocial._strip_html("<p>use &lt;b&gt; for bold</p>"),
42 "use <b> for bold",
43 )
44
45 def test_paragraphs_are_separated(self):
46 self.assertEqual(
47 truthsocial._strip_html("<p>First paragraph.</p><p>Second paragraph.</p>"),
48 "First paragraph.\nSecond paragraph.",
49 )
50 self.assertEqual(
51 truthsocial._strip_html('<p>One</p>\n<p class="x">Two</p>'),
52 "One\nTwo",
53 )
54
55
56 class TestExtractCoreSubject(unittest.TestCase):
57 """Test query preprocessing."""
58
59 def test_strips_question_prefix(self):
60 self.assertEqual(truthsocial._extract_core_subject("what are people saying about tariffs"), "tariffs")
61
62 def test_strips_noise_words(self):
63 self.assertEqual(truthsocial._extract_core_subject("latest trending crypto news"), "crypto")
64
65 def test_preserves_core_topic(self):
66 self.assertEqual(truthsocial._extract_core_subject("tariffs"), "tariffs")
67
68 def test_strips_trailing_punctuation(self):
69 self.assertEqual(truthsocial._extract_core_subject("what is bitcoin?"), "bitcoin")
70
71
72 class TestParseDate(unittest.TestCase):
73 """Test date parsing from Mastodon status."""
74
75 def test_iso_date(self):
76 self.assertEqual(truthsocial._parse_date({"created_at": "2026-03-09T12:00:00.000Z"}), "2026-03-09")
77
78 def test_missing_date(self):
79 self.assertIsNone(truthsocial._parse_date({}))
80
81 def test_short_date(self):
82 self.assertIsNone(truthsocial._parse_date({"created_at": "short"}))
83
84 def test_none_value(self):
85 self.assertIsNone(truthsocial._parse_date({"created_at": None}))
86
87
88 class TestDepthConfig(unittest.TestCase):
89 """Test depth configuration."""
90
91 def test_all_depths_exist(self):
92 self.assertIn("quick", truthsocial.DEPTH_CONFIG)
93 self.assertIn("default", truthsocial.DEPTH_CONFIG)
94 self.assertIn("deep", truthsocial.DEPTH_CONFIG)
95
96 def test_depth_ordering(self):
97 self.assertLess(truthsocial.DEPTH_CONFIG["quick"], truthsocial.DEPTH_CONFIG["default"])
98 self.assertLess(truthsocial.DEPTH_CONFIG["default"], truthsocial.DEPTH_CONFIG["deep"])
99
100
101 class TestSearchTruthSocial(unittest.TestCase):
102 """Test search function auth handling."""
103
104 def test_no_config_returns_error(self):
105 result = truthsocial.search_truthsocial("test", "2026-02-09", "2026-03-09")
106 self.assertEqual(result["statuses"], [])
107 self.assertIn("not configured", result["error"])
108
109 def test_empty_token_returns_error(self):
110 result = truthsocial.search_truthsocial(
111 "test", "2026-02-09", "2026-03-09",
112 config={"TRUTHSOCIAL_TOKEN": ""},
113 )
114 self.assertEqual(result["statuses"], [])
115 self.assertIn("not configured", result["error"])
116
117 @patch("lib.truthsocial.http.request")
118 def test_search_sends_browser_like_headers(self, mock_request):
119 """Regression for #909: Cloudflare 403s the skill's default
120 User-Agent regardless of token validity; the request must include
121 browser-like headers alongside Authorization."""
122 from lib import http as http_module
123 mock_request.return_value = {"statuses": []}
124 truthsocial.search_truthsocial(
125 "health policy", "2026-02-09", "2026-03-09",
126 config={"TRUTHSOCIAL_TOKEN": "valid_token"},
127 )
128 _, kwargs = mock_request.call_args
129 headers = kwargs["headers"]
130 self.assertEqual(headers["Authorization"], "Bearer valid_token")
131 self.assertEqual(headers["User-Agent"], http_module.BROWSER_USER_AGENT)
132 self.assertIn("Accept", headers)
133 self.assertIn("Accept-Language", headers)
134 self.assertEqual(headers["Referer"], "https://truthsocial.com/")
135
136 @patch("lib.truthsocial.http.request")
137 def test_401_returns_token_expired(self, mock_request):
138 from lib.http import HTTPError
139 mock_request.side_effect = HTTPError("Unauthorized", status_code=401)
140 result = truthsocial.search_truthsocial(
141 "test", "2026-02-09", "2026-03-09",
142 config={"TRUTHSOCIAL_TOKEN": "expired_token"},
143 )
144 self.assertEqual(result["statuses"], [])
145 self.assertIn("expired", result["error"])
146
147 @patch("lib.truthsocial.http.request")
148 def test_403_returns_access_denied(self, mock_request):
149 from lib.http import HTTPError
150 mock_request.side_effect = HTTPError("Forbidden", status_code=403)
151 result = truthsocial.search_truthsocial(
152 "test", "2026-02-09", "2026-03-09",
153 config={"TRUTHSOCIAL_TOKEN": "blocked_token"},
154 )
155 self.assertEqual(result["statuses"], [])
156 self.assertIn("Cloudflare", result["error"])
157
158 @patch("lib.truthsocial.http.request")
159 def test_429_returns_rate_limited(self, mock_request):
160 from lib.http import HTTPError
161 mock_request.side_effect = HTTPError("Too Many Requests", status_code=429)
162 result = truthsocial.search_truthsocial(
163 "test", "2026-02-09", "2026-03-09",
164 config={"TRUTHSOCIAL_TOKEN": "rate_limited_token"},
165 )
166 self.assertEqual(result["statuses"], [])
167 self.assertIn("rate limited", result["error"])
168
169 @patch("lib.truthsocial.http.request")
170 def test_successful_search(self, mock_request):
171 mock_request.return_value = {
172 "statuses": [
173 {
174 "content": "<p>Test post about tariffs</p>",
175 "created_at": "2026-03-09T12:00:00.000Z",
176 "url": "https://truthsocial.com/@user/123",
177 "account": {"acct": "user", "display_name": "Test User"},
178 "favourites_count": 10,
179 "reblogs_count": 5,
180 "replies_count": 3,
181 }
182 ]
183 }
184 result = truthsocial.search_truthsocial(
185 "tariffs", "2026-02-09", "2026-03-09",
186 config={"TRUTHSOCIAL_TOKEN": "valid_token"},
187 )
188 self.assertEqual(len(result["statuses"]), 1)
189 # Verify bearer token was passed
190 call_args = mock_request.call_args
191 self.assertEqual(call_args[1]["headers"]["Authorization"], "Bearer valid_token")
192
193
194 class TestParseTruthSocialResponse(unittest.TestCase):
195 """Test response parsing."""
196
197 def test_basic_post(self):
198 response = {
199 "statuses": [
200 {
201 "content": "<p>Hello from Truth Social</p>",
202 "created_at": "2026-03-09T12:00:00.000Z",
203 "url": "https://truthsocial.com/@testuser/456",
204 "account": {"acct": "testuser", "display_name": "Test User"},
205 "favourites_count": 100,
206 "reblogs_count": 50,
207 "replies_count": 25,
208 }
209 ]
210 }
211 items = truthsocial.parse_truthsocial_response(response)
212 self.assertEqual(len(items), 1)
213 item = items[0]
214 self.assertEqual(item["handle"], "testuser")
215 self.assertEqual(item["display_name"], "Test User")
216 self.assertEqual(item["text"], "Hello from Truth Social")
217 self.assertEqual(item["url"], "https://truthsocial.com/@testuser/456")
218 self.assertEqual(item["date"], "2026-03-09")
219 self.assertEqual(item["engagement"]["likes"], 100)
220 self.assertEqual(item["engagement"]["reposts"], 50)
221 self.assertEqual(item["engagement"]["replies"], 25)
222 self.assertGreater(item["relevance"], 0)
223
224 def test_empty_response(self):
225 items = truthsocial.parse_truthsocial_response({"statuses": []})
226 self.assertEqual(items, [])
227
228 def test_missing_fields(self):
229 response = {
230 "statuses": [
231 {
232 "content": "",
233 "account": {},
234 }
235 ]
236 }
237 items = truthsocial.parse_truthsocial_response(response)
238 self.assertEqual(len(items), 1)
239 self.assertEqual(items[0]["handle"], "")
240 self.assertEqual(items[0]["text"], "")
241 self.assertEqual(items[0]["engagement"]["likes"], 0)
242
243 def test_relevance_ordering(self):
244 response = {
245 "statuses": [
246 {"content": "<p>First</p>", "account": {"acct": "a"}, "favourites_count": 10, "reblogs_count": 0, "replies_count": 0},
247 {"content": "<p>Second</p>", "account": {"acct": "b"}, "favourites_count": 5, "reblogs_count": 0, "replies_count": 0},
248 {"content": "<p>Third</p>", "account": {"acct": "c"}, "favourites_count": 1, "reblogs_count": 0, "replies_count": 0},
249 ]
250 }
251 items = truthsocial.parse_truthsocial_response(response)
252 self.assertGreaterEqual(items[0]["relevance"], items[1]["relevance"])
253 self.assertGreaterEqual(items[1]["relevance"], items[2]["relevance"])
254
255 def test_html_stripping_in_parse(self):
256 response = {
257 "statuses": [
258 {
259 "content": "<p>Hello <a href='https://example.com'>@user</a> check this out<br/>New line</p>",
260 "account": {"acct": "poster"},
261 "favourites_count": 0,
262 "reblogs_count": 0,
263 "replies_count": 0,
264 }
265 ]
266 }
267 items = truthsocial.parse_truthsocial_response(response)
268 self.assertNotIn("<", items[0]["text"])
269 self.assertNotIn(">", items[0]["text"])
270
271 def test_parse_decodes_entities_and_paragraphs(self):
272 response = {
273 "statuses": [
274 {
275 "content": "<p>Tariffs &amp; trade</p><p>It&#39;s &quot;huge&quot;</p>",
276 "account": {"acct": "poster"},
277 }
278 ]
279 }
280 items = truthsocial.parse_truthsocial_response(response)
281 self.assertEqual(items[0]["text"], 'Tariffs & trade\nIt\'s "huge"')
282
283 if __name__ == "__main__":
284 unittest.main()
285
285 lines PYTHON