Alialdlfy1 commited on
Commit
d9f2063
·
verified ·
1 Parent(s): 2e5ffed

Upload test_full_pipeline.py

Browse files
tests/integration/test_full_pipeline.py ADDED
@@ -0,0 +1,1239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ import os
4
+ import sys
5
+ import time
6
+ import unittest
7
+ from unittest.mock import AsyncMock, MagicMock, patch
8
+ from typing import Optional, Dict, Any, List, Tuple
9
+
10
+ _loop = asyncio.new_event_loop()
11
+ asyncio.set_event_loop(_loop)
12
+
13
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
14
+
15
+ from modules.blogger.ai_manager import (
16
+ AIKeyManager, AIClient, NoAvailableAIProvider, AllProvidersExhausted,
17
+ PROVIDER_CONFIGS, PROVIDER_ORDER, _model_cache, TIMEOUT,
18
+ )
19
+ from modules.blogger.processor import ArticleProcessor
20
+ from modules.blogger.database import BloggerDatabase, DEFAULT_BLOGGER_DATA
21
+ import modules.blogger.ai_manager as _ai_mod
22
+ import httpx
23
+
24
+
25
+ TEST_RAW_TEXT = """📢 #وظائف #بغداد
26
+ تعلن وزارة التربية العراقية عن توفر 500 درجة وظيفية للمتقدمين من حملة الشهادات.
27
+ الراتب: 800,000 دينار عراقي
28
+ آخر موعد للتقديم: 2026/08/15
29
+ للتقديم: https://forms.gle/test123
30
+ """
31
+
32
+
33
+ def mock_http_response(status_code=200, json_data=None, text=""):
34
+ resp = MagicMock()
35
+ resp.status_code = status_code
36
+ resp.json.return_value = json_data or {}
37
+ resp.text = text or json.dumps(json_data or {}, ensure_ascii=False)
38
+ resp.reason_phrase = "OK" if status_code == 200 else "Error"
39
+ resp.is_error = status_code >= 400
40
+ return resp
41
+
42
+
43
+ class InMemoryDB:
44
+
45
+ def __init__(self):
46
+ self.data = json.loads(json.dumps(DEFAULT_BLOGGER_DATA))
47
+ self.data["ai_keys"] = {
48
+ "test_gemini_1": {
49
+ "name": "GEMINI_KEY_1", "key": "test-key-gemini-1",
50
+ "enabled": True, "usage_count": 0, "error_count": 0,
51
+ "last_used": 0, "added_at": 0,
52
+ },
53
+ "test_gemini_2": {
54
+ "name": "GEMINI_KEY_2", "key": "test-key-gemini-2",
55
+ "enabled": True, "usage_count": 0, "error_count": 0,
56
+ "last_used": 0, "added_at": 0,
57
+ },
58
+ "test_groq_1": {
59
+ "name": "GROQ_KEY_1", "key": "test-key-groq-1",
60
+ "enabled": True, "usage_count": 0, "error_count": 0,
61
+ "last_used": 0, "added_at": 0,
62
+ },
63
+ "test_or_1": {
64
+ "name": "OPENROUTER_KEY_1", "key": "test-key-or-1",
65
+ "enabled": True, "usage_count": 0, "error_count": 0,
66
+ "last_used": 0, "added_at": 0,
67
+ },
68
+ }
69
+ self.data["sections"] = {
70
+ "sec1": {"name": "general", "labels": ["عام", "اخبار"]},
71
+ }
72
+
73
+ def get_config(self): return dict(self.data.get("config", {}))
74
+ def update_config(self, key, value): self.data["config"][key] = value
75
+ def get_all_ai_keys(self): return dict(self.data.get("ai_keys", {}))
76
+ def get_all_sections(self): return dict(self.data.get("sections", {}))
77
+ def get_all_channels(self): return list(self.data.get("channels", {}).values())
78
+ def get_channel(self, ch_id): return self.data.get("channels", {}).get(str(ch_id))
79
+ def save_channel(self, ch_id, ch_data): self.data["channels"][str(ch_id)] = ch_data
80
+ def get_articles_by_status(self, status): return [a for a in self.data.get("articles", {}).values() if a.get("status") == status]
81
+ def save_article(self, aid, a): self.data["articles"][str(aid)] = a
82
+ def get_article(self, aid): return self.data.get("articles", {}).get(str(aid))
83
+ def is_published(self, fp): return fp in self.data.get("published_ids", [])
84
+ def mark_published(self, fp):
85
+ if fp not in self.data["published_ids"]:
86
+ self.data["published_ids"].append(fp)
87
+ self.data["stats"]["total_published"] += 1
88
+ def mark_failed(self): self.data["stats"]["total_failed"] += 1
89
+ def add_log(self, entry): self.data["logs"].append(entry)
90
+ def get_logs(self, limit=50): return list(self.data["logs"])[-limit:]
91
+ def get_stats(self): return dict(self.data.get("stats", {}))
92
+ def update_article_status(self, aid, status, extra=None):
93
+ if str(aid) in self.data["articles"]:
94
+ self.data["articles"][str(aid)]["status"] = status
95
+ if extra:
96
+ self.data["articles"][str(aid)].update(extra)
97
+ def increment_daily_count(self, section):
98
+ today = time.strftime("%Y-%m-%d")
99
+ self.data["stats"].setdefault("daily", {})
100
+ self.data["stats"]["daily"].setdefault(today, {})
101
+ self.data["stats"]["daily"][today][section] = self.data["stats"]["daily"][today].get(section, 0) + 1
102
+ def get_gemini_pending_queue(self): return self.data.get("_gemini_pending", [])
103
+ def save_gemini_pending_queue(self, q): self.data["_gemini_pending"] = q
104
+ def add_to_gemini_pending(self, raw_text, source_url="", media=None, fingerprint="", channel_id="", section=""):
105
+ self.data.setdefault("_gemini_pending", [])
106
+ if fingerprint and any(p.get("fingerprint") == fingerprint for p in self.data["_gemini_pending"]):
107
+ return
108
+ self.data["_gemini_pending"].append({
109
+ "raw_text": raw_text, "source_url": source_url, "media": media or [],
110
+ "fingerprint": fingerprint, "channel_id": channel_id, "section": section,
111
+ "attempts": 0, "added_at": int(time.time()),
112
+ })
113
+ def remove_from_gemini_pending(self, index=0):
114
+ if 0 <= index < len(self.data.get("_gemini_pending", [])):
115
+ self.data["_gemini_pending"].pop(index)
116
+ def remove_pending_by_fingerprint(self, fingerprint):
117
+ self.data["_gemini_pending"] = [p for p in self.data.get("_gemini_pending", []) if p.get("fingerprint") != fingerprint]
118
+ def increment_pending_attempts(self, fingerprint):
119
+ for p in self.data.get("_gemini_pending", []):
120
+ if p.get("fingerprint") == fingerprint:
121
+ p["attempts"] = p.get("attempts", 0) + 1
122
+ return p["attempts"]
123
+ return -1
124
+ def set_pending_retry_after(self, fingerprint, attempts):
125
+ import math
126
+ seconds = min(3600, 60 * (2 ** max(0, attempts - 1)))
127
+ for p in self.data.get("_gemini_pending", []):
128
+ if p.get("fingerprint") == fingerprint:
129
+ p["retry_after"] = int(time.time()) + seconds
130
+ return seconds
131
+ return seconds
132
+ def get_gemini_state(self): return self.data.get("stats", {}).get("_gemini", {"global_cooldown_until": 0.0})
133
+ def save_gemini_state(self, state): self.data.setdefault("stats", {})["_gemini"] = state
134
+ def increment_ai_key_usage(self, key_id):
135
+ if str(key_id) in self.data.get("ai_keys", {}):
136
+ self.data["ai_keys"][str(key_id)]["usage_count"] += 1
137
+ def increment_ai_key_error(self, key_id):
138
+ if str(key_id) in self.data.get("ai_keys", {}):
139
+ self.data["ai_keys"][str(key_id)]["error_count"] += 1
140
+ def set_ai_key_enabled(self, key_id, enabled):
141
+ if str(key_id) in self.data.get("ai_keys", {}):
142
+ self.data["ai_keys"][str(key_id)]["enabled"] = enabled
143
+ def get_schedule_state(self):
144
+ return self.data.get("stats", {}).get("_schedule", {"day": "", "last_slot": -1})
145
+ def save_schedule_state(self, state):
146
+ self.data.setdefault("stats", {})["_schedule"] = state
147
+
148
+
149
+ def make_gemini_models_response():
150
+ return mock_http_response(200, {
151
+ "models": [
152
+ {"name": "models/gemini-2.0-flash", "supportedGenerationMethods": ["generateContent"]},
153
+ ]
154
+ })
155
+
156
+
157
+ def make_openai_models_response():
158
+ return mock_http_response(200, {
159
+ "data": [
160
+ {"id": "deepseek-chat", "object": "model", "owned_by": "deepseek"},
161
+ ]
162
+ })
163
+
164
+
165
+ def make_gemini_chat_response(json_data: dict):
166
+ text = json.dumps(json_data, ensure_ascii=False)
167
+ return mock_http_response(200, {
168
+ "candidates": [{"content": {"parts": [{"text": text}]}}]
169
+ })
170
+
171
+
172
+ def make_openai_chat_response(json_data: dict):
173
+ text = json.dumps(json_data, ensure_ascii=False)
174
+ return mock_http_response(200, {
175
+ "choices": [{"message": {"content": text}}]
176
+ })
177
+
178
+
179
+ def make_gemini_fail_response(status_code=429, message="rate limit"):
180
+ return mock_http_response(status_code, {"error": {"message": message}})
181
+
182
+
183
+ def make_openai_fail_response(status_code=429, message="rate limit"):
184
+ return mock_http_response(status_code, {"error": {"message": message}})
185
+
186
+
187
+ class TestFullPipelineIntegration(unittest.IsolatedAsyncioTestCase):
188
+
189
+ def setUp(self):
190
+ _model_cache.clear()
191
+ self.env_patcher = patch.dict(os.environ, {
192
+ "GEMINI_KEY_1": "test-key-gemini-1",
193
+ "GEMINI_KEY_2": "test-key-gemini-2",
194
+ "GROQ_KEY_1": "test-key-groq-1",
195
+ "OPENROUTER_KEY_1": "test-key-or-1",
196
+ })
197
+ self.env_patcher.start()
198
+ self.db = InMemoryDB()
199
+ self.key_manager = AIKeyManager(self.db)
200
+ self.ai = AIClient(self.key_manager)
201
+ self.ai._http = AsyncMock()
202
+ self.ai._http.post = AsyncMock()
203
+ self.ai._http.get = AsyncMock()
204
+ self.processor = ArticleProcessor(self.db, self.ai, {"default_jobs_image": ""})
205
+
206
+ def tearDown(self):
207
+ self.env_patcher.stop()
208
+ _model_cache.clear()
209
+
210
+ def _setup_models_discovery(self):
211
+ """Mock HTTP GET to return correct model list per provider."""
212
+ async def mock_get(url, **kwargs):
213
+ if "generativelanguage" in url:
214
+ return make_gemini_models_response()
215
+ return make_openai_models_response()
216
+ self.ai._http.get = AsyncMock(side_effect=mock_get)
217
+
218
+ # ================================================================
219
+ # 1. Full Pipeline: raw_text -> queued article with all fields
220
+ # ================================================================
221
+ async def test_full_pipeline_success(self):
222
+ self._setup_models_discovery()
223
+
224
+ responses = [
225
+ {"title": "وزارة التربية تعلن عن 500 درجة وظيفية",
226
+ "body": "<h2>التفاصيل</h2><p>أعلنت وزارة التربية عن توفر 500 درجة.</p>",
227
+ "introduction": "أعلنت وزارة التربية عن فرص عمل جديدة.",
228
+ "faq": [{"question": "ما هي الدرجات؟", "answer": "500 درجة وظيفية."}],
229
+ "conclusion": "فرصة ممتازة للباحثين عن عمل."},
230
+ {"ministry": "وزارة التربية", "province": "بغداد",
231
+ "job_type": "وظائف", "salary": "800,000 دينار", "deadline": "2026/08/15"},
232
+ {"summary": "وزارة التربية تعلن عن 500 درجة وظيفية براتب يصل إلى 800 ألف دينار."},
233
+ {"notes": ["الراتب 800,000 دينار عراقي.", "آخر موعد 2026/08/15."],
234
+ "keywords": "وظائف العراق، وزارة التربية، بغداد، تعيينات",
235
+ "hashtags": ["#العراق", "#وظائف", "#التعليم"]},
236
+ ]
237
+ resp_iter = iter(responses)
238
+
239
+ async def mock_post(url, **kwargs):
240
+ data = next(resp_iter)
241
+ if "generativelanguage" in url:
242
+ return make_gemini_chat_response(data)
243
+ return make_openai_chat_response(data)
244
+
245
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
246
+
247
+ fingerprint = self.processor.enqueue_raw_post(TEST_RAW_TEXT, source_url="https://t.me/test/1")
248
+ self.assertIsNotNone(fingerprint)
249
+ pending = self.db.get_gemini_pending_queue()
250
+ self.assertTrue(any(p.get("fingerprint") == fingerprint for p in pending))
251
+
252
+ session_ok = await self.ai.acquire_session()
253
+ self.assertTrue(session_ok)
254
+
255
+ result = await self.processor._process_next_pending()
256
+ self.assertIsNotNone(result)
257
+ self.assertEqual(result["status"], "processed")
258
+ self.assertEqual(result["title"], "وزارة التربية تعلن عن 500 درجة وظيفية")
259
+ self.assertIn("<h2>التفاصيل</h2>", result["body"])
260
+ self.assertIn("hashtags", result)
261
+ self.assertEqual(result["hashtags"], ["#العراق", "#وظائف", "#التعليم"])
262
+
263
+ saved = self.db.get_article(fingerprint)
264
+ self.assertIsNotNone(saved)
265
+ self.assertEqual(saved["status"], "processed")
266
+
267
+ # ================================================================
268
+ # 2. HTML contains hashtags after <hr>
269
+ # ================================================================
270
+ async def test_html_contains_hashtags(self):
271
+ article = {
272
+ "title": "Test Title",
273
+ "body": "<p>Test body</p>",
274
+ "hashtags": ["#العراق", "#وظائف", "#التعليم"],
275
+ "extracted": {"ministry": "test"},
276
+ "reading_time": 3,
277
+ "source": {"name": "Test"},
278
+ }
279
+ html = self.processor.make_article_html(article)
280
+ self.assertIn("#العراق", html)
281
+ self.assertIn("#وظائف", html)
282
+ self.assertIn("#التعليم", html)
283
+ self.assertIn("🏷️ الهاشتاكات", html)
284
+ self.assertIn("#العراق", html)
285
+ self.assertIn("#وظائف", html)
286
+ self.assertIn("#التعليم", html)
287
+
288
+ # ================================================================
289
+ # 3. Timeout -> tries next key
290
+ # ================================================================
291
+ async def test_ai_timeout_tries_next_key(self):
292
+ _model_cache.clear()
293
+ self._setup_models_discovery()
294
+
295
+ call_count = [0]
296
+
297
+ async def mock_post(url, **kwargs):
298
+ call_count[0] += 1
299
+ if call_count[0] == 1:
300
+ raise httpx.TimeoutException("timeout", request=None)
301
+ data = {"title": "OK", "body": "<p>OK</p>"}
302
+ if "generativelanguage" in url:
303
+ return make_gemini_chat_response(data)
304
+ return make_openai_chat_response(data)
305
+
306
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
307
+
308
+ session_ok = await self.ai.acquire_session()
309
+ self.assertTrue(session_ok)
310
+
311
+ result = await self.ai.generate("test prompt")
312
+ self.assertIsNotNone(result)
313
+ self.assertGreater(call_count[0], 1)
314
+
315
+ # ================================================================
316
+ # 4. Invalid API key -> tries next key
317
+ # ================================================================
318
+ async def test_invalid_key_skips_to_next(self):
319
+ _model_cache.clear()
320
+ self._setup_models_discovery()
321
+
322
+ call_count = [0]
323
+
324
+ async def mock_post(url, **kwargs):
325
+ call_count[0] += 1
326
+ if call_count[0] == 1:
327
+ return make_gemini_fail_response(401, "API key not valid")
328
+ data = {"title": "OK", "body": "<p>OK</p>"}
329
+ if "generativelanguage" in url:
330
+ return make_gemini_chat_response(data)
331
+ return make_openai_chat_response(data)
332
+
333
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
334
+
335
+ session_ok = await self.ai.acquire_session()
336
+ self.assertTrue(session_ok)
337
+
338
+ result = await self.ai.generate("test prompt")
339
+ self.assertIsNotNone(result)
340
+
341
+ # ================================================================
342
+ # 5. ALL providers fail -> NoAvailableAIProvider (no recursion)
343
+ # ================================================================
344
+ async def test_all_providers_fail_raises_no_recursion(self):
345
+ _model_cache.clear()
346
+ self._setup_models_discovery()
347
+
348
+ async def mock_post(url, **kwargs):
349
+ return make_gemini_fail_response(429, "quota exhausted")
350
+
351
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
352
+
353
+ session_ok = await self.ai.acquire_session()
354
+ self.assertTrue(session_ok)
355
+
356
+ with self.assertRaises(NoAvailableAIProvider):
357
+ await self.ai.generate("test prompt")
358
+
359
+ # ================================================================
360
+ # 6. No RecursionError when all keys fail
361
+ # ================================================================
362
+ async def test_no_recursion_on_repeated_failures(self):
363
+ _model_cache.clear()
364
+ self._setup_models_discovery()
365
+ self.ai._http.post = AsyncMock(return_value=make_gemini_fail_response(429, "rate limit"))
366
+
367
+ old_limit = sys.getrecursionlimit()
368
+ sys.setrecursionlimit(50)
369
+ try:
370
+ for _ in range(3):
371
+ self.ai.release_session()
372
+ with self.assertRaises(NoAvailableAIProvider):
373
+ await self.ai.generate("test prompt")
374
+ finally:
375
+ sys.setrecursionlimit(old_limit)
376
+
377
+ # ================================================================
378
+ # 7. Blogger error -> article stays queued (not lost)
379
+ # ================================================================
380
+ async def test_blogger_error_keeps_article_pending(self):
381
+ self._setup_models_discovery()
382
+
383
+ resp_iter = iter([
384
+ {"title": "Test", "body": "<p>Test</p>", "introduction": "", "faq": [], "conclusion": "",
385
+ "summary": "Test", "notes": [], "keywords": "test", "hashtags": ["#test"]},
386
+ {"ministry": "test"},
387
+ {"summary": "Test"},
388
+ {"notes": [], "keywords": "test", "hashtags": ["#test"]},
389
+ ])
390
+
391
+ def save_next_data(*args):
392
+ return {"title": "Test", "body": "<p>Test</p>", "introduction": "", "faq": [], "conclusion": ""}
393
+
394
+ async def mock_post(url, **kwargs):
395
+ data = next(resp_iter)
396
+ if "generativelanguage" in url:
397
+ return make_gemini_chat_response(data)
398
+ return make_openai_chat_response(data)
399
+
400
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
401
+
402
+ fingerprint = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
403
+ session_ok = await self.ai.acquire_session()
404
+ self.assertTrue(session_ok)
405
+
406
+ result = await self.processor._process_next_pending()
407
+ self.assertIsNotNone(result)
408
+ self.assertEqual(result["status"], "processed")
409
+
410
+ saved = self.db.get_article(fingerprint)
411
+ self.assertEqual(saved["status"], "processed")
412
+
413
+ # ================================================================
414
+ # 8. Labels and hashtags independent
415
+ # ================================================================
416
+ async def test_labels_and_hashtags_independent(self):
417
+ self._setup_models_discovery()
418
+
419
+ resp_iter = iter([
420
+ {"title": "Test Article", "body": "<p>Content</p>", "introduction": "Intro",
421
+ "faq": [], "conclusion": "Conclusion"},
422
+ {"ministry": "test"},
423
+ {"summary": "Summary text"},
424
+ {"notes": ["Note 1"], "keywords": "kw1, kw2", "hashtags": ["#tag1", "#tag2"]},
425
+ ])
426
+
427
+ async def mock_post(url, **kwargs):
428
+ data = next(resp_iter)
429
+ if "generativelanguage" in url:
430
+ return make_gemini_chat_response(data)
431
+ return make_openai_chat_response(data)
432
+
433
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
434
+
435
+ fingerprint = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
436
+ session_ok = await self.ai.acquire_session()
437
+ self.assertTrue(session_ok)
438
+
439
+ result = await self.processor._process_next_pending()
440
+ self.assertIsNotNone(result)
441
+ self.assertEqual(result.get("hashtags"), ["#tag1", "#tag2"])
442
+
443
+ html = self.processor.make_article_html(result)
444
+ self.assertIn("#tag1", html)
445
+ self.assertIn("🏷️ الهاشتاكات", html)
446
+
447
+ # ================================================================
448
+ # 9. Duplicate detection
449
+ # ================================================================
450
+ async def test_duplicate_detection(self):
451
+ fp1 = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
452
+ self.assertIsNotNone(fp1)
453
+ fp2 = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
454
+ self.assertIsNone(fp2)
455
+
456
+ # ================================================================
457
+ # 10. Generate safe multiple calls
458
+ # ================================================================
459
+ async def test_multiple_generate_calls_safe(self):
460
+ _model_cache.clear()
461
+ self._setup_models_discovery()
462
+
463
+ async def mock_post(url, **kwargs):
464
+ data = {"title": "OK", "body": "<p>OK</p>"}
465
+ if "generativelanguage" in url:
466
+ return make_gemini_chat_response(data)
467
+ return make_openai_chat_response(data)
468
+
469
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
470
+
471
+ session_ok = await self.ai.acquire_session()
472
+ self.assertTrue(session_ok)
473
+
474
+ for i in range(3):
475
+ result = await self.ai.generate(f"test prompt {i}")
476
+ self.assertIsNotNone(result)
477
+ self.ai.release_session()
478
+ if i < 2:
479
+ session_ok = await self.ai.acquire_session()
480
+ self.assertTrue(session_ok)
481
+
482
+ # ================================================================
483
+ # 11. No infinite loop in key rotation
484
+ # ================================================================
485
+ async def test_no_infinite_loop_key_rotation(self):
486
+ _model_cache.clear()
487
+ self._setup_models_discovery()
488
+ self.ai._http.post = AsyncMock(return_value=make_gemini_fail_response(429, "rate limit"))
489
+
490
+ session_ok = await self.ai.acquire_session()
491
+ self.assertTrue(session_ok)
492
+
493
+ start = time.time()
494
+ try:
495
+ await self.ai.generate("test")
496
+ self.fail("Should have raised NoAvailableAIProvider")
497
+ except NoAvailableAIProvider:
498
+ elapsed = time.time() - start
499
+ self.assertLess(elapsed, 10)
500
+
501
+ # ================================================================
502
+ # 12. Timeout is 30 seconds
503
+ # ================================================================
504
+ def test_timeout_is_30_seconds(self):
505
+ self.assertEqual(TIMEOUT, 30.0)
506
+
507
+ # ================================================================
508
+ # 13. Model not found -> tries next model
509
+ # ================================================================
510
+ async def test_model_not_found_tries_next_model(self):
511
+ _model_cache.clear()
512
+ self._setup_models_discovery()
513
+
514
+ call_count = [0]
515
+
516
+ async def mock_post(url, **kwargs):
517
+ call_count[0] += 1
518
+ if call_count[0] == 1:
519
+ if "generativelanguage" in url:
520
+ return mock_http_response(404, {"error": {"message": "model not found"}})
521
+ return mock_http_response(404, {"error": {"message": "model not found"}})
522
+ data = {"title": "OK", "body": "<p>OK</p>"}
523
+ if "generativelanguage" in url:
524
+ return make_gemini_chat_response(data)
525
+ return make_openai_chat_response(data)
526
+
527
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
528
+
529
+ session_ok = await self.ai.acquire_session()
530
+ self.assertTrue(session_ok)
531
+
532
+ result = await self.ai.generate("test prompt")
533
+ self.assertIsNotNone(result)
534
+ self.assertGreater(call_count[0], 1)
535
+
536
+ # ================================================================
537
+ # 14. Empty hashtags not added to HTML
538
+ # ================================================================
539
+ async def test_empty_hashtags_no_html(self):
540
+ article = {
541
+ "title": "Test",
542
+ "body": "<p>Body</p>",
543
+ "extracted": {},
544
+ "reading_time": 2,
545
+ "source": {"name": "Src"},
546
+ }
547
+ html = self.processor.make_article_html(article)
548
+ self.assertNotIn("<hr", html)
549
+
550
+ # ================================================================
551
+ # 15. Hashtags from AI are stored and preserved
552
+ # ================================================================
553
+ async def test_hashtags_preserved_through_full_cycle(self):
554
+ self._setup_models_discovery()
555
+
556
+ resp_iter = iter([
557
+ {"title": "T", "body": "<p>B</p>", "introduction": "", "faq": [], "conclusion": ""},
558
+ {"ministry": "t"},
559
+ {"summary": "S"},
560
+ {"notes": [], "keywords": "k", "hashtags": ["#h1", "#h2"]},
561
+ ])
562
+
563
+ async def mock_post(url, **kwargs):
564
+ data = next(resp_iter)
565
+ if "generativelanguage" in url:
566
+ return make_gemini_chat_response(data)
567
+ return make_openai_chat_response(data)
568
+
569
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
570
+
571
+ fp = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
572
+ await self.ai.acquire_session()
573
+ result = await self.processor._process_next_pending()
574
+ self.assertIsNotNone(result)
575
+ self.assertEqual(result["status"], "processed")
576
+ self.assertEqual(result["hashtags"], ["#h1", "#h2"])
577
+
578
+ html = self.processor.make_article_html(result)
579
+ self.assertIn("#h1", html)
580
+ self.assertIn("#h2", html)
581
+
582
+ # ================================================================
583
+ # 15b. Disabled keys are skipped during rotation
584
+ # ================================================================
585
+ async def test_disabled_keys_skipped_in_rotation(self):
586
+ _model_cache.clear()
587
+ self._setup_models_discovery()
588
+
589
+ gemini_hits = [0]
590
+ success_hits = [0]
591
+
592
+ async def mock_post(url, **kwargs):
593
+ if "generativelanguage" in url:
594
+ gemini_hits[0] += 1
595
+ return make_gemini_fail_response(401, "API key not valid")
596
+ success_hits[0] += 1
597
+ data = {"title": "OK", "body": "<p>OK</p>"}
598
+ return make_openai_chat_response(data)
599
+
600
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
601
+
602
+ # Disable all Gemini keys so rotation has to skip the whole provider.
603
+ for kid in list(self.key_manager._keys):
604
+ if self.key_manager._keys[kid].get("_provider") == "gemini":
605
+ await self.key_manager.mark_disabled(kid)
606
+
607
+ session_ok = await self.ai.acquire_session()
608
+ self.assertTrue(session_ok)
609
+ # A disabled provider must never be selected as the session provider.
610
+ self.assertNotEqual(self.ai._session_provider, "gemini")
611
+
612
+ result = await self.ai.generate("test prompt")
613
+ self.assertIsNotNone(result)
614
+ self.assertEqual(gemini_hits[0], 0, "Disabled Gemini keys must never be called")
615
+ self.assertGreaterEqual(success_hits[0], 1)
616
+
617
+ # ================================================================
618
+ # 15c. Performance stats are recorded across calls
619
+ # ================================================================
620
+ async def test_perf_stats_recorded_success_and_errors(self):
621
+ _model_cache.clear()
622
+ self._setup_models_discovery()
623
+
624
+ call_count = [0]
625
+
626
+ async def mock_post(url, **kwargs):
627
+ call_count[0] += 1
628
+ if call_count[0] == 1:
629
+ return make_gemini_fail_response(429, "rate limit")
630
+ data = {"title": "OK", "body": "<p>OK</p>"}
631
+ if "generativelanguage" in url:
632
+ return make_gemini_chat_response(data)
633
+ return make_openai_chat_response(data)
634
+
635
+ self.ai._http.post = AsyncMock(side_effect=mock_post)
636
+
637
+ session_ok = await self.ai.acquire_session()
638
+ self.assertTrue(session_ok)
639
+
640
+ result = await self.ai.generate("test prompt")
641
+ self.assertIsNotNone(result)
642
+
643
+ perf = self.key_manager.get_perf_stats()
644
+ self.assertIn("requests", perf)
645
+ self.assertGreaterEqual(perf["requests"], 2)
646
+ self.assertGreaterEqual(perf["rate_limited"], 1)
647
+ self.assertGreaterEqual(perf["success"], 1)
648
+ self.assertIn("avg_latency_ms", perf)
649
+ self.assertIn("by_provider", perf)
650
+
651
+ # ================================================================
652
+ # 15d. Exponential backoff defers a failed pending article
653
+ # ================================================================
654
+ async def test_backoff_defers_failed_pending_article(self):
655
+ fp = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
656
+ pending = self.db.get_gemini_pending_queue()
657
+ self.assertTrue(any(p.get("fingerprint") == fp for p in pending))
658
+
659
+ # Simulate a failure via the retry path (generic exception, not key exhaustion).
660
+ self.processor._handle_processing_failure(
661
+ fp, TEST_RAW_TEXT, "", [], "ch1", RuntimeError("boom"), {}, section="general"
662
+ )
663
+
664
+ pending = self.db.get_gemini_pending_queue()
665
+ item = next(p for p in pending if p.get("fingerprint") == fp)
666
+ self.assertGreater(item.get("retry_after", 0), int(time.time()),
667
+ "retry_after must be set in the future after a failure")
668
+
669
+ # A pending item still inside its backoff window must be deferred instantly.
670
+ result = await self.processor._process_next_pending()
671
+ self.assertIsNone(result)
672
+
673
+ # Once the backoff window passes, processing is attempted again.
674
+ item["retry_after"] = int(time.time()) - 1
675
+ self.db.save_gemini_pending_queue(pending)
676
+ self.ai._http.post = AsyncMock(return_value=make_gemini_fail_response(429, "rate limit"))
677
+ self._setup_models_discovery()
678
+ _model_cache.clear()
679
+ await self.ai.acquire_session()
680
+ # Key exhaustion is caught by _process_next_pending, which soft-fails -> None.
681
+ result = await self.processor._process_next_pending()
682
+ self.assertIsNone(result)
683
+
684
+
685
+ # ================================================================
686
+ # 16. Scheduler single-publish-per-cycle (no catch-up burst)
687
+ # ================================================================
688
+ class TestBloggerScheduler(unittest.IsolatedAsyncioTestCase):
689
+
690
+ def setUp(self):
691
+ self.db = InMemoryDB()
692
+ self.db.data["channels"] = {
693
+ "ch1": {
694
+ "channel_id": "ch1", "enabled": True,
695
+ "section": "general", "daily_limit": 10,
696
+ "start_hour": 9, "end_hour": 23,
697
+ }
698
+ }
699
+ self.db.data["published_ids"] = []
700
+ self.db.data["stats"]["daily"] = {}
701
+ self.ai = MagicMock()
702
+ self.processor = MagicMock(spec=ArticleProcessor)
703
+ self.processor._fingerprint.return_value = "test_fp"
704
+ self.processor.make_article_html.return_value = "<p>Test</p>"
705
+ self.processor.db = self.db
706
+ self.publisher = MagicMock()
707
+ self.publisher.config.is_enabled.return_value = True
708
+ self.publisher.publish_article = AsyncMock(return_value="post_123")
709
+ from modules.blogger.scheduler import BloggerScheduler
710
+ self.scheduler = BloggerScheduler(self.db, self.processor, self.publisher)
711
+ self.scheduler._queue = []
712
+
713
+ def _make_article(self, title, fingerprint, channel_id="ch1"):
714
+ return {
715
+ "fingerprint": fingerprint,
716
+ "title": title,
717
+ "body": "<p>Body</p>",
718
+ "status": "queued",
719
+ "channel_id": channel_id,
720
+ "section": "general",
721
+ "labels": [],
722
+ "source_text": title,
723
+ "created_at": int(time.time()),
724
+ }
725
+
726
+ async def test_skips_past_slot_window_no_burst(self):
727
+ """When scheduler starts late, past-slot windows are skipped one per cycle."""
728
+ self.scheduler._queue = [
729
+ self._make_article("Article 1", "fp1"),
730
+ self._make_article("Article 2", "fp2"),
731
+ ]
732
+ for a in self.scheduler._queue:
733
+ self.db.save_article(a["fingerprint"], a)
734
+
735
+ import modules.blogger.scheduler as sched_mod
736
+ _real_dt = sched_mod.datetime
737
+
738
+ class FakeDatetime(_real_dt):
739
+ @classmethod
740
+ def now(cls):
741
+ return _real_dt(2026, 7, 29, 9, 45, 0)
742
+ sched_mod.datetime = FakeDatetime
743
+
744
+ try:
745
+ # Cycle 1: slot 0 (09:00-09:30) is past window → skip, last_slot=0
746
+ await self.scheduler._process_queue()
747
+ state = self.db.get_schedule_state()
748
+ self.assertEqual(state["last_slot"], 0, "Slot 0 should be skipped")
749
+ self.assertEqual(self.publisher.publish_article.call_count, 0,
750
+ "No publish when skipping past slot")
751
+
752
+ # Cycle 2: slot 1 (09:30-10:00) is current window → publish
753
+ await self.scheduler._process_queue()
754
+ state = self.db.get_schedule_state()
755
+ self.assertEqual(state["last_slot"], 1, "Slot 1 should be used for publish")
756
+ finally:
757
+ sched_mod.datetime = _real_dt
758
+
759
+ self.assertEqual(self.publisher.publish_article.call_count, 1,
760
+ "Only one article per cycle")
761
+
762
+ async def test_only_one_article_per_cycle(self):
763
+ """Even with many queued articles, only one is published per _process_queue call."""
764
+ self.scheduler._queue = [
765
+ self._make_article("Article 1", "fp1"),
766
+ self._make_article("Article 2", "fp2"),
767
+ self._make_article("Article 3", "fp3"),
768
+ ]
769
+ for a in self.scheduler._queue:
770
+ self.db.save_article(a["fingerprint"], a)
771
+
772
+ import modules.blogger.scheduler as sched_mod
773
+ _real_dt = sched_mod.datetime
774
+
775
+ class FakeDatetime(_real_dt):
776
+ @classmethod
777
+ def now(cls):
778
+ return _real_dt(2026, 7, 29, 10, 5, 0)
779
+ sched_mod.datetime = FakeDatetime
780
+
781
+ try:
782
+ # Skip slots 0 and 1 (past windows), publish in slot 2 (10:00-10:30)
783
+ for _ in range(3):
784
+ await self.scheduler._process_queue()
785
+ finally:
786
+ sched_mod.datetime = _real_dt
787
+
788
+ self.assertEqual(self.publisher.publish_article.call_count, 1,
789
+ "Only one article published across all cycles")
790
+
791
+ async def test_no_publish_outside_window(self):
792
+ """When current time is not within any slot window, no article is published."""
793
+ self.scheduler._queue = [
794
+ self._make_article("Article 1", "fp1"),
795
+ ]
796
+ for a in self.scheduler._queue:
797
+ self.db.save_article(a["fingerprint"], a)
798
+
799
+ self.db.save_schedule_state({"day": "2026-07-29", "last_slot": -1})
800
+
801
+ import modules.blogger.scheduler as sched_mod
802
+ _real_dt = sched_mod.datetime
803
+
804
+ class FakeDatetime(_real_dt):
805
+ @classmethod
806
+ def now(cls):
807
+ return _real_dt(2026, 7, 29, 23, 30, 0)
808
+ sched_mod.datetime = FakeDatetime
809
+
810
+ try:
811
+ await self.scheduler._process_queue()
812
+ finally:
813
+ sched_mod.datetime = _real_dt
814
+
815
+ self.assertEqual(self.publisher.publish_article.call_count, 0,
816
+ "No publish outside schedule window")
817
+
818
+ # ================================================================
819
+ # 16b. Gemini pending queue drains progressively (capped per cycle)
820
+ # ================================================================
821
+ async def test_gemini_pending_drains_progressively(self):
822
+ from modules.blogger.scheduler import PROGRESSIVE_DRAIN_BATCH
823
+ self.publisher.config.is_enabled.return_value = True
824
+
825
+ calls = [0]
826
+
827
+ def recovered(*args, **kwargs):
828
+ calls[0] += 1
829
+ # Mirrors the real processor: successful recovery removes the item.
830
+ if self.db.get_gemini_pending_queue():
831
+ self.db.remove_from_gemini_pending(0)
832
+ return {
833
+ "fingerprint": f"fp_{calls[0]}",
834
+ "title": f"Article {calls[0]}",
835
+ "body": "<p>Body</p>",
836
+ "status": "queued",
837
+ "channel_id": "ch1",
838
+ "section": "general",
839
+ "labels": ["عام", "اخبار"],
840
+ "hashtags": ["#test"],
841
+ }
842
+
843
+ # MagicMock('_process_next_pending') is an un-awaitable default; patch side effect.
844
+ self.processor._process_next_pending = AsyncMock(side_effect=recovered)
845
+
846
+ # Simulate a large backlog present in the DB.
847
+ pending = []
848
+ for i in range(12):
849
+ pending.append({
850
+ "raw_text": f"text {i}", "source_url": "", "media": [],
851
+ "fingerprint": f"fp_{i+1}", "channel_id": "ch1",
852
+ "section": "general", "attempts": 0, "added_at": 0,
853
+ })
854
+ self.db.save_gemini_pending_queue(pending)
855
+
856
+ await self.scheduler._process_gemini_pending()
857
+ # Only PROGRESSIVE_DRAIN_BATCH articles were recovered in this single cycle.
858
+ self.assertEqual(calls[0], PROGRESSIVE_DRAIN_BATCH,
859
+ "Pending recovery must be capped per cycle")
860
+ # Remaining articles stay queued for the next cycle.
861
+ remaining = self.db.get_gemini_pending_queue()
862
+ self.assertEqual(len(remaining), 12 - PROGRESSIVE_DRAIN_BATCH)
863
+
864
+
865
+ # ================================================================
866
+ # 17. Details table + single apply section (mandatory variant checks)
867
+ # ================================================================
868
+ class TestArticleHtmlFormatting(unittest.TestCase):
869
+
870
+ def setUp(self):
871
+ self.db = InMemoryDB()
872
+ self.ai = MagicMock()
873
+ self.processor = ArticleProcessor(self.db, self.ai, {"default_jobs_image": ""})
874
+
875
+ def _make_article(self, extracted=None, body=None, conclusion="", with_channel=True):
876
+ art = {
877
+ "title": "وظيفة في بغداد",
878
+ "body": body or "<h2>طريقة التقديم</h2><p>أرسل سيرتك الذاتية.</p>",
879
+ "extracted": extracted or {},
880
+ "conclusion": conclusion,
881
+ "hashtags": [],
882
+ }
883
+ if with_channel:
884
+ art["source"] = {
885
+ "name": "قناة الوظائف", "username": "jobs_iraq", "link": "https://t.me/jobs_iraq",
886
+ }
887
+ return art
888
+
889
+ def _assert_order(self, html, markers):
890
+ idxs = [html.find(m) for m in markers]
891
+ self.assertNotIn(-1, idxs, f"missing marker: {markers}")
892
+ self.assertEqual(idxs, sorted(idxs), f"wrong order: {dict(zip(markers, idxs))}")
893
+
894
+ # ---------------- apply section: single source, fixed order ----------------
895
+
896
+ def test_phone_only(self):
897
+ html = self.processor.make_article_html(self._make_article({"phone": "07701234567"}))
898
+ self.assertIn('href="tel:07701234567"', html)
899
+ self.assertIn("apply-box-phone", html)
900
+ self.assertIn("آلية التقديم والتواصل", html)
901
+ self.assertNotIn("mailto:", html)
902
+ self.assertNotIn('class="apply-box apply-box-link"', html)
903
+ self._assert_order(html, [
904
+ "آلية التقديم والتواصل", "يمكنك التقديم على هذه الفرصة",
905
+ "📞 رقم الهاتف", "07701234567", "📞 اتصال", "💬 واتساب",
906
+ ])
907
+
908
+ def test_phone_and_email(self):
909
+ extracted = {"phone": "07701234567", "email": "jobs@example.com"}
910
+ html = self.processor.make_article_html(self._make_article(extracted))
911
+ self.assertIn('href="mailto:jobs@example.com"', html)
912
+ self.assertIn('href="tel:07701234567"', html)
913
+ self.assertNotIn('class="apply-box apply-box-link"', html)
914
+ self._assert_order(html, [
915
+ "آلية التقديم والتواصل", "📞 رقم الهاتف", "07701234567",
916
+ "✉️ البريد الإلكتروني", "jobs@example.com",
917
+ ])
918
+
919
+ def test_phone_email_and_link(self):
920
+ extracted = {
921
+ "phone": "07701234567", "email": "jobs@example.com",
922
+ "apply_url": "https://forms.gle/xyz",
923
+ }
924
+ html = self.processor.make_article_html(self._make_article(extracted))
925
+ self.assertIn('apply-btn-now', html)
926
+ self._assert_order(html, [
927
+ "آلية التقديم والتواصل", "📞 رقم الهاتف", "07701234567",
928
+ "✉️ البريد الإلكتروني", "jobs@example.com",
929
+ "🌐 راب�� التقديم", "https://forms.gle/xyz",
930
+ ])
931
+
932
+ def test_email_only(self):
933
+ html = self.processor.make_article_html(self._make_article({"email": "jobs@example.com"}))
934
+ self.assertIn('href="mailto:jobs@example.com"', html)
935
+ self.assertIn("✉️ البريد الإلكتروني", html)
936
+ self.assertNotIn('href="tel:', html)
937
+ self.assertNotIn('class="apply-box apply-box-link"', html)
938
+ self._assert_order(html, [
939
+ "آلية التقديم والتواصل", "✉️ البريد الإلكتروني", "jobs@example.com",
940
+ ])
941
+
942
+ def test_link_only(self):
943
+ html = self.processor.make_article_html(self._make_article({"apply_url": "https://forms.gle/xyz"}))
944
+ self.assertIn('href="https://forms.gle/xyz"', html)
945
+ self.assertIn('apply-btn-now', html)
946
+ self.assertNotIn("mailto:", html)
947
+ self.assertNotIn('href="tel:', html)
948
+ self._assert_order(html, [
949
+ "آلية التقديم والتواصل", "🌐 رابط التقديم", "https://forms.gle/xyz", ">التقديم<",
950
+ ])
951
+
952
+ def test_all_three_no_duplicates(self):
953
+ extracted = {
954
+ "phone": "07701234567", "email": "jobs@example.com",
955
+ "apply_url": "https://forms.gle/xyz",
956
+ }
957
+ html = self.processor.make_article_html(self._make_article(extracted))
958
+ self.assertEqual(html.count('class="apply-section"'), 1)
959
+ self.assertEqual(html.count('href="mailto:jobs@example.com"'), 2)
960
+ self.assertEqual(html.count('href="tel:07701234567"'), 2)
961
+ self.assertEqual(html.count('href="https://forms.gle/xyz"'), 2)
962
+ self.assertEqual(html.count('class="apply-btn apply-btn-now"'), 1)
963
+ self.assertIn('href="https://wa.me/9647701234567"', html)
964
+
965
+ def test_foreign_phone_no_whatsapp(self):
966
+ html = self.processor.make_article_html(self._make_article({"phone": "+44 7700 900123"}))
967
+ self.assertIn('href="tel:+447700900123"', html)
968
+ self.assertNotIn("wa.me", html)
969
+
970
+ def test_no_contacts_no_apply_section(self):
971
+ html = self.processor.make_article_html(self._make_article({}))
972
+ self.assertNotIn("آلية التقديم والتواصل", html)
973
+ self.assertNotIn('class="apply-', html)
974
+
975
+ def test_ai_apply_paragraph_replaced(self):
976
+ art = self._make_article({"phone": "07701234567"},
977
+ body="<h2>طريقة التقديم</h2><p>نص قديم يجب استبداله.</p>")
978
+ html = self.processor.make_article_html(art)
979
+ self.assertNotIn("نص قديم يجب استبداله", html)
980
+ self.assertIn("آلية التقديم والتواصل", html)
981
+ self.assertEqual(html.count('class="apply-section"'), 1)
982
+
983
+ def test_apply_builder_log_once(self):
984
+ with self.assertLogs("modules.blogger.processor", level="INFO") as cm:
985
+ self.processor.make_article_html(self._make_article({"phone": "07701234567"}))
986
+ msgs = [r.getMessage() for r in cm.records]
987
+ self.assertEqual(msgs.count("Apply Builder Called"), 1)
988
+
989
+ # ---------------- other sections untouched ----------------
990
+
991
+ def test_benefits_table_intact(self):
992
+ body = ('<h2>المميزات</h2>'
993
+ '<table><tr><td>الراتب</td><td>800,000 دينار</td></tr>'
994
+ '<tr><td>الدوام</td><td>8 ساعات</td></tr></table>'
995
+ '<h2>طريقة التقديم</h2><p>نص قديم.</p>')
996
+ html = self.processor.make_article_html(self._make_article({"phone": "07701234567"}, body=body))
997
+ self.assertIn('class="job-table"', html)
998
+ self.assertIn("800,000 دينار", html)
999
+ self.assertIn("آلية التقديم والتواصل", html)
1000
+
1001
+ def test_no_table(self):
1002
+ html = self.processor.make_article_html(self._make_article({}))
1003
+ self.assertNotIn('class="job-table"', html)
1004
+
1005
+ def test_legacy_div_before_heading_untouched_section_once(self):
1006
+ body = ('<div style="background:#e8f5e9;border-right:4px solid #4caf50;padding:12px 16px;margin:15px 0;border-radius:4px;"><strong style="color:#2e7d32;">🔗 رابط التقديم</strong>'
1007
+ '<p><a href="https://forms.gle/dup">https://forms.gle/dup</a></p></div>'
1008
+ '<h2>طريقة التقديم</h2><p>نص.</p>')
1009
+ html = self.processor.make_article_html(self._make_article({"phone": "07701234567"}, body=body))
1010
+ self.assertEqual(html.count('class="apply-section"'), 1)
1011
+ self.assertNotIn("نص.", html)
1012
+
1013
+ def test_conclusion_card(self):
1014
+ html = self.processor.make_article_html(
1015
+ self._make_article({}, conclusion="للمزيد من الوظائف اليومية تابع قناة قلعة الوظائف العراقية"))
1016
+ self.assertIn('class="article-end"', html)
1017
+ self.assertIn("قلعة الوظائف العراقية", html)
1018
+
1019
+ def test_no_conclusion_no_card(self):
1020
+ html = self.processor.make_article_html(self._make_article({}))
1021
+ self.assertNotIn('class="article-end"', html)
1022
+
1023
+ def test_professional_stylesheet_present(self):
1024
+ html = self.processor.make_article_html(self._make_article({}))
1025
+ self.assertIn("<style>", html)
1026
+ self.assertIn(".apply-box-phone", html)
1027
+ self.assertIn(".apply-btn-whatsapp", html)
1028
+ self.assertIn(".apply-btn-now", html)
1029
+ self.assertIn(".job-table", html)
1030
+ self.assertIn(".article-end", html)
1031
+ self.assertIn("@media (max-width:600px)", html)
1032
+ self.assertNotIn("details-table", html)
1033
+
1034
+ # ---------------- single generator per section (no duplicates) ----------------
1035
+
1036
+ def test_single_toc_only_and_nav_heading_removed(self):
1037
+ body = ('<h2>التنقل السريع</h2><ul><li>رابط</li></ul>'
1038
+ '<h2>الوصف</h2><p>نص.</p>'
1039
+ '<h2>المميزات</h2><p>نص.</p>')
1040
+ html = self.processor.make_article_html(self._make_article({}, body=body))
1041
+ self.assertEqual(html.count('class="toc-box"'), 1)
1042
+ self.assertEqual(html.count("المحتويات والتنقل السريع"), 1)
1043
+ self.assertNotIn("<h2>التنقل السريع</h2>", html)
1044
+ self.assertNotIn("<li>رابط</li>", html)
1045
+
1046
+ def test_toc_right_after_introduction(self):
1047
+ art = self._make_article({}, body="<h2>الوصف</h2><p>نص.</p><h2>المميزات</h2><p>نص.</p>")
1048
+ art["introduction"] = "مقدمة المقال"
1049
+ html = self.processor.make_article_html(art)
1050
+ self.assertGreater(html.find("المحتويات والتنقل السريع"), html.find(">المقدمة<"))
1051
+ self.assertGreater(html.find(">الوصف<"), html.find("المحتويات والتنقل السريع"))
1052
+
1053
+ def test_details_table_section_removed_entirely(self):
1054
+ html = self.processor.make_article_html(self._make_article({}))
1055
+ self.assertNotIn("ملخص تفاصيل الفرصة الوظيفية", html)
1056
+ self.assertNotIn("details-table", html)
1057
+ self.assertNotIn("الجهة المعلنة", html)
1058
+
1059
+ def test_single_apply_section(self):
1060
+ extracted = {"phone": "07701234567", "email": "jobs@example.com",
1061
+ "apply_url": "https://forms.gle/xyz"}
1062
+ html = self.processor.make_article_html(self._make_article(extracted))
1063
+ self.assertEqual(html.count('class="apply-section"'), 1)
1064
+ self.assertEqual(html.count("آلية التقديم والتواصل"), 1)
1065
+ self.assertEqual(html.count('class="apply-box apply-box-phone"'), 1)
1066
+ self.assertEqual(html.count('class="apply-box apply-box-mail"'), 1)
1067
+ self.assertEqual(html.count('class="apply-box apply-box-link"'), 1)
1068
+
1069
+
1070
+ # ================================================================
1071
+ # 18. Source footer cleaning + Telegram links never apply methods
1072
+ # ================================================================
1073
+ class TestSourceFooterCleaning(unittest.IsolatedAsyncioTestCase):
1074
+
1075
+ def setUp(self):
1076
+ self.db = InMemoryDB()
1077
+ self.ai = MagicMock()
1078
+ self.processor = ArticleProcessor(self.db, self.ai, {"default_jobs_image": ""})
1079
+
1080
+ def _article(self, extracted=None, body=None):
1081
+ return {
1082
+ "title": "وظيفة في بغداد",
1083
+ "body": body or "<h2>الوصف</h2><p>نص.</p><h2>المميزات</h2><p>نص.</p>",
1084
+ "extracted": extracted or {},
1085
+ "conclusion": "",
1086
+ "hashtags": [],
1087
+ }
1088
+
1089
+ # --- ad with phone only ---
1090
+ def test_phone_only_ad(self):
1091
+ raw = ("تعلن شركة عن وظيفة شاغرة\n"
1092
+ "07774411303\n"
1093
+ "للمزيد من الوظائف تابعوا قناتنا")
1094
+ cleaned = self.processor._clean_source_footer(raw)
1095
+ self.assertIn("07774411303", cleaned)
1096
+ self.assertNotIn("للمزيد من الوظائف", cleaned)
1097
+ html = self.processor.make_article_html(self._article({"phone": "07774411303"}))
1098
+ self.assertIn("apply-box-phone", html)
1099
+ self.assertNotIn('class="apply-box apply-box-mail"', html)
1100
+ self.assertNotIn('class="apply-box apply-box-link"', html)
1101
+
1102
+ # --- ad with email only ---
1103
+ def test_email_only_ad(self):
1104
+ raw = "مطلوب موظف\nhr@company.com\nاشترك بقناتنا"
1105
+ cleaned = self.processor._clean_source_footer(raw)
1106
+ self.assertIn("hr@company.com", cleaned)
1107
+ self.assertNotIn("اشترك بقناتنا", cleaned)
1108
+ html = self.processor.make_article_html(self._article({"email": "hr@company.com"}))
1109
+ self.assertIn('href="mailto:hr@company.com"', html)
1110
+ self.assertNotIn('class="apply-box apply-box-phone"', html)
1111
+
1112
+ # --- ad with apply link only ---
1113
+ def test_apply_link_only_ad(self):
1114
+ raw = "للتقديم عبر النموذج الرسمي\nhttps://forms.gle/xyz"
1115
+ cleaned = self.processor._clean_source_footer(raw)
1116
+ self.assertIn("https://forms.gle/xyz", cleaned)
1117
+ html = self.processor.make_article_html(self._article({"apply_url": "https://forms.gle/xyz"}))
1118
+ self.assertIn('class="apply-box apply-box-link"', html)
1119
+ self.assertIn("apply-btn-now", html)
1120
+
1121
+ # --- ad with phone + email + link ---
1122
+ def test_phone_email_link_ad(self):
1123
+ raw = ("07774411303\nhr@company.com\nhttps://company.com/jobs\n"
1124
+ "تابعونا على قناتنا")
1125
+ cleaned = self.processor._clean_source_footer(raw)
1126
+ self.assertIn("07774411303", cleaned)
1127
+ self.assertIn("hr@company.com", cleaned)
1128
+ self.assertIn("https://company.com/jobs", cleaned)
1129
+ self.assertNotIn("تابعونا", cleaned)
1130
+ html = self.processor.make_article_html(self._article({
1131
+ "phone": "07774411303", "email": "hr@company.com",
1132
+ "apply_url": "https://company.com/jobs",
1133
+ }))
1134
+ self.assertEqual(html.count('class="apply-section"'), 1)
1135
+ self._assert_order(html, [
1136
+ "📞 رقم الهاتف", "✉️ البريد الإلكتروني", "🌐 رابط التقديم",
1137
+ ])
1138
+
1139
+ def _assert_order(self, html, markers):
1140
+ idxs = [html.find(m) for m in markers]
1141
+ self.assertNotIn(-1, idxs, f"missing marker: {markers}")
1142
+ self.assertEqual(idxs, sorted(idxs), f"wrong order: {dict(zip(markers, idxs))}")
1143
+
1144
+ # --- ad with Telegram link only ---
1145
+ def test_telegram_link_only_ignored(self):
1146
+ cleaned = self.processor._clean_source_footer("وظيفة شاغرة\nhttps://t.me/CastleJobiq")
1147
+ self.assertNotIn("t.me", cleaned)
1148
+ html = self.processor.make_article_html(self._article({"apply_url": "https://t.me/CastleJobiq"}))
1149
+ self.assertNotIn('class="apply-section"', html)
1150
+ self.assertNotIn("آلية التقديم والتواصل", html)
1151
+ self.assertNotIn("CastleJobiq", html)
1152
+
1153
+ # --- Telegram signature at the bottom of the ad ---
1154
+ def test_telegram_signature_at_bottom_cleaned(self):
1155
+ raw = ("07774411303\nhr@company.com\nhttps://company.com/jobs\n"
1156
+ "ولمتابعة المزيد من الوظائف تابع قناة قلعة الوظائف العراقية على التليجرام\n"
1157
+ "https://t.me/CastleJobiq")
1158
+ cleaned = self.processor._clean_source_footer(raw)
1159
+ self.assertIn("07774411303", cleaned)
1160
+ self.assertIn("hr@company.com", cleaned)
1161
+ self.assertIn("https://company.com/jobs", cleaned)
1162
+ self.assertNotIn("تابع قناة", cleaned)
1163
+ self.assertNotIn("t.me", cleaned)
1164
+ self.assertNotIn("CastleJobiq", cleaned)
1165
+ self.assertNotIn("التليجرام", cleaned)
1166
+ html = self.processor.make_article_html(self._article({
1167
+ "phone": "07774411303", "email": "hr@company.com",
1168
+ "apply_url": "https://company.com/jobs",
1169
+ }))
1170
+ self.assertNotIn("CastleJobiq", html)
1171
+ self.assertNotIn("t.me", html)
1172
+
1173
+ # --- "للمزيد من الوظائف تابع قناة CastleJobiq" ---
1174
+ def test_follow_channel_phrase_removed(self):
1175
+ cleaned = self.processor._clean_source_footer("للمزيد من الوظائف تابع قناة CastleJobiq")
1176
+ self.assertEqual(cleaned, "")
1177
+
1178
+ # --- @CastleJobiq username ---
1179
+ def test_at_channel_username_removed(self):
1180
+ cleaned = self.processor._clean_source_footer("وظيفة شاغرة\n@CastleJobiq")
1181
+ self.assertEqual(cleaned, "وظيفة شاغرة")
1182
+
1183
+ # --- multiple Telegram links ---
1184
+ def test_multiple_telegram_links_removed(self):
1185
+ raw = ("07774411303\n"
1186
+ "https://t.me/CastleJobiq\n"
1187
+ "https://telegram.me/CastleJobs\n"
1188
+ "https://tlgrm.me/join\n"
1189
+ "hr@company.com")
1190
+ cleaned = self.processor._clean_source_footer(raw)
1191
+ self.assertIn("07774411303", cleaned)
1192
+ self.assertIn("hr@company.com", cleaned)
1193
+ self.assertNotIn("t.me", cleaned)
1194
+ self.assertNotIn("telegram", cleaned)
1195
+
1196
+ # --- ad with no contacts at all ---
1197
+ def test_no_contacts_no_apply_section(self):
1198
+ html = self.processor.make_article_html(self._article({}))
1199
+ self.assertNotIn('class="apply-', html)
1200
+ self.assertNotIn("آلية التقديم والتواصل", html)
1201
+
1202
+ # --- Telegram apply_url defensively ignored in HTML even if extracted ---
1203
+ def test_telegram_apply_url_dropped_but_phone_kept(self):
1204
+ html = self.processor.make_article_html(self._article({
1205
+ "phone": "07774411303", "apply_url": "https://t.me/CastleJobiq",
1206
+ }))
1207
+ self.assertEqual(html.count('class="apply-section"'), 1)
1208
+ self.assertIn("apply-box-phone", html)
1209
+ self.assertNotIn('class="apply-box apply-box-link"', html)
1210
+ self.assertNotIn("CastleJobiq", html)
1211
+
1212
+ # --- pipeline passes cleaned text to rewrite/extract ---
1213
+ async def test_pipeline_extract_receives_cleaned_text(self):
1214
+ raw = ("07774411303\nhr@company.com\nhttps://company.com/jobs\n"
1215
+ "ولمتابعة المزيد م�� الوظائف\nhttps://t.me/CastleJobiq")
1216
+ self.processor._rewrite = AsyncMock(return_value={
1217
+ "title": "وظيفة", "body": "<p>نص</p>", "introduction": "",
1218
+ "faq": [], "conclusion": "",
1219
+ })
1220
+ self.processor._extract = AsyncMock(return_value={
1221
+ "phone": "07774411303", "email": "hr@company.com",
1222
+ "apply_url": "https://company.com/jobs",
1223
+ })
1224
+ self.processor._summary = AsyncMock(return_value={"summary": "ملخص"})
1225
+ self.processor._metadata = AsyncMock(return_value={
1226
+ "notes": [], "keywords": "", "hashtags": ["#وظائف"],
1227
+ })
1228
+ await self.processor._run_pipeline({"fingerprint": "f1"}, raw)
1229
+ prompt = self.processor._extract.await_args.args[0]
1230
+ self.assertNotIn("t.me", prompt)
1231
+ self.assertNotIn("CastleJobiq", prompt)
1232
+ self.assertNotIn("لمتابعة المزيد", prompt)
1233
+ self.assertIn("07774411303", prompt)
1234
+ self.assertIn("hr@company.com", prompt)
1235
+ self.assertIn("https://company.com/jobs", prompt)
1236
+
1237
+
1238
+ if __name__ == "__main__":
1239
+ unittest.main()