feat: migrate VK bot to Callback API

This commit is contained in:
nyan404 committed 2026-10-10 21:33:56 +03:00
1 parent 2794546974
commit a04498d634
10 files changed
+438 -58

No files matched your search

+43 -39
View File
@@ -11,9 +11,8 @@ import time
import unicodedata import unicodedata
from datetime import datetime from datetime import datetime
from difflib import SequenceMatcher from difflib import SequenceMatcher
from typing import Any, Iterator from typing import Any
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.error import URLError
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
from .api import ApiError, calculate_payload from .api import ApiError, calculate_payload
@@ -23,6 +22,7 @@ from .image_host import ImageHostClient
from .identity import Identity, IdentityDirectory from .identity import Identity, IdentityDirectory
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
from .google_sheets_export import GoogleSheetsExportService from .google_sheets_export import GoogleSheetsExportService
from .vk_callback import CallbackHTTPServer, process_callback
from .vk_scheduler import VkConversationStore, VkScheduler from .vk_scheduler import VkConversationStore, VkScheduler
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -874,13 +874,23 @@ class BelkiBot:
def handle_event(self, event: dict[str, Any]) -> None: def handle_event(self, event: dict[str, Any]) -> None:
""" """
Обработка события из Long Poll сервера. Обработка одного события VK Callback API.
Извлекает текст сообщения, прикрепляет фото и обрабатывает через dialog. Извлекает текст сообщения, прикрепляет фото и обрабатывает через dialog.
""" """
if event.get("type") != "message_new": event_type = event.get("type")
if event_type not in {"message_new", "message_event"}:
return return
message = event.get("object", {}).get("message", event.get("object", {})) event_object = event.get("object", {})
if event_type == "message_event":
message = {
"peer_id": event_object.get("peer_id"),
"from_id": event_object.get("user_id"),
"payload": event_object.get("payload"),
"text": "",
}
else:
message = event_object.get("message", event_object)
peer_id = message.get("peer_id") peer_id = message.get("peer_id")
action = (message.get("action") or {}).get("type") action = (message.get("action") or {}).get("type")
if peer_id and int(peer_id) >= 2_000_000_000: if peer_id and int(peer_id) >= 2_000_000_000:
@@ -958,38 +968,14 @@ class BelkiBot:
"independence:self": "сам", "independence:nonself": "несам", "independence:self": "сам", "independence:nonself": "несам",
}.get(str(value)) }.get(str(value))
def events(self) -> Iterator[dict[str, Any]]: def run_forever(self, *, callback_host: str, callback_port: int, callback_secret: str,
""" callback_confirmation: str) -> None:
Генератор событий из Long Poll сервера VK. """Run the Callback API listener, notifications and scheduler."""
if not callback_secret:
raise RuntimeError("VK_CALLBACK_SECRET is required")
if not callback_confirmation:
raise RuntimeError("VK_CALLBACK_CONFIRMATION is required")
Перезапускает подключение при сетевых и SSL-ошибках, не завершая процесс.
"""
while True:
try:
poll = self.client.call("groups.getLongPollServer", {"group_id": self.group_id})
server, key, ts = poll["server"], poll["key"], poll["ts"]
while True:
query = urlencode({"act": "a_check", "key": key, "wait": 25, "ts": ts})
try:
with urlopen(f"{server}?{query}", timeout=35) as response:
payload = json.load(response)
except (OSError, TimeoutError, URLError) as exc:
logger.warning("VK Long Poll connection failed; reconnecting: %s", exc)
time.sleep(1)
break
if payload.get("ts"):
ts = payload["ts"]
if payload.get("failed"):
logger.warning("VK Long Poll requested a new server: failed=%s", payload["failed"])
break
for event in payload.get("updates", []):
yield event
except (OSError, TimeoutError, URLError, VkError) as exc:
logger.warning("VK Long Poll setup failed; retrying: %s", exc)
time.sleep(1)
def run_forever(self) -> None:
"""Бесконечный цикл обработки событий."""
def notification_loop() -> None: def notification_loop() -> None:
"""Периодически отправляет уведомления о принятых заявках.""" """Периодически отправляет уведомления о принятых заявках."""
while True: while True:
@@ -998,8 +984,21 @@ class BelkiBot:
time.sleep(15) time.sleep(15)
threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start() threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start()
threading.Thread(target=self.scheduler.run_forever, name="belki-vk-scheduler", daemon=True).start() threading.Thread(target=self.scheduler.run_forever, name="belki-vk-scheduler", daemon=True).start()
for event in self.events(): callback_server = CallbackHTTPServer(
self.handle_event(event) (callback_host, callback_port),
process_callback,
expected_secret=callback_secret,
group_id=self.group_id,
confirmation=callback_confirmation,
claim_event=self.conversation_store.claim_callback_event,
release_event=self.conversation_store.release_callback_event,
handle_event=self.handle_event,
)
logger.info("VK Callback API listening on %s:%s", callback_host, callback_port)
try:
callback_server.serve_forever()
finally:
callback_server.server_close()
class BelkiDialog: class BelkiDialog:
@@ -1767,7 +1766,12 @@ def main() -> None:
group_id = int(os.environ["VK_GROUP_ID"]) group_id = int(os.environ["VK_GROUP_ID"])
version = os.getenv("VK_API_VERSION", "5.199") version = os.getenv("VK_API_VERSION", "5.199")
bot = BelkiBot(VkApiClient(token, version), group_id) bot = BelkiBot(VkApiClient(token, version), group_id)
bot.run_forever() bot.run_forever(
callback_host=os.getenv("VK_CALLBACK_HOST", "0.0.0.0"),
callback_port=int(os.getenv("VK_CALLBACK_PORT", "8081")),
callback_secret=os.environ["VK_CALLBACK_SECRET"],
callback_confirmation=os.environ["VK_CALLBACK_CONFIRMATION"],
)
if __name__ == "__main__": if __name__ == "__main__":
+138
View File
@@ -0,0 +1,138 @@
"""VK Callback API transport and request validation."""
from __future__ import annotations
import json
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Callable
@dataclass(frozen=True)
class CallbackResponse:
"""HTTP response returned by the pure callback processor."""
status: int
body: str
class CallbackRequestError(ValueError):
"""Raised when VK sends an invalid callback request."""
def process_callback(
payload: dict[str, Any],
*,
secret: str,
expected_secret: str,
group_id: int,
confirmation: str,
claim_event: Callable[[str, str], bool] | None,
release_event: Callable[[str], None] | None,
handle_event: Callable[[dict[str, Any]], None],
) -> CallbackResponse:
"""Validate and dispatch one VK Callback API payload.
The function returns a response before the caller writes it to the socket,
which keeps HTTP transport concerns separate from bot event processing.
"""
if expected_secret and secret != expected_secret:
return CallbackResponse(403, "forbidden")
if not isinstance(payload, dict):
return CallbackResponse(400, "invalid payload")
if int(payload.get("group_id", 0) or 0) != int(group_id):
return CallbackResponse(400, "invalid group_id")
event_type = str(payload.get("type", ""))
if event_type == "confirmation":
if not confirmation:
return CallbackResponse(503, "confirmation is not configured")
return CallbackResponse(200, confirmation)
event_id = payload.get("event_id")
if event_id is None and isinstance(payload.get("object"), dict):
event_id = payload["object"].get("event_id")
if event_id is not None and claim_event is not None:
if not claim_event(str(event_id), event_type):
return CallbackResponse(200, "ok")
try:
handle_event(payload)
except Exception:
if event_id is not None and release_event is not None:
release_event(str(event_id))
raise
return CallbackResponse(200, "ok")
class CallbackHTTPServer(ThreadingHTTPServer):
"""Threaded HTTP server bound to a Belki callback processor."""
daemon_threads = True
allow_reuse_address = True
def __init__(self, address: tuple[str, int], processor: Callable[..., CallbackResponse], *,
expected_secret: str, group_id: int, confirmation: str, claim_event: Callable[[str, str], bool] | None,
release_event: Callable[[str], None] | None,
handle_event: Callable[[dict[str, Any]], None]) -> None:
super().__init__(address, CallbackRequestHandler)
self.processor = processor
self.expected_secret = expected_secret
self.group_id = group_id
self.confirmation = confirmation
self.claim_event = claim_event
self.release_event = release_event
self.handle_event = handle_event
class CallbackRequestHandler(BaseHTTPRequestHandler):
"""Minimal HTTP adapter for VK callback requests and health checks."""
server: CallbackHTTPServer
max_body_bytes = 2 * 1024 * 1024
def do_GET(self) -> None: # noqa: N802
if self.path == "/health":
self._write(200, "ok")
return
self._write(404, "not found")
def do_POST(self) -> None: # noqa: N802
if self.path != "/api/vk/callback":
self._write(404, "not found")
return
try:
length = int(self.headers.get("Content-Length", "0"))
if length <= 0 or length > self.max_body_bytes:
raise CallbackRequestError("invalid body size")
payload = json.loads(self.rfile.read(length))
if not isinstance(payload, dict):
raise CallbackRequestError("payload must be an object")
response = self.server.processor(
payload,
secret=str(payload.get("secret", "")),
expected_secret=self.server.expected_secret,
group_id=self.server.group_id,
confirmation=self.server.confirmation,
claim_event=self.server.claim_event,
release_event=self.server.release_event,
handle_event=self.server.handle_event,
)
except (CallbackRequestError, TypeError, ValueError, json.JSONDecodeError):
self._write(400, "invalid payload")
return
except Exception:
self._write(500, "internal error")
return
self._write(response.status, response.body)
def _write(self, status: int, body: str) -> None:
encoded = body.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(encoded)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(encoded)
def log_message(self, format: str, *args: object) -> None:
return
+38
View File
@@ -86,6 +86,9 @@ class VkConversationStore:
"""CREATE TABLE IF NOT EXISTS vk_dialog_states ( """CREATE TABLE IF NOT EXISTS vk_dialog_states (
actor_id BIGINT PRIMARY KEY, state_json TEXT NOT NULL, pending_json TEXT NOT NULL, actor_id BIGINT PRIMARY KEY, state_json TEXT NOT NULL, pending_json TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)""", updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)""",
"""CREATE TABLE IF NOT EXISTS vk_callback_events (
event_id TEXT PRIMARY KEY, event_type TEXT NOT NULL,
received_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)""",
] ]
if self._postgres: if self._postgres:
with self._psycopg.connect(self.database_url) as conn: with self._psycopg.connect(self.database_url) as conn:
@@ -164,6 +167,41 @@ class VkConversationStore:
"""Remove a completed or cancelled dialog from durable storage.""" """Remove a completed or cancelled dialog from durable storage."""
self._execute("DELETE FROM vk_dialog_states WHERE actor_id=?", (int(actor_id),)) self._execute("DELETE FROM vk_dialog_states WHERE actor_id=?", (int(actor_id),))
def claim_callback_event(self, event_id: str, event_type: str) -> bool:
"""Claim a callback event once, preventing duplicate VK deliveries."""
if not event_id.strip():
return True
now = datetime.now(timezone.utc)
try:
self._execute(
"INSERT INTO vk_callback_events(event_id,event_type,received_at) VALUES(?,?,?)",
(event_id[:255], event_type[:100], now.isoformat()),
)
return True
except Exception:
# A unique-key collision is a duplicate; an unavailable database
# must propagate so VK retries the callback instead of losing it.
rows = self._execute(
"SELECT event_id FROM vk_callback_events WHERE event_id=?",
(event_id[:255],), fetch=True,
) or []
if rows:
return False
raise
finally:
try:
self._execute(
"DELETE FROM vk_callback_events WHERE received_at<?",
((now - timedelta(days=7)).isoformat(),),
)
except Exception:
pass
def release_callback_event(self, event_id: str) -> None:
"""Release a failed callback claim so VK can retry the event."""
if event_id.strip():
self._execute("DELETE FROM vk_callback_events WHERE event_id=?", (event_id[:255],))
def create_template(self, name: str, text: str, *, active: bool = True, starts_on: str | None = None, ends_on: str | None = None) -> int: def create_template(self, name: str, text: str, *, active: bool = True, starts_on: str | None = None, ends_on: str | None = None) -> int:
if not text.strip() or len(text) > 4096: raise ValueError("Текст шаблона должен быть от 1 до 4096 символов") if not text.strip() or len(text) > 4096: raise ValueError("Текст шаблона должен быть от 1 до 4096 символов")
rows = self._execute("INSERT INTO vk_message_templates(name,text,active,starts_on,ends_on) VALUES(?,?,?,?,?) RETURNING id", (name.strip() or "Без названия", text.strip(), active, starts_on, ends_on), fetch=True) rows = self._execute("INSERT INTO vk_message_templates(name,text,active,starts_on,ends_on) VALUES(?,?,?,?,?) RETURNING id", (name.strip() or "Без названия", text.strip(), active, starts_on, ends_on), fetch=True)
+41
View File
@@ -118,14 +118,55 @@ spec:
name: belki-vk name: belki-vk
key: VK_API_VERSION key: VK_API_VERSION
optional: true optional: true
- name: VK_CALLBACK_SECRET
valueFrom:
secretKeyRef:
name: belki-vk
key: VK_CALLBACK_SECRET
- name: VK_CALLBACK_CONFIRMATION
valueFrom:
secretKeyRef:
name: belki-vk
key: VK_CALLBACK_CONFIRMATION
- name: BELKI_DATABASE_URL - name: BELKI_DATABASE_URL
valueFrom: valueFrom:
secretKeyRef: secretKeyRef:
name: belki-vk name: belki-vk
key: BELKI_DATABASE_URL key: BELKI_DATABASE_URL
ports:
- name: callback
containerPort: 8081
readinessProbe:
httpGet:
path: /health
port: callback
initialDelaySeconds: 3
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: callback
initialDelaySeconds: 10
periodSeconds: 20
securityContext: securityContext:
allowPrivilegeEscalation: false allowPrivilegeEscalation: false
readOnlyRootFilesystem: true readOnlyRootFilesystem: true
runAsNonRoot: true runAsNonRoot: true
runAsUser: 10001 runAsUser: 10001
---
apiVersion: v1
kind: Service
metadata:
name: belki-bot
namespace: belki
labels:
app.kubernetes.io/part-of: belki-calculator
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: belki-bot
ports:
- name: callback
port: 8081
targetPort: callback
# app.yaml defines the app production resource; keep namespace and secret references aligned with belki. # app.yaml defines the app production resource; keep namespace and secret references aligned with belki.
+42
View File
@@ -194,6 +194,9 @@ spec:
image: reg.nyan404.ru/cwshed-clone/belki:6656484 image: reg.nyan404.ru/cwshed-clone/belki:6656484
imagePullPolicy: IfNotPresent imagePullPolicy: IfNotPresent
command: ["python", "-m", "app.belki.vk_bot"] command: ["python", "-m", "app.belki.vk_bot"]
ports:
- name: callback
containerPort: 8081
env: env:
- name: VK_GROUP_TOKEN - name: VK_GROUP_TOKEN
valueFrom: valueFrom:
@@ -210,6 +213,16 @@ spec:
secretKeyRef: secretKeyRef:
name: belki-runtime name: belki-runtime
key: VK_API_VERSION key: VK_API_VERSION
- name: VK_CALLBACK_SECRET
valueFrom:
secretKeyRef:
name: belki-runtime
key: VK_CALLBACK_SECRET
- name: VK_CALLBACK_CONFIRMATION
valueFrom:
secretKeyRef:
name: belki-runtime
key: VK_CALLBACK_CONFIRMATION
- name: BELKI_DATABASE_URL - name: BELKI_DATABASE_URL
valueFrom: valueFrom:
secretKeyRef: secretKeyRef:
@@ -227,4 +240,33 @@ spec:
value: https://cat.nyan404.ru value: https://cat.nyan404.ru
- name: BELKI_S3_SECURE - name: BELKI_S3_SECURE
value: "false" value: "false"
readinessProbe:
httpGet:
path: /health
port: callback
initialDelaySeconds: 3
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: callback
initialDelaySeconds: 10
periodSeconds: 20
---
apiVersion: v1
kind: Service
metadata:
name: belki-bot
namespace: belki
labels:
app.kubernetes.io/name: belki-bot
app.kubernetes.io/part-of: belki-calculator
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: belki-bot
ports:
- name: callback
port: 8081
targetPort: callback
# production.yaml defines the production production resource; keep namespace and secret references aligned with belki. # production.yaml defines the production production resource; keep namespace and secret references aligned with belki.
+2
View File
@@ -8,6 +8,8 @@ stringData:
VK_GROUP_TOKEN: replace-out-of-band VK_GROUP_TOKEN: replace-out-of-band
VK_GROUP_ID: replace-out-of-band VK_GROUP_ID: replace-out-of-band
VK_API_VERSION: "5.199" VK_API_VERSION: "5.199"
VK_CALLBACK_SECRET: replace-out-of-band
VK_CALLBACK_CONFIRMATION: replace-out-of-band
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
POSTGRES_PASSWORD: replace-out-of-band POSTGRES_PASSWORD: replace-out-of-band
BELKI_ADMIN_PASSWORD: replace-out-of-band BELKI_ADMIN_PASSWORD: replace-out-of-band
+9
View File
@@ -114,6 +114,15 @@ http {
proxy_pass http://10.12.0.212/sudoku/; proxy_pass http://10.12.0.212/sudoku/;
} }
location = /api/vk/callback {
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://belki-bot:8081/api/vk/callback;
}
location ^~ /api/ { location ^~ /api/ {
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
+49 -19
View File
@@ -1,7 +1,5 @@
import unittest import unittest
import json import json
from unittest.mock import patch
from urllib.error import URLError
from app.belki.vk_bot import ( from app.belki.vk_bot import (
BelkiDialog, BelkiDialog,
@@ -12,31 +10,63 @@ from app.belki.vk_bot import (
BelkiBot, BelkiBot,
extract_photo_attachments, extract_photo_attachments,
) )
from app.belki.vk_callback import process_callback
class VkBotTests(unittest.TestCase): class VkBotTests(unittest.TestCase):
def test_long_poll_reconnects_after_ssl_error(self): def test_callback_confirmation_requires_valid_secret_and_group(self):
handler = lambda event: None
response = process_callback(
{"type": "confirmation", "group_id": 1, "secret": "secret"},
secret="secret", expected_secret="secret", group_id=1,
confirmation="confirm-me", claim_event=None, release_event=None,
handle_event=handler,
)
self.assertEqual((response.status, response.body), (200, "confirm-me"))
self.assertEqual(
process_callback(
{"type": "confirmation", "group_id": 1, "secret": "wrong"},
secret="wrong", expected_secret="secret", group_id=1,
confirmation="confirm-me", claim_event=None, release_event=None,
handle_event=handler,
).status,
403,
)
def test_callback_event_is_claimed_once(self):
handled = []
claimed = set()
def claim(event_id, event_type):
if event_id in claimed:
return False
claimed.add(event_id)
return True
payload = {"type": "message_new", "group_id": 1, "secret": "secret", "event_id": "evt-1"}
kwargs = dict(secret="secret", expected_secret="secret", group_id=1,
confirmation="confirm-me", claim_event=claim, release_event=None,
handle_event=handled.append)
self.assertEqual(process_callback(payload, **kwargs).body, "ok")
self.assertEqual(process_callback(payload, **kwargs).body, "ok")
self.assertEqual(handled, [payload])
def test_message_event_callback_is_normalized_to_button_message(self):
class Client: class Client:
def __init__(self): def __init__(self): self.sent = []
self.calls = 0 def send(self, *args, **kwargs): self.sent.append((args, kwargs))
def call(self, method, params):
self.calls += 1
return {"server": "https://vk.example/longpoll", "key": "key", "ts": str(self.calls)}
class Response:
def __enter__(self): return self
def __exit__(self, *args): return False
def __iter__(self): return iter(())
def read(self): return b'{"ts":"2","updates":[{"type":"message_new"}]}'
bot = BelkiBot.__new__(BelkiBot) bot = BelkiBot.__new__(BelkiBot)
bot.client = Client() bot.client = Client()
bot.group_id = 1 bot.group_id = 1
events = bot.events() bot.application_dialog = type("ApplicationDialog", (), {"is_application_command": lambda *_: False, "handle": lambda *_: None, "keyboard_for": lambda *_: None})()
with patch("app.belki.vk_bot.urlopen", side_effect=[URLError("handshake timeout"), Response()]), patch("app.belki.vk_bot.time.sleep"): bot.dialog = type("Dialog", (), {"handle": lambda *_args, **_kwargs: "Ответ", "keyboard_for": lambda *_: None})()
self.assertEqual(next(events)["type"], "message_new") bot.conversation_store = type("Store", (), {})()
self.assertEqual(bot.client.calls, 2) bot.handle_event({"type": "message_event", "object": {
"peer_id": 42, "user_id": 42, "payload": '{"command":"menu:help"}',
}})
self.assertEqual(bot.client.sent[0][0][0], 42)
self.assertEqual(bot.client.sent[0][0][1], "Ответ")
def test_public_chat_messages_are_ignored_but_invite_is_registered(self): def test_public_chat_messages_are_ignored_but_invite_is_registered(self):
class Client: class Client:
def __init__(self): self.sent = [] def __init__(self): self.sent = []
+68
View File
@@ -0,0 +1,68 @@
import http.client
import json
import threading
import unittest
from app.belki.vk_callback import CallbackHTTPServer, process_callback
class VkCallbackHTTPTests(unittest.TestCase):
def test_http_callback_confirms_and_dispatches_once(self):
handled = []
claimed = set()
def claim(event_id, event_type):
if event_id in claimed:
return False
claimed.add(event_id)
return True
server = CallbackHTTPServer(
("127.0.0.1", 0), process_callback,
expected_secret="secret", group_id=7, confirmation="confirm",
claim_event=claim, release_event=claimed.discard,
handle_event=handled.append,
)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=2)
body = json.dumps({"type": "confirmation", "group_id": 7, "secret": "secret"})
connection.request("POST", "/api/vk/callback", body, {"Content-Type": "application/json"})
response = connection.getresponse()
self.assertEqual((response.status, response.read().decode()), (200, "confirm"))
event = {"type": "message_new", "group_id": 7, "secret": "secret", "event_id": "evt-1"}
for _ in range(2):
connection.request("POST", "/api/vk/callback", json.dumps(event), {"Content-Type": "application/json"})
response = connection.getresponse()
self.assertEqual((response.status, response.read().decode()), (200, "ok"))
self.assertEqual(handled, [event])
finally:
connection.close()
server.shutdown()
thread.join(timeout=2)
server.server_close()
def test_health_endpoint_is_available_for_kubernetes_probe(self):
server = CallbackHTTPServer(
("127.0.0.1", 0), process_callback,
expected_secret="secret", group_id=7, confirmation="confirm",
claim_event=None, release_event=None, handle_event=lambda event: None,
)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=2)
connection.request("GET", "/health")
response = connection.getresponse()
self.assertEqual((response.status, response.read().decode()), (200, "ok"))
finally:
connection.close()
server.shutdown()
thread.join(timeout=2)
server.server_close()
if __name__ == "__main__":
unittest.main()
+8
View File
@@ -242,6 +242,14 @@ class VkConversationTests(unittest.TestCase):
self.assertIn("подтверд", confirmation.lower()) self.assertIn("подтверд", confirmation.lower())
self.assertEqual(recreated._states[204]["attachments"][0]["url"], "https://example.test/history.jpg") self.assertEqual(recreated._states[204]["attachments"][0]["url"], "https://example.test/history.jpg")
def test_callback_event_claim_is_idempotent_and_releasable(self):
with TemporaryDirectory() as directory:
store = VkConversationStore(sqlite_path=f"{directory}/vk.sqlite3")
self.assertTrue(store.claim_callback_event("event-1", "message_new"))
self.assertFalse(store.claim_callback_event("event-1", "message_new"))
store.release_callback_event("event-1")
self.assertTrue(store.claim_callback_event("event-1", "message_new"))
def test_inspection_character_without_directory_offers_pairing(self): def test_inspection_character_without_directory_offers_pairing(self):
dialog = BelkiDialog(IdentityDirectory()) dialog = BelkiDialog(IdentityDirectory())
dialog.handle(105, "/осмотр") dialog.handle(105, "/осмотр")