Files
uPortal2/bots/_smoke_test.py
T

173 lines
5.3 KiB
Python

"""Offline smoke test for the bot (no network). Run: python bots/_smoke_test.py"""
import os
import sys
import tempfile
from datetime import datetime, timedelta, timezone
try:
sys.stdout.reconfigure(encoding="utf-8")
except (AttributeError, ValueError):
pass
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from meetings_telegram_bot.api import Meeting
from meetings_telegram_bot.bot import MeetingsBot
from meetings_telegram_bot.config import Config
from meetings_telegram_bot.state import StateStore
now = datetime.now(timezone.utc)
def mk(i, title="T", room=None, sched=None, has_notification=True):
return Meeting(
id=i,
title=title,
intent="about " + title,
room=room or ("room-%d" % i),
scheduled_at=sched or (now + timedelta(hours=1)),
created_by=1,
created_by_name="Roman",
created_at=now,
has_notification=has_notification,
)
class FakeApi:
session_token = "sess"
csrf_token = "csrf"
has_session = True
def __init__(self, meetings):
self._m = meetings
def restore_session(self, a, b):
pass
def still_authenticated(self):
return True
def signin(self, *a, **k):
raise AssertionError("should not sign in")
def list_meetings(self, limit=200, offset=0):
return list(self._m)
class FakeBot:
def __init__(self):
self.sent = []
def send_message(self, chat_id, text, **kw):
self.sent.append((chat_id, text))
return {"message_id": len(self.sent)}
def test_polling():
from meetings_telegram_bot.config import _resolve_timezone
tmp = tempfile.mkdtemp()
tz = _resolve_timezone(os.getenv("TIMEZONE", ""))
cfg = Config(
api_base_url="http://x",
api_login="u",
api_password="p",
bot_token="t",
chat_id="@g",
state_file=os.path.join(tmp, "state.json"),
timezone=tz,
)
print("polling timezone:", tz or "local")
api = FakeApi([mk(1), mk(2), mk(3)])
tb = FakeBot()
b = MeetingsBot(cfg, api=api, bot=tb, store=StateStore(cfg.state_file))
b.start()
assert b.poll_once() == 0 and len(tb.sent) == 0 # first run seeds silently
print("run1 (seed) announced 0 sent 0")
# Fixture meetings are scheduled 1 hour in the future (see mk()).
new_meeting = mk(4, title="Design review")
api._m.append(new_meeting)
b2 = MeetingsBot(cfg, api=api, bot=tb, store=StateStore(cfg.state_file))
b2.start()
assert b2.poll_once() == 1 and len(tb.sent) == 1 # one new meeting posted
print("run2 (new) announced 1 sent 1")
print("scheduled (UTC): %s -> shown as: %s"
% (new_meeting.scheduled_at.strftime("%Y-%m-%d %H:%M"), tz or "local"))
print("--- message ---")
print(tb.sent[0][1])
print("--- end ---")
b3 = MeetingsBot(cfg, api=api, bot=tb, store=StateStore(cfg.state_file))
b3.start()
assert b3.poll_once() == 0 and len(tb.sent) == 1 # no change, no post
print("run3 (no change) announced 0 sent 1")
api._m.append(mk(5, title="Stale", sched=now - timedelta(days=3)))
b4 = MeetingsBot(cfg, api=api, bot=tb, store=StateStore(cfg.state_file))
b4.start()
assert b4.poll_once() == 0 and len(tb.sent) == 1 # stale not posted
print("run4 (stale) announced 0 sent 1")
api._m.append(mk(6, title="Silent", has_notification=False))
b5 = MeetingsBot(cfg, api=api, bot=tb, store=StateStore(cfg.state_file))
b5.start()
assert b5.poll_once() == 0 and len(tb.sent) == 1 # no-notification not posted
assert 6 in b5.state.seen_meeting_ids
print("run5 (no notification) announced 0 sent 1")
print("ALL GOOD")
def test_proxy():
import telebot.apihelper as apihelper
from meetings_telegram_bot.api import GoChatApi
from meetings_telegram_bot.config import load_config
os.environ.update(
API_BASE_URL="http://x",
API_LOGIN="u",
API_PASSWORD="p",
TELEGRAM_BOT_TOKEN="t",
TELEGRAM_CHAT_ID="@g",
SOCKS5_PROXY="socks5://user:pass@127.0.0.1:1080",
)
cfg = load_config()
assert cfg.socks5_proxy == "socks5://user:pass@127.0.0.1:1080"
api = GoChatApi(cfg.api_base_url, proxy=cfg.socks5_proxy)
assert api._http.proxies.get("http") == cfg.socks5_proxy
assert api._http.proxies.get("https") == cfg.socks5_proxy
apihelper.proxy = {"http": cfg.socks5_proxy, "https": cfg.socks5_proxy}
assert apihelper.proxy["https"] == cfg.socks5_proxy
print("proxy wiring OK")
def test_timezone():
from datetime import timezone as dt_timezone
from meetings_telegram_bot.config import _resolve_timezone
from meetings_telegram_bot.messages import format_new_meeting
gmt3 = _resolve_timezone("GMT+3")
assert gmt3.utcoffset(None) == timedelta(hours=3)
assert _resolve_timezone("") is None
assert _resolve_timezone("UTC").utcoffset(None) == timedelta(0)
assert _resolve_timezone("UTC+05:30").utcoffset(None) == timedelta(hours=5, minutes=30)
# A fixed instant to check the rendered hour shifts by +3.
sched = datetime(2026, 1, 1, 12, 0, tzinfo=dt_timezone.utc)
text = format_new_meeting(mk(1, sched=sched), tz=gmt3)
assert "15:00" in text, text # 12:00 UTC rendered as 15:00 at GMT+3
assert "GMT+3" in text, text
print("timezone OK")
if __name__ == "__main__":
test_polling()
test_proxy()
test_timezone()