// FakeTelegramService and the TableService contract: every declared method answers, bad params are rejected and counted,
// events reach sinks, cancel works, Premium behaves three ways (FR-66).
#include <deque>
#include "tttest.hpp"
#include "mologram/FakeTelegramService.hpp"
using namespace mologram;
using js::Array;
using js::Object;
using js::Value;
namespace {
struct Sink : IEventSink {
std::vector<Event> events;
void onEvent(const Event& e) override { events.push_back(e); }
int count(const std::string& n) const { int c = 0; for (auto& e : events) if (e.name == n) c++; return c; }
};
RpcResult run(ITelegramService& s, const std::string& m, Object p = {}) {
RpcResult out; bool called = false;
s.call(m, Value(std::move(p)), [&](const RpcResult& r) { out = r; called = true; });
if (!called) return RpcResult::failure("test", "callback not called synchronously");
return out;
}
Value peerV(const char* k) { return Value(std::string(k)); }
/// Fake whose jobs wait in a queue, to test cancel before start.
struct DeferredFake : FakeTelegramService {
std::deque<std::function<void()>> q;
void execute(std::function<void()> job) override { q.push_back(std::move(job)); }
void drain() { while (!q.empty()) { auto j = q.front(); q.pop_front(); j(); } }
};
} // namespace
TEST_CASE("every declared protocol method has a handler", "[service][unit]") {
FakeTelegramService s;
for (const auto& m : ProtocolMethods::all()) {
Object p;
for (const auto& name : m.required()) {
if (name == "peer" || name == "from" || name == "to" || name == "user") p[name] = peerV("user:100");
else if (name == "ids" || name == "options" || name == "reactions") p[name] = Value(Array{});
else if (name == "on") p[name] = Value(true);
else if (name == "fields" || name == "settings" || name == "folder" || name == "recipients") p[name] = Value(Object{});
else if (name == "who") p[name] = Value(std::string("everyone"));
else if (name == "stars") p[name] = Value(3);
else if (name == "reaction") p[name] = Value(Object{{"emoji", Value("A")}});
else p[name] = Value(std::string("x"));
}
RpcResult r = run(s, m.name, p);
CHECK(!(r.error.code == ErrorCode::UnknownMethod));
CHECK(!(r.error.code == ErrorCode::BadParams));
}
CHECK_EQ((int)s.rejectedCalls(), 0);
}
TEST_CASE("unknown method and bad params are rejected and counted", "[service][unit]") {
FakeTelegramService s;
CHECK_EQ(run(s, "nope").error.code, std::string(ErrorCode::UnknownMethod));
CHECK_EQ(run(s, "messages.send", {{"peer", peerV("user:100")}}).error.code, std::string(ErrorCode::BadParams));
CHECK_EQ(run(s, "messages.send", {{"peer", peerV("user:100")}, {"text", Value("a")}, {"junk", Value(1)}}).error.code, std::string(ErrorCode::BadParams));
CHECK_EQ((int)s.rejectedCalls(), 3);
}
TEST_CASE("send message updates history, preview and emits message.new", "[service][unit]") {
FakeTelegramService s; Sink sink; s.addSink(&sink);
RpcResult r = run(s, "messages.send", {{"peer", peerV("user:100")}, {"text", Value("hello")}});
REQUIRE(r.ok);
Message m = Message::fromJson(r.value);
CHECK(m.outgoing); CHECK_EQ(m.text, std::string("hello"));
CHECK_EQ(sink.count("message.new"), 1);
RpcResult h = run(s, "messages.history", {{"peer", peerV("user:100")}, {"count", Value(1)}});
REQUIRE(h.ok);
CHECK_EQ(js::getStr(*js::getArr(h.value, "messages")->begin(), "text"), std::string("hello"));
CHECK_EQ(s.dialogs()[1].preview, std::string("hello"));
s.removeSink(&sink);
run(s, "messages.send", {{"peer", peerV("user:100")}, {"text", Value("again")}});
CHECK_EQ(sink.count("message.new"), 1);
}
TEST_CASE("history pages older and newer without gaps", "[service][unit]") {
FakeTelegramService s;
auto page = [&](const char* dir, std::int64_t off, int n) {
RpcResult r = run(s, "messages.history", {{"peer", peerV("user:100")}, {"offset_id", js::id(off)}, {"direction", Value(dir)}, {"count", Value(n)}});
std::vector<std::int64_t> ids; for (auto& e : *js::getArr(r.value, "messages")) ids.push_back(js::getId(e, "id")); return ids;
};
auto first = page("older", 0, 10);
REQUIRE(first.size() == 10);
auto older = page("older", first.front(), 10);
REQUIRE(older.size() == 10);
CHECK_EQ(older.back() + 1, first.front());
auto newer = page("newer", older.back(), 10);
CHECK_EQ(newer.front(), first.front());
}
TEST_CASE("edit of a foreign message and send of empty text return server style errors", "[service][unit]") {
FakeTelegramService s;
auto h = run(s, "messages.history", {{"peer", peerV("user:100")}, {"count", Value(3)}});
std::int64_t foreign = 0;
for (auto& e : *js::getArr(h.value, "messages")) if (!js::getBool(e, "out")) foreign = js::getId(e, "id");
REQUIRE(foreign != 0);
CHECK_EQ(run(s, "messages.edit", {{"peer", peerV("user:100")}, {"id", js::id(foreign)}, {"text", Value("x")}}).error.text, std::string("MESSAGE_AUTHOR_REQUIRED"));
CHECK_EQ(run(s, "messages.send", {{"peer", peerV("user:100")}, {"text", Value("")}}).error.text, std::string("MESSAGE_EMPTY"));
}
TEST_CASE("cancel before start yields cancelled and the callback still runs once", "[service][unit]") {
DeferredFake s;
int calls = 0; RpcResult got;
RequestId id = s.call("dialogs.folders", Value(Object{}), [&](const RpcResult& r) { calls++; got = r; });
s.cancel(id);
s.drain();
CHECK_EQ(calls, 1);
CHECK_EQ(got.error.code, std::string(ErrorCode::Cancelled));
}
TEST_CASE("login flow: phone, code, password", "[service][unit]") {
FakeTelegramService s; s.setLoggedIn(false);
CHECK_EQ(js::getStr(run(s, "auth.state").value, "state"), std::string("need_phone"));
run(s, "auth.send_phone", {{"phone", Value("+1")}});
CHECK_EQ(run(s, "auth.send_code", {{"code", Value("00000")}}).error.text, std::string("PHONE_CODE_INVALID"));
run(s, "auth.send_code", {{"code", Value("12345")}});
CHECK_EQ(run(s, "auth.send_password", {{"password", Value("bad")}}).error.text, std::string("PASSWORD_HASH_INVALID"));
run(s, "auth.send_password", {{"password", Value("secret")}});
CHECK_EQ(js::getStr(run(s, "auth.state").value, "state"), std::string("ready"));
}
TEST_CASE("premium three ways: premium, not premium, premium lost midway", "[service][premium][unit]") {
Object two; Array rs;
Reaction a; a.emoji = "A"; Reaction b; b.emoji = "B";
rs.push_back(a.toJson()); rs.push_back(b.toJson());
two["peer"] = peerV("user:100"); two["id"] = js::id(1); two["reactions"] = Value(rs);
auto firstIdOf = [](FakeTelegramService& s) {
auto h = run(s, "messages.history", {{"peer", peerV("user:100")}, {"count", Value(1)}});
return js::getId(*js::getArr(h.value, "messages")->begin(), "id");
};
{ // Premium: allowed
FakeTelegramService s; s.setPremium(PremiumState::Premium);
two["id"] = js::id(firstIdOf(s));
CHECK(run(s, "messages.react", two).ok);
CHECK(run(s, "premium.transcribe", {{"peer", peerV("user:100")}, {"id", js::id(1)}}).ok);
}
{ // NotPremium: refused with the typed code, one reaction still fine
FakeTelegramService s; s.setPremium(PremiumState::NotPremium);
two["id"] = js::id(firstIdOf(s));
CHECK_EQ(run(s, "messages.react", two).error.code, std::string(ErrorCode::PremiumRequired));
Object one = two; one["reactions"] = Value(Array{rs[0]});
CHECK(run(s, "messages.react", one).ok);
CHECK_EQ(run(s, "premium.translate", {{"peer", peerV("user:100")}, {"id", two["id"]}, {"to", Value("nl")}}).error.code, std::string(ErrorCode::PremiumRequired));
}
{ // Premium lost midway: client still told premium, server refuses; state event flips it
FakeTelegramService s; Sink sink; s.addSink(&sink); s.setPremium(PremiumState::Premium);
two["id"] = js::id(firstIdOf(s));
CHECK(run(s, "messages.react", two).ok);
s.revokePremiumSilently();
CHECK_EQ(js::getStr(run(s, "premium.state").value, "state"), std::string("premium"));
CHECK_EQ(run(s, "messages.react", two).error.code, std::string(ErrorCode::PremiumRequired));
s.setPremium(PremiumState::NotPremium);
CHECK_EQ(js::getStr(run(s, "premium.state").value, "state"), std::string("not_premium"));
CHECK_EQ(sink.count("premium.changed"), 2);
}
}
TEST_CASE("simulated incoming message raises unread and emits", "[service][unit]") {
FakeTelegramService s; Sink sink; s.addSink(&sink);
int before = s.dialogs()[2].unread;
s.simulateIncoming({PeerKind::User, 101}, "ping");
CHECK_EQ(s.dialogs()[2].unread, before + 1);
CHECK_EQ(sink.count("message.new"), 1);
CHECK(run(s, "dialogs.mark_read", {{"peer", peerV("user:101")}}).ok);
CHECK_EQ(s.dialogs()[2].unread, 0);
}