Files
telegram/tests/session_test.zi
waozi 07fa719408 Announce pinned chats, group sizes and newest messages; fit photo sizes
loadChats now carries each dialog's pin, member count and normalized newest
message so an app can order and preview chats as Telegram does.
downloadMessageFile takes max_edge to fetch a photo size that fits a bubble.
2026-11-16 00:34:01 -03:00

153 lines
19 KiB
Ziran

Session :: #import "session";
Members :: #import "members";
E :: #import "encoding";
Auth :: #import "auth";
TL :: #import "tl";
Time :: #import "std/timer_linux";
c :: #system_library "libc";
ClockProbe :: (clock: s32, value: *Time.ClockValue) -> s32 #foreign c "clock_gettime";
#import "std/json_scan"
#import "std/text"
DialogChecks :: () -> s32 {
failures: s32
// Every dialog becomes a chat with a person's full name, its newest
// message and mute state; the account's own chat is Saved Messages.
Session.head=Session.tail;Session.account.user="{\"@type\":\"user\",\"id\":100}"
dialogs:="{\"@type\":\"messages.dialogsSlice\",\"count\":4,\"dialogs\":[{\"@type\":\"dialog\",\"pinned\":true,\"peer\":{\"@type\":\"peerUser\",\"user_id\":200},\"top_message\":77,\"read_inbox_max_id\":70,\"unread_count\":7,\"notify_settings\":{\"@type\":\"peerNotifySettings\",\"mute_until\":2147483647}},{\"@type\":\"dialog\",\"peer\":{\"@type\":\"peerChannel\",\"channel_id\":5},\"top_message\":9,\"read_inbox_max_id\":9,\"unread_count\":0,\"notify_settings\":{\"@type\":\"peerNotifySettings\"}},{\"@type\":\"dialog\",\"peer\":{\"@type\":\"peerUser\",\"user_id\":100},\"top_message\":3,\"read_inbox_max_id\":3,\"unread_count\":0,\"notify_settings\":{\"@type\":\"peerNotifySettings\"}},{\"@type\":\"dialog\",\"peer\":{\"@type\":\"peerUser\",\"user_id\":300},\"top_message\":4,\"read_inbox_max_id\":4,\"unread_count\":0,\"notify_settings\":{\"@type\":\"peerNotifySettings\"}}],\"messages\":[{\"@type\":\"message\",\"id\":77,\"peer_id\":{\"@type\":\"peerUser\",\"user_id\":200},\"from_id\":{\"@type\":\"peerUser\",\"user_id\":200},\"date\":1794700000,\"message\":\"See you soon\"}],\"chats\":[{\"@type\":\"channel\",\"id\":5,\"title\":\"News\",\"broadcast\":true,\"participants_count\":1200}],\"users\":[{\"@type\":\"user\",\"id\":200,\"first_name\":\"Alice\",\"last_name\":\"Doe\"},{\"@type\":\"user\",\"id\":100,\"first_name\":\"Owner\"},{\"@type\":\"user\",\"id\":300,\"first_name\":\"Helper\",\"bot\":true}]}"
if Session.Announce(dialogs,0)!=4 { failures+=1;print("FAIL every dialog is announced\n") }
person:=Session.Receive(0.0);chat:=FieldAt(person,0,"chat");unused Session.Receive(0.0)
if E.String(person,chat,"title")!="Alice Doe" || E.Number(person,chat,"last_message_id")!=77 || E.Raw(person,FieldAt(person,chat,"is_muted"))!="true" { failures+=1;print("FAIL private chat carries full name, newest message and mute state\n") }
news:=Session.Receive(0.0);chat=FieldAt(news,0,"chat");unused Session.Receive(0.0)
if E.String(news,chat,"title")!="News" || E.Raw(news,FieldAt(news,FieldAt(news,chat,"type"),"is_channel"))!="true" || E.Number(news,chat,"id")!=-1000000000005 || E.Raw(news,FieldAt(news,chat,"is_muted"))!="false" { failures+=1;print("FAIL broadcast channel is announced as a channel\n") }
// Telegram's order needs the pin, the newest message and group sizes.
if E.Raw(news,FieldAt(news,chat,"is_pinned"))!="false" || E.Number(news,chat,"member_count")!=1200 || E.Raw(news,FieldAt(news,chat,"last_message"))!="null" { failures+=1;print("FAIL channel size and absent newest message\n") }
chat=FieldAt(person,0,"chat");last:=FieldAt(person,chat,"last_message")
if E.Raw(person,FieldAt(person,chat,"is_pinned"))!="true" || E.Number(person,last,"id")!=77 || E.Number(person,last,"date")!=1794700000 || E.String(person,FieldAt(person,FieldAt(person,last,"content"),"text"),"text")!="See you soon" { failures+=1;print("FAIL pinned chat carries its newest message\n") }
saved:=Session.Receive(0.0);unused Session.Receive(0.0)
if E.String(saved,FieldAt(saved,0,"chat"),"title")!="Saved Messages" { failures+=1;print("FAIL own chat is Saved Messages\n") }
helper:=Session.Receive(0.0);unused Session.Receive(0.0)
if E.Raw(helper,FieldAt(helper,FieldAt(helper,FieldAt(helper,0,"chat"),"type"),"is_bot"))!="true" { failures+=1;print("FAIL bot chats are marked\n") }
return failures
}
MediaChecks :: () -> s32 {
failures: s32
// The largest photo wins; progressive sizes report their final length.
message:="{\"@type\":\"message\",\"media\":{\"@type\":\"messageMediaPhoto\",\"photo\":{\"@type\":\"photo\",\"id\":5,\"sizes\":[{\"@type\":\"photoStrippedSize\",\"type\":\"i\"},{\"@type\":\"photoSize\",\"type\":\"m\",\"w\":320,\"h\":240,\"size\":9000},{\"@type\":\"photoSizeProgressive\",\"type\":\"y\",\"w\":1280,\"h\":960,\"sizes\":[4000,30000,81234]},{\"@type\":\"photoSize\",\"type\":\"x\",\"w\":800,\"h\":600,\"size\":50000}]}}}"
best:=Session.PhotoSize(message,FieldAt(message,FieldAt(message,0,"media"),"photo"))
if E.String(best,0,"type")!="y" || E.Number(best,0,"size")!=81234 { failures+=1;print("FAIL largest photo size\n") }
// An edge limit takes the largest size within it, or the smallest.
fitting:=Session.PhotoSize(message,FieldAt(message,FieldAt(message,0,"media"),"photo"),800)
if E.String(fitting,0,"type")!="x" { failures+=1;print("FAIL photo size within an edge limit\n") }
tiny:=Session.PhotoSize(message,FieldAt(message,FieldAt(message,0,"media"),"photo"),100)
if E.String(tiny,0,"type")!="m" { failures+=1;print("FAIL smallest photo size when none fits\n") }
return failures
}
LoginWaitChecks :: () -> s32 {
failures: s32
Session.head=Session.tail; Session.account.state="password"
cpu_before: Time.ClockValue; cpu_after: Time.ClockValue
unused ClockProbe(2,*cpu_before)
before:=Time.MonotonicMilliseconds(); empty:=Session.Receive(0.05)
elapsed:=Time.MonotonicMilliseconds()-before
unused ClockProbe(2,*cpu_after)
cpu_ms:=(cpu_after.seconds-cpu_before.seconds)*1000+(cpu_after.nanoseconds-cpu_before.nanoseconds)/1000000
if empty!="" || elapsed<45 || cpu_ms>10 { failures+=1;print("FAIL sign-in receive waits without spinning: wall % ms, CPU % ms\n",elapsed,cpu_ms) }
Session.Push("queued login event");before=Time.MonotonicMilliseconds()
queued:=Session.Receive(0.5);elapsed=Time.MonotonicMilliseconds()-before
if queued!="queued login event" || elapsed>=400 { failures+=1;print("FAIL queued sign-in event is delivered immediately\n") }
before=Time.MonotonicMilliseconds();unused Session.Receive(0.0);unused Session.Receive(-1.0)
if Time.MonotonicMilliseconds()-before>=400 { failures+=1;print("FAIL nonblocking sign-in receive\n") }
print("Telegram sign-in idle receive: wall % ms, CPU % ms\n",50,cpu_ms)
Session.account.state="";return failures
}
CallChecks :: () -> s32 {
failures: s32; Session.head=Session.tail; before := Session.pts
updates: [5]string = .{"{\"@type\":\"updatePhoneCall\",\"phone_call\":{\"@type\":\"phoneCallRequested\",\"id\":9007199254740993}}","{\"@type\":\"updatePhoneCallSignalingData\",\"phone_call_id\":9007199254740993,\"data\":\"AAE=\"}","{\"@type\":\"updateGroupCall\",\"call\":{\"@type\":\"groupCallDiscarded\",\"id\":12}}","{\"@type\":\"updateGroupCallConnection\",\"params\":{\"@type\":\"dataJSON\",\"data\":\"{}\"}}","{\"@type\":\"updateGroupCallParticipants\",\"call\":{\"@type\":\"inputGroupCall\",\"id\":12,\"access_hash\":34},\"participants\":[],\"version\":2}"}
for i: 0..cast(s32)4 { Session.Update(updates[i]); if Session.Receive(0.0) != updates[i] { failures+=1;print("FAIL call update delivery %\n",i) } }
if Session.pts != before { failures+=1;print("FAIL calls do not advance message sequence\n") }
protocol := "{\"@type\":\"phoneCallProtocol\",\"udp_p2p\":true,\"udp_reflector\":true,\"min_layer\":65,\"max_layer\":92,\"library_versions\":[\"13.0.0\"]}"
call: Vec(u8); BuilderPrint(*call,"{\"@type\":\"phone.requestCall\",\"user_id\":{\"@type\":\"inputUser\",\"user_id\":123,\"access_hash\":456},\"random_id\":789,\"g_a_hash\":\"AAE=\",\"protocol\":%}",protocol)
bytes: [4096]u8; if TL.Encode(BuilderFinish(call),bytes[:]) <= 0 { failures+=1;print("FAIL private call serialization\n") }
if TL.Encode("{\"@type\":\"phone.joinGroupCall\",\"call\":{\"@type\":\"inputGroupCall\",\"id\":12,\"access_hash\":34},\"join_as\":{\"@type\":\"inputPeerSelf\"},\"params\":{\"@type\":\"dataJSON\",\"data\":\"{}\"}}",bytes[:]) <= 0 { failures+=1;print("FAIL group call serialization\n") }
return failures
}
MemberChecks :: () -> s32 {
failures: s32
// Supergroup members keep their roles and custom titles; users carry
// presence, bot access and active usernames.
reply := "{\"@type\":\"channels.channelParticipants\",\"count\":6,\"participants\":[{\"@type\":\"channelParticipantCreator\",\"user_id\":10,\"admin_rights\":{\"@type\":\"chatAdminRights\"}},{\"@type\":\"channelParticipantAdmin\",\"user_id\":11,\"promoted_by\":10,\"date\":1,\"admin_rights\":{\"@type\":\"chatAdminRights\"},\"rank\":\"Admin\"},{\"@type\":\"channelParticipant\",\"user_id\":12,\"date\":2},{\"@type\":\"channelParticipantBanned\",\"left\":true,\"peer\":{\"@type\":\"peerUser\",\"user_id\":13},\"kicked_by\":10,\"date\":3,\"banned_rights\":{\"@type\":\"chatBannedRights\",\"until_date\":0}}],\"chats\":[],\"users\":[{\"@type\":\"user\",\"id\":10,\"first_name\":\"Yoel\",\"status\":{\"@type\":\"userStatusRecently\"},\"photo\":{\"@type\":\"userProfilePhoto\",\"photo_id\":9007199254740993,\"dc_id\":2}},{\"@type\":\"user\",\"id\":11,\"self\":true,\"first_name\":\"Martin\",\"last_name\":\"Waozi\",\"usernames\":[{\"@type\":\"username\",\"username\":\"old\"},{\"@type\":\"username\",\"active\":true,\"username\":\"waozi\"}],\"status\":{\"@type\":\"userStatusOffline\",\"was_online\":1760000000}},{\"@type\":\"user\",\"id\":12,\"bot\":true,\"bot_chat_history\":true,\"first_name\":\"funbot\",\"username\":\"funbot\"}]}"
members := Members.Members(reply, 200); rows := FieldAt(members, 0, "members")
if E.Kind(members) != "chatMembers" || E.Number(members, 0, "total_count") != 6 || ArrayCount(members, rows) != 4 { failures += 1; print("FAIL supergroup members: %\n", members) }
roles: [4]string = .{"chatMemberStatusCreator", "chatMemberStatusAdministrator", "chatMemberStatusMember", "chatMemberStatusLeft"}
for i: 0..cast(s32)3 { if E.String(members, FieldAt(members, ElementAt(members, rows, i), "status"), "@type") != roles[i] { failures += 1; print("FAIL member role %\n", i) } }
admin := FieldAt(members, ElementAt(members, rows, 1), "status"); left := FieldAt(members, ElementAt(members, rows, 3), "member_id")
if E.String(members, admin, "custom_title") != "Admin" || E.Number(members, left, "user_id") != 13 { failures += 1; print("FAIL custom title and peer members\n") }
users := FieldAt(members, 0, "users"); owner := ElementAt(members, users, 0); self := ElementAt(members, users, 1); bot := ElementAt(members, users, 2)
if E.String(members, FieldAt(members, owner, "status"), "@type") != "userStatusRecently" || E.String(members, owner, "photo_id") != "9007199254740993" || E.Number(members, owner, "photo_dc") != 2 { failures += 1; print("FAIL owner presence and exact photo ID\n") }
if E.String(members, self, "username") != "waozi" || E.Raw(members, FieldAt(members, self, "is_self")) != "true" || E.Number(members, FieldAt(members, self, "status"), "was_online") != 1760000000 { failures += 1; print("FAIL active username and last seen\n") }
if E.String(members, FieldAt(members, bot, "type"), "@type") != "userTypeBot" || E.Raw(members, FieldAt(members, FieldAt(members, bot, "type"), "can_read_all_group_messages")) != "true" { failures += 1; print("FAIL bot message access\n") }
if ArrayCount(Members.Members(reply, 2), FieldAt(Members.Members(reply, 2), 0, "members")) != 2 { failures += 1; print("FAIL member limit\n") }
// Basic groups list members on their full chat.
basic := Members.Members("{\"@type\":\"messages.chatFull\",\"full_chat\":{\"@type\":\"chatFull\",\"id\":5,\"about\":\"\",\"participants\":{\"@type\":\"chatParticipants\",\"chat_id\":5,\"participants\":[{\"@type\":\"chatParticipantCreator\",\"user_id\":10},{\"@type\":\"chatParticipant\",\"user_id\":12,\"inviter_id\":10,\"date\":2}],\"version\":1}},\"chats\":[],\"users\":[]}", 200)
if E.Number(basic, 0, "total_count") != 2 || E.String(basic, FieldAt(basic, ElementAt(basic, FieldAt(basic, 0, "members"), 0), "status"), "@type") != "chatMemberStatusCreator" { failures += 1; print("FAIL basic group members: %\n", basic) }
// Shared-media counts use one API filter per TDLib filter.
query := Members.CountQuery("{\"@type\":\"inputPeerSelf\"}", Members.Filter("searchMessagesFilterUrl")); encoded: [512]u8
if E.String(query, ElementAt(query, FieldAt(query, 0, "filters"), 0), "@type") != "inputMessagesFilterUrl" || TL.Encode(query, encoded[:]) <= 0 || Members.Filter("searchMessagesFilterPoll") != "" { failures += 1; print("FAIL media counter request\n") }
counted := Members.Count("[{\"@type\":\"messages.searchCounter\",\"filter\":{\"@type\":\"inputMessagesFilterUrl\"},\"count\":136}]")
if E.Kind(counted) != "count" || E.Number(counted, 0, "count") != 136 || E.Number(Members.Count("[]"), 0, "count") != 0 { failures += 1; print("FAIL media counter reply: %\n", counted) }
// Vector replies such as users.getUsers leave the peer cache untouched.
Session.head = Session.tail; peers := Session.peer_count; Session.Cache("[{\"@type\":\"user\",\"id\":5,\"access_hash\":6}]")
if Session.peer_count != peers || Session.head != Session.tail { failures += 1; print("FAIL vector reply cache\n") }
// Group details carry the member count and description.
group := Session.GroupReply("{\"@type\":\"messages.chatFull\",\"full_chat\":{\"@type\":\"channelFull\",\"id\":7,\"about\":\"Shared projects\",\"participants_count\":6,\"migrated_from_chat_id\":5323743735},\"chats\":[{\"@type\":\"channel\",\"id\":7,\"title\":\"Agent Lab\",\"megagroup\":true}],\"users\":[]}")
if E.Number(group, 0, "member_count") != 6 || E.String(group, 0, "description") != "Shared projects" || E.Number(group, 0, "upgraded_from_chat_id") != -5323743735 { failures += 1; print("FAIL group member count and upgraded basic group: %\n", group) }
return failures
}
Main :: () -> s32 {
failures: s32 = LoginWaitChecks()
query := Session.GroupQuery("{\"title\":\"Errors\",\"description\":\"Command and task failures\"}")
group_encoded: [4096]u8
send := Session.TextQuery("{\"random_id\":9007199254740993,\"input_message_content\":{\"text\":{\"text\":\"Errors summary\"}}}", "{\"@type\":\"inputPeerSelf\"}")
if E.Number(send, 0, "random_id") != 9007199254740993 || TL.Encode(send, group_encoded[:]) <= 0 { failures += 1; print("FAIL durable message identity serialization\n") }
first_send := Session.TextQuery("{}", "{\"@type\":\"inputPeerSelf\"}"); second_send := Session.TextQuery("{}", "{\"@type\":\"inputPeerSelf\"}")
if E.Number(first_send, 0, "random_id") == 0 || E.Number(first_send, 0, "random_id") == E.Number(second_send, 0, "random_id") { failures += 1; print("FAIL fresh identities for ordinary messages\n") }
if E.Kind(query) != "channels.createChannel" || E.Raw(query, FieldAt(query, 0, "megagroup")) != "true" || TL.Encode(query, group_encoded[:]) <= 0 || Session.GroupQuery("{}") != "" { failures += 1; print("FAIL private group creation serialization\n") }
created := Session.GroupReply("{\"@type\":\"updates\",\"chats\":[{\"@type\":\"channel\",\"id\":321,\"title\":\"Errors\",\"megagroup\":true,\"creator\":true}]}")
if E.Number(created, 0, "id") != -1000000000321 || E.Raw(created, FieldAt(created, 0, "is_private")) != "true" || E.Raw(created, FieldAt(created, 0, "is_creator")) != "true" { failures += 1; print("FAIL created private group receipt: %\n", created) }
public := Session.GroupReply("{\"chats\":[{\"@type\":\"channel\",\"id\":321,\"username\":\"public_errors\",\"megagroup\":true}]}")
if E.Raw(public, FieldAt(public, 0, "is_private")) != "false" || E.Kind(Session.GroupReply("{\"@type\":\"rpc_error\",\"error_code\":420}")) != "rpc_error" { failures += 1; print("FAIL group privacy and RPC failures\n") }
Session.pts=10;Session.date=100
Session.Update("{\"@type\":\"updateShortMessage\",\"id\":12,\"user_id\":66,\"message\":\"Hello 🙂\",\"pts\":11,\"pts_count\":1,\"date\":101}")
first:=Session.Receive(0.0);message:=E.Raw(first,FieldAt(first,0,"message"))
// Check the normalized object rather than any serializer whitespace.
content:=FieldAt(message,0,"content")
if E.Kind(first)!="updateNewMessage" || Session.pts!=11 || E.Number(message,0,"chat_id")!=66 || E.String(message,FieldAt(message,content,"text"),"text")!="Hello 🙂" { failures+=1;print("FAIL short-message delivery\n") }
Session.Update("{\"@type\":\"updateShortMessage\",\"id\":12,\"user_id\":66,\"message\":\"Hello 🙂\",\"pts\":11,\"pts_count\":1,\"date\":101}")
if Session.Receive(0.0)!="" { failures+=1;print("FAIL duplicate sequence suppressed\n") }
Session.Update("{\"@type\":\"updateDeleteMessages\",\"messages\":[12],\"pts\":12,\"pts_count\":1}")
deleted:=Session.Receive(0.0)
if E.Kind(deleted)!="updateDeleteMessages" || E.Number(deleted,0,"chat_id")!=0 { failures+=1;print("FAIL account-wide deletion identity\n") }
Session.peer_ids[0]=-1000000000099;Session.peer_hashes[0]=9007199254740993;Session.peer_count=1;Session.channel_pts[0]=4
Session.Update("{\"@type\":\"updateDeleteChannelMessages\",\"channel_id\":99,\"messages\":[12],\"pts\":5,\"pts_count\":1}")
deleted=Session.Receive(0.0)
if E.Number(deleted,0,"chat_id")!=-1000000000099 || Session.channel_pts[0]!=5 || Session.pts!=12 { failures+=1;print("FAIL independent channel cursor\n") }
Session.Update("{\"@type\":\"updateShortChatMessage\",\"id\":13,\"chat_id\":42,\"from_id\":66,\"message\":\"Missed event\",\"pts\":15,\"pts_count\":1,\"date\":103}")
unused Session.Receive(0.0)
if !Session.account.client.gap || Session.pts!=12 { failures+=1;print("FAIL missing sequence triggers recovery without skipping cursor\n") }
Session.Checkpoint();snapshot:=Session.Snapshot();Session.pts=0;Session.peer_count=0;Session.RestoreUpdates(snapshot)
if Session.pts!=12 || Session.channel_pts[0]!=5 || Session.peer_hashes[0]!=9007199254740993 { failures+=1;print("FAIL durable update cursors and exact peer hash\n") }
failures+=DialogChecks()
failures+=MediaChecks()
failures+=CallChecks()
failures+=MemberChecks()
file := "{\"@type\":\"inputFile\",\"id\":5,\"parts\":1,\"name\":\"voice.ogg\",\"md5_checksum\":\"\"}"
media := Session.Media("{\"@type\":\"inputMessageVoiceNote\",\"mime_type\":\"audio/ogg\",\"duration\":3}",file,"voice.ogg")
rows := FieldAt(media,0,"attributes"); audio := E.Raw(media,ElementAt(media,rows,1))
if E.Kind(media)!="inputMediaUploadedDocument" || E.Kind(audio)!="documentAttributeAudio" || E.Raw(audio,FieldAt(audio,0,"voice"))!="true" || E.Number(audio,0,"duration")!=3 { failures+=1;print("FAIL voice-note media attribute\n") }
encoded: [4096]u8
if TL.Encode(media,encoded[:]) <= 0 { failures+=1;print("FAIL voice-note media schema serialization\n") }
document := Session.Media("{\"@type\":\"inputMessageDocument\"}",file,"voice.ogg")
if ArrayCount(document,FieldAt(document,0,"attributes"))!=1 { failures+=1;print("FAIL ordinary document has no voice attribute\n") }
print("Telegram update sessions: % failures\n",failures);return failures
}