Spaces:
Running
Running
Upload 6 files
Browse files
tests/__init__.py
ADDED
|
File without changes
|
tests/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (175 Bytes). View file
|
|
|
tests/integration/__init__.py
ADDED
|
File without changes
|
tests/integration/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (187 Bytes). View file
|
|
|
tests/integration/__pycache__/test_full_pipeline.cpython-314.pyc
ADDED
|
Binary file (39.2 kB). View file
|
|
|
tests/integration/test_full_pipeline.py
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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=""):
|
| 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,
|
| 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 get_gemini_state(self): return self.data.get("stats", {}).get("_gemini", {"global_cooldown_until": 0.0})
|
| 125 |
+
def save_gemini_state(self, state): self.data.setdefault("stats", {})["_gemini"] = state
|
| 126 |
+
def increment_ai_key_usage(self, key_id):
|
| 127 |
+
if str(key_id) in self.data.get("ai_keys", {}):
|
| 128 |
+
self.data["ai_keys"][str(key_id)]["usage_count"] += 1
|
| 129 |
+
def increment_ai_key_error(self, key_id):
|
| 130 |
+
if str(key_id) in self.data.get("ai_keys", {}):
|
| 131 |
+
self.data["ai_keys"][str(key_id)]["error_count"] += 1
|
| 132 |
+
def set_ai_key_enabled(self, key_id, enabled):
|
| 133 |
+
if str(key_id) in self.data.get("ai_keys", {}):
|
| 134 |
+
self.data["ai_keys"][str(key_id)]["enabled"] = enabled
|
| 135 |
+
def get_schedule_state(self):
|
| 136 |
+
return self.data.get("stats", {}).get("_schedule", {"day": "", "last_slot": -1})
|
| 137 |
+
def save_schedule_state(self, state):
|
| 138 |
+
self.data.setdefault("stats", {})["_schedule"] = state
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def make_gemini_models_response():
|
| 142 |
+
return mock_http_response(200, {
|
| 143 |
+
"models": [
|
| 144 |
+
{"name": "models/gemini-2.0-flash", "supportedGenerationMethods": ["generateContent"]},
|
| 145 |
+
]
|
| 146 |
+
})
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def make_openai_models_response():
|
| 150 |
+
return mock_http_response(200, {
|
| 151 |
+
"data": [
|
| 152 |
+
{"id": "deepseek-chat", "object": "model", "owned_by": "deepseek"},
|
| 153 |
+
]
|
| 154 |
+
})
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def make_gemini_chat_response(json_data: dict):
|
| 158 |
+
text = json.dumps(json_data, ensure_ascii=False)
|
| 159 |
+
return mock_http_response(200, {
|
| 160 |
+
"candidates": [{"content": {"parts": [{"text": text}]}}]
|
| 161 |
+
})
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def make_openai_chat_response(json_data: dict):
|
| 165 |
+
text = json.dumps(json_data, ensure_ascii=False)
|
| 166 |
+
return mock_http_response(200, {
|
| 167 |
+
"choices": [{"message": {"content": text}}]
|
| 168 |
+
})
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def make_gemini_fail_response(status_code=429, message="rate limit"):
|
| 172 |
+
return mock_http_response(status_code, {"error": {"message": message}})
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def make_openai_fail_response(status_code=429, message="rate limit"):
|
| 176 |
+
return mock_http_response(status_code, {"error": {"message": message}})
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class TestFullPipelineIntegration(unittest.IsolatedAsyncioTestCase):
|
| 180 |
+
|
| 181 |
+
def setUp(self):
|
| 182 |
+
_model_cache.clear()
|
| 183 |
+
self.env_patcher = patch.dict(os.environ, {
|
| 184 |
+
"GEMINI_KEY_1": "test-key-gemini-1",
|
| 185 |
+
"GEMINI_KEY_2": "test-key-gemini-2",
|
| 186 |
+
"GROQ_KEY_1": "test-key-groq-1",
|
| 187 |
+
"OPENROUTER_KEY_1": "test-key-or-1",
|
| 188 |
+
})
|
| 189 |
+
self.env_patcher.start()
|
| 190 |
+
self.db = InMemoryDB()
|
| 191 |
+
self.key_manager = AIKeyManager(self.db)
|
| 192 |
+
self.ai = AIClient(self.key_manager)
|
| 193 |
+
self.ai._http = AsyncMock()
|
| 194 |
+
self.ai._http.post = AsyncMock()
|
| 195 |
+
self.ai._http.get = AsyncMock()
|
| 196 |
+
self.processor = ArticleProcessor(self.db, self.ai, {"default_jobs_image": ""})
|
| 197 |
+
|
| 198 |
+
def tearDown(self):
|
| 199 |
+
self.env_patcher.stop()
|
| 200 |
+
_model_cache.clear()
|
| 201 |
+
|
| 202 |
+
def _setup_models_discovery(self):
|
| 203 |
+
"""Mock HTTP GET to return correct model list per provider."""
|
| 204 |
+
async def mock_get(url, **kwargs):
|
| 205 |
+
if "generativelanguage" in url:
|
| 206 |
+
return make_gemini_models_response()
|
| 207 |
+
return make_openai_models_response()
|
| 208 |
+
self.ai._http.get = AsyncMock(side_effect=mock_get)
|
| 209 |
+
|
| 210 |
+
# ================================================================
|
| 211 |
+
# 1. Full Pipeline: raw_text -> queued article with all fields
|
| 212 |
+
# ================================================================
|
| 213 |
+
async def test_full_pipeline_success(self):
|
| 214 |
+
self._setup_models_discovery()
|
| 215 |
+
|
| 216 |
+
responses = [
|
| 217 |
+
{"title": "وزارة التربية تعلن عن 500 درجة وظيفية",
|
| 218 |
+
"body": "<h2>التفاصيل</h2><p>أعلنت وزارة التربية عن توفر 500 درجة.</p>",
|
| 219 |
+
"introduction": "أعلنت وزارة التربية عن فرص عمل جديدة.",
|
| 220 |
+
"faq": [{"question": "ما هي الدرجات؟", "answer": "500 درجة وظيفية."}],
|
| 221 |
+
"conclusion": "فرصة ممتازة للباحثين عن عمل."},
|
| 222 |
+
{"ministry": "وزارة التربية", "province": "بغداد",
|
| 223 |
+
"job_type": "وظ��ئف", "salary": "800,000 دينار", "deadline": "2026/08/15"},
|
| 224 |
+
{"summary": "وزارة التربية تعلن عن 500 درجة وظيفية براتب يصل إلى 800 ألف دينار."},
|
| 225 |
+
{"notes": ["الراتب 800,000 دينار عراقي.", "آخر موعد 2026/08/15."]},
|
| 226 |
+
{"keywords": "وظائف العراق، وزارة التربية، بغداد، تعيينات"},
|
| 227 |
+
{"hashtags": ["#العراق", "#وظائف", "#التعليم"]},
|
| 228 |
+
]
|
| 229 |
+
resp_iter = iter(responses)
|
| 230 |
+
|
| 231 |
+
async def mock_post(url, **kwargs):
|
| 232 |
+
data = next(resp_iter)
|
| 233 |
+
if "generativelanguage" in url:
|
| 234 |
+
return make_gemini_chat_response(data)
|
| 235 |
+
return make_openai_chat_response(data)
|
| 236 |
+
|
| 237 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 238 |
+
|
| 239 |
+
fingerprint = self.processor.enqueue_raw_post(TEST_RAW_TEXT, source_url="https://t.me/test/1")
|
| 240 |
+
self.assertIsNotNone(fingerprint)
|
| 241 |
+
pending = self.db.get_gemini_pending_queue()
|
| 242 |
+
self.assertTrue(any(p.get("fingerprint") == fingerprint for p in pending))
|
| 243 |
+
|
| 244 |
+
session_ok = await self.ai.acquire_session()
|
| 245 |
+
self.assertTrue(session_ok)
|
| 246 |
+
|
| 247 |
+
result = await self.processor._process_next_pending()
|
| 248 |
+
self.assertIsNotNone(result)
|
| 249 |
+
self.assertEqual(result["status"], "processed")
|
| 250 |
+
self.assertEqual(result["title"], "وزارة التربية تعلن عن 500 درجة وظيفية")
|
| 251 |
+
self.assertIn("<h2>التفاصيل</h2>", result["body"])
|
| 252 |
+
self.assertIn("hashtags", result)
|
| 253 |
+
self.assertEqual(result["hashtags"], ["#العراق", "#وظائف", "#التعليم"])
|
| 254 |
+
|
| 255 |
+
saved = self.db.get_article(fingerprint)
|
| 256 |
+
self.assertIsNotNone(saved)
|
| 257 |
+
self.assertEqual(saved["status"], "processed")
|
| 258 |
+
|
| 259 |
+
# ================================================================
|
| 260 |
+
# 2. HTML contains hashtags after <hr>
|
| 261 |
+
# ================================================================
|
| 262 |
+
async def test_html_contains_hashtags(self):
|
| 263 |
+
article = {
|
| 264 |
+
"title": "Test Title",
|
| 265 |
+
"body": "<p>Test body</p>",
|
| 266 |
+
"hashtags": ["#العراق", "#وظائف", "#التعليم"],
|
| 267 |
+
"extracted": {"ministry": "test"},
|
| 268 |
+
"reading_time": 3,
|
| 269 |
+
"source": {"name": "Test"},
|
| 270 |
+
}
|
| 271 |
+
html = self.processor.make_article_html(article)
|
| 272 |
+
self.assertIn("#العراق", html)
|
| 273 |
+
self.assertIn("#وظائف", html)
|
| 274 |
+
self.assertIn("#التعليم", html)
|
| 275 |
+
self.assertIn("<hr", html)
|
| 276 |
+
after_hr = html.split("<hr")[1] if "<hr" in html else ""
|
| 277 |
+
self.assertIn("#العراق", after_hr)
|
| 278 |
+
|
| 279 |
+
# ================================================================
|
| 280 |
+
# 3. Timeout -> tries next key
|
| 281 |
+
# ================================================================
|
| 282 |
+
async def test_ai_timeout_tries_next_key(self):
|
| 283 |
+
_model_cache.clear()
|
| 284 |
+
self._setup_models_discovery()
|
| 285 |
+
|
| 286 |
+
call_count = [0]
|
| 287 |
+
|
| 288 |
+
async def mock_post(url, **kwargs):
|
| 289 |
+
call_count[0] += 1
|
| 290 |
+
if call_count[0] == 1:
|
| 291 |
+
raise httpx.TimeoutException("timeout", request=None)
|
| 292 |
+
data = {"title": "OK", "body": "<p>OK</p>"}
|
| 293 |
+
if "generativelanguage" in url:
|
| 294 |
+
return make_gemini_chat_response(data)
|
| 295 |
+
return make_openai_chat_response(data)
|
| 296 |
+
|
| 297 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 298 |
+
|
| 299 |
+
session_ok = await self.ai.acquire_session()
|
| 300 |
+
self.assertTrue(session_ok)
|
| 301 |
+
|
| 302 |
+
result = await self.ai.generate("test prompt")
|
| 303 |
+
self.assertIsNotNone(result)
|
| 304 |
+
self.assertGreater(call_count[0], 1)
|
| 305 |
+
|
| 306 |
+
# ================================================================
|
| 307 |
+
# 4. Invalid API key -> tries next key
|
| 308 |
+
# ================================================================
|
| 309 |
+
async def test_invalid_key_skips_to_next(self):
|
| 310 |
+
_model_cache.clear()
|
| 311 |
+
self._setup_models_discovery()
|
| 312 |
+
|
| 313 |
+
call_count = [0]
|
| 314 |
+
|
| 315 |
+
async def mock_post(url, **kwargs):
|
| 316 |
+
call_count[0] += 1
|
| 317 |
+
if call_count[0] == 1:
|
| 318 |
+
return make_gemini_fail_response(401, "API key not valid")
|
| 319 |
+
data = {"title": "OK", "body": "<p>OK</p>"}
|
| 320 |
+
if "generativelanguage" in url:
|
| 321 |
+
return make_gemini_chat_response(data)
|
| 322 |
+
return make_openai_chat_response(data)
|
| 323 |
+
|
| 324 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 325 |
+
|
| 326 |
+
session_ok = await self.ai.acquire_session()
|
| 327 |
+
self.assertTrue(session_ok)
|
| 328 |
+
|
| 329 |
+
result = await self.ai.generate("test prompt")
|
| 330 |
+
self.assertIsNotNone(result)
|
| 331 |
+
|
| 332 |
+
# ================================================================
|
| 333 |
+
# 5. ALL providers fail -> NoAvailableAIProvider (no recursion)
|
| 334 |
+
# ================================================================
|
| 335 |
+
async def test_all_providers_fail_raises_no_recursion(self):
|
| 336 |
+
_model_cache.clear()
|
| 337 |
+
self._setup_models_discovery()
|
| 338 |
+
|
| 339 |
+
async def mock_post(url, **kwargs):
|
| 340 |
+
return make_gemini_fail_response(429, "quota exhausted")
|
| 341 |
+
|
| 342 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 343 |
+
|
| 344 |
+
session_ok = await self.ai.acquire_session()
|
| 345 |
+
self.assertTrue(session_ok)
|
| 346 |
+
|
| 347 |
+
with self.assertRaises(NoAvailableAIProvider):
|
| 348 |
+
await self.ai.generate("test prompt")
|
| 349 |
+
|
| 350 |
+
# ================================================================
|
| 351 |
+
# 6. No RecursionError when all keys fail
|
| 352 |
+
# ================================================================
|
| 353 |
+
async def test_no_recursion_on_repeated_failures(self):
|
| 354 |
+
_model_cache.clear()
|
| 355 |
+
self._setup_models_discovery()
|
| 356 |
+
self.ai._http.post = AsyncMock(return_value=make_gemini_fail_response(429, "rate limit"))
|
| 357 |
+
|
| 358 |
+
old_limit = sys.getrecursionlimit()
|
| 359 |
+
sys.setrecursionlimit(50)
|
| 360 |
+
try:
|
| 361 |
+
for _ in range(3):
|
| 362 |
+
self.ai.release_session()
|
| 363 |
+
with self.assertRaises(NoAvailableAIProvider):
|
| 364 |
+
await self.ai.generate("test prompt")
|
| 365 |
+
finally:
|
| 366 |
+
sys.setrecursionlimit(old_limit)
|
| 367 |
+
|
| 368 |
+
# ================================================================
|
| 369 |
+
# 7. Blogger error -> article stays queued (not lost)
|
| 370 |
+
# ================================================================
|
| 371 |
+
async def test_blogger_error_keeps_article_pending(self):
|
| 372 |
+
self._setup_models_discovery()
|
| 373 |
+
|
| 374 |
+
resp_iter = iter([
|
| 375 |
+
{"title": "Test", "body": "<p>Test</p>", "introduction": "", "faq": [], "conclusion": "",
|
| 376 |
+
"summary": "Test", "notes": [], "keywords": "test", "hashtags": ["#test"]},
|
| 377 |
+
{"ministry": "test"},
|
| 378 |
+
{"summary": "Test"},
|
| 379 |
+
{"notes": []},
|
| 380 |
+
{"keywords": "test"},
|
| 381 |
+
{"hashtags": ["#test"]},
|
| 382 |
+
])
|
| 383 |
+
|
| 384 |
+
def save_next_data(*args):
|
| 385 |
+
return {"title": "Test", "body": "<p>Test</p>", "introduction": "", "faq": [], "conclusion": ""}
|
| 386 |
+
|
| 387 |
+
async def mock_post(url, **kwargs):
|
| 388 |
+
data = next(resp_iter)
|
| 389 |
+
if "generativelanguage" in url:
|
| 390 |
+
return make_gemini_chat_response(data)
|
| 391 |
+
return make_openai_chat_response(data)
|
| 392 |
+
|
| 393 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 394 |
+
|
| 395 |
+
fingerprint = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
|
| 396 |
+
session_ok = await self.ai.acquire_session()
|
| 397 |
+
self.assertTrue(session_ok)
|
| 398 |
+
|
| 399 |
+
result = await self.processor._process_next_pending()
|
| 400 |
+
self.assertIsNotNone(result)
|
| 401 |
+
self.assertEqual(result["status"], "processed")
|
| 402 |
+
|
| 403 |
+
saved = self.db.get_article(fingerprint)
|
| 404 |
+
self.assertEqual(saved["status"], "processed")
|
| 405 |
+
|
| 406 |
+
# ================================================================
|
| 407 |
+
# 8. Labels and hashtags independent
|
| 408 |
+
# ================================================================
|
| 409 |
+
async def test_labels_and_hashtags_independent(self):
|
| 410 |
+
self._setup_models_discovery()
|
| 411 |
+
|
| 412 |
+
resp_iter = iter([
|
| 413 |
+
{"title": "Test Article", "body": "<p>Content</p>", "introduction": "Intro",
|
| 414 |
+
"faq": [], "conclusion": "Conclusion"},
|
| 415 |
+
{"ministry": "test"},
|
| 416 |
+
{"summary": "Summary text"},
|
| 417 |
+
{"notes": ["Note 1"]},
|
| 418 |
+
{"keywords": "kw1, kw2"},
|
| 419 |
+
{"hashtags": ["#tag1", "#tag2"]},
|
| 420 |
+
])
|
| 421 |
+
|
| 422 |
+
async def mock_post(url, **kwargs):
|
| 423 |
+
data = next(resp_iter)
|
| 424 |
+
if "generativelanguage" in url:
|
| 425 |
+
return make_gemini_chat_response(data)
|
| 426 |
+
return make_openai_chat_response(data)
|
| 427 |
+
|
| 428 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 429 |
+
|
| 430 |
+
fingerprint = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
|
| 431 |
+
session_ok = await self.ai.acquire_session()
|
| 432 |
+
self.assertTrue(session_ok)
|
| 433 |
+
|
| 434 |
+
result = await self.processor._process_next_pending()
|
| 435 |
+
self.assertIsNotNone(result)
|
| 436 |
+
self.assertEqual(result.get("hashtags"), ["#tag1", "#tag2"])
|
| 437 |
+
|
| 438 |
+
html = self.processor.make_article_html(result)
|
| 439 |
+
self.assertIn("#tag1", html)
|
| 440 |
+
self.assertIn("<hr", html)
|
| 441 |
+
|
| 442 |
+
# ================================================================
|
| 443 |
+
# 9. Duplicate detection
|
| 444 |
+
# ================================================================
|
| 445 |
+
async def test_duplicate_detection(self):
|
| 446 |
+
fp1 = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
|
| 447 |
+
self.assertIsNotNone(fp1)
|
| 448 |
+
fp2 = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
|
| 449 |
+
self.assertIsNone(fp2)
|
| 450 |
+
|
| 451 |
+
# ================================================================
|
| 452 |
+
# 10. Generate safe multiple calls
|
| 453 |
+
# ================================================================
|
| 454 |
+
async def test_multiple_generate_calls_safe(self):
|
| 455 |
+
_model_cache.clear()
|
| 456 |
+
self._setup_models_discovery()
|
| 457 |
+
|
| 458 |
+
async def mock_post(url, **kwargs):
|
| 459 |
+
data = {"title": "OK", "body": "<p>OK</p>"}
|
| 460 |
+
if "generativelanguage" in url:
|
| 461 |
+
return make_gemini_chat_response(data)
|
| 462 |
+
return make_openai_chat_response(data)
|
| 463 |
+
|
| 464 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 465 |
+
|
| 466 |
+
session_ok = await self.ai.acquire_session()
|
| 467 |
+
self.assertTrue(session_ok)
|
| 468 |
+
|
| 469 |
+
for i in range(3):
|
| 470 |
+
result = await self.ai.generate(f"test prompt {i}")
|
| 471 |
+
self.assertIsNotNone(result)
|
| 472 |
+
self.ai.release_session()
|
| 473 |
+
if i < 2:
|
| 474 |
+
session_ok = await self.ai.acquire_session()
|
| 475 |
+
self.assertTrue(session_ok)
|
| 476 |
+
|
| 477 |
+
# ================================================================
|
| 478 |
+
# 11. No infinite loop in key rotation
|
| 479 |
+
# ================================================================
|
| 480 |
+
async def test_no_infinite_loop_key_rotation(self):
|
| 481 |
+
_model_cache.clear()
|
| 482 |
+
self._setup_models_discovery()
|
| 483 |
+
self.ai._http.post = AsyncMock(return_value=make_gemini_fail_response(429, "rate limit"))
|
| 484 |
+
|
| 485 |
+
session_ok = await self.ai.acquire_session()
|
| 486 |
+
self.assertTrue(session_ok)
|
| 487 |
+
|
| 488 |
+
start = time.time()
|
| 489 |
+
try:
|
| 490 |
+
await self.ai.generate("test")
|
| 491 |
+
self.fail("Should have raised NoAvailableAIProvider")
|
| 492 |
+
except NoAvailableAIProvider:
|
| 493 |
+
elapsed = time.time() - start
|
| 494 |
+
self.assertLess(elapsed, 10)
|
| 495 |
+
|
| 496 |
+
# ================================================================
|
| 497 |
+
# 12. Timeout is 30 seconds
|
| 498 |
+
# ================================================================
|
| 499 |
+
def test_timeout_is_30_seconds(self):
|
| 500 |
+
self.assertEqual(TIMEOUT, 30.0)
|
| 501 |
+
|
| 502 |
+
# ================================================================
|
| 503 |
+
# 13. Model not found -> tries next model
|
| 504 |
+
# ================================================================
|
| 505 |
+
async def test_model_not_found_tries_next_model(self):
|
| 506 |
+
_model_cache.clear()
|
| 507 |
+
self._setup_models_discovery()
|
| 508 |
+
|
| 509 |
+
call_count = [0]
|
| 510 |
+
|
| 511 |
+
async def mock_post(url, **kwargs):
|
| 512 |
+
call_count[0] += 1
|
| 513 |
+
if call_count[0] == 1:
|
| 514 |
+
if "generativelanguage" in url:
|
| 515 |
+
return mock_http_response(404, {"error": {"message": "model not found"}})
|
| 516 |
+
return mock_http_response(404, {"error": {"message": "model not found"}})
|
| 517 |
+
data = {"title": "OK", "body": "<p>OK</p>"}
|
| 518 |
+
if "generativelanguage" in url:
|
| 519 |
+
return make_gemini_chat_response(data)
|
| 520 |
+
return make_openai_chat_response(data)
|
| 521 |
+
|
| 522 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 523 |
+
|
| 524 |
+
session_ok = await self.ai.acquire_session()
|
| 525 |
+
self.assertTrue(session_ok)
|
| 526 |
+
|
| 527 |
+
result = await self.ai.generate("test prompt")
|
| 528 |
+
self.assertIsNotNone(result)
|
| 529 |
+
self.assertGreater(call_count[0], 1)
|
| 530 |
+
|
| 531 |
+
# ================================================================
|
| 532 |
+
# 14. Empty hashtags not added to HTML
|
| 533 |
+
# ================================================================
|
| 534 |
+
async def test_empty_hashtags_no_html(self):
|
| 535 |
+
article = {
|
| 536 |
+
"title": "Test",
|
| 537 |
+
"body": "<p>Body</p>",
|
| 538 |
+
"extracted": {},
|
| 539 |
+
"reading_time": 2,
|
| 540 |
+
"source": {"name": "Src"},
|
| 541 |
+
}
|
| 542 |
+
html = self.processor.make_article_html(article)
|
| 543 |
+
self.assertNotIn("<hr", html)
|
| 544 |
+
|
| 545 |
+
# ================================================================
|
| 546 |
+
# 15. Hashtags from AI are stored and preserved
|
| 547 |
+
# ================================================================
|
| 548 |
+
async def test_hashtags_preserved_through_full_cycle(self):
|
| 549 |
+
self._setup_models_discovery()
|
| 550 |
+
|
| 551 |
+
resp_iter = iter([
|
| 552 |
+
{"title": "T", "body": "<p>B</p>", "introduction": "", "faq": [], "conclusion": ""},
|
| 553 |
+
{"ministry": "t"},
|
| 554 |
+
{"summary": "S"},
|
| 555 |
+
{"notes": []},
|
| 556 |
+
{"keywords": "k"},
|
| 557 |
+
{"hashtags": ["#h1", "#h2"]},
|
| 558 |
+
])
|
| 559 |
+
|
| 560 |
+
async def mock_post(url, **kwargs):
|
| 561 |
+
data = next(resp_iter)
|
| 562 |
+
if "generativelanguage" in url:
|
| 563 |
+
return make_gemini_chat_response(data)
|
| 564 |
+
return make_openai_chat_response(data)
|
| 565 |
+
|
| 566 |
+
self.ai._http.post = AsyncMock(side_effect=mock_post)
|
| 567 |
+
|
| 568 |
+
fp = self.processor.enqueue_raw_post(TEST_RAW_TEXT)
|
| 569 |
+
await self.ai.acquire_session()
|
| 570 |
+
result = await self.processor._process_next_pending()
|
| 571 |
+
self.assertIsNotNone(result)
|
| 572 |
+
self.assertEqual(result["status"], "processed")
|
| 573 |
+
self.assertEqual(result["hashtags"], ["#h1", "#h2"])
|
| 574 |
+
|
| 575 |
+
html = self.processor.make_article_html(result)
|
| 576 |
+
self.assertIn("#h1", html)
|
| 577 |
+
self.assertIn("#h2", html)
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
if __name__ == "__main__":
|
| 581 |
+
unittest.main()
|