-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
executable file
·3179 lines (2895 loc) · 141 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
from tempfile import TemporaryDirectory
from functools import reduce, partial
from datetime import timedelta
import unittest
import asyncio
import json
import math
import os
import re
import discord
# change globals before importation by main program so they're inherited
import defs
tempdir = TemporaryDirectory()
defs.AVATAR_DIRECTORY = tempdir.name
defs.AVATAR_URL_BASE = 'https://gestalt.gov/'
defs.BECOME_MAX = 1
# don't spam the channels with error messages
defs.DEFAULT_PREFS &= ~defs.Prefs.errors
import gestalt
import gesp
# this test harness reimplements most relevant parts of the discord API, offline
# the alternative involves maintaining *4* separate bots
# and either threading (safety not guaranteed) or switching between them (sloow)
# meanwhile, existing discord.py testing solutions don't support multiple users
# i wish it didn't have to be this way but i promise this is the best solution
class warptime:
real = discord.utils.utcnow
warp = 0
@classmethod
def now(cls):
return cls.real() + timedelta(seconds = cls.warp)
class Object:
nextid = discord.utils.time_snowflake(warptime.now())
def __init__(self, **kwargs):
# don't call now() each time
self.id = ((warptime.warp * 1000) << 22) + Object.nextid
Object.nextid += 1
vars(self).update(kwargs)
class User(Object):
users = {}
def __init__(self, **kwargs):
self._deleted = False
self.bot = False
self.dm_channel = None
self.discriminator = '0001'
super().__init__(**kwargs)
if not self.bot:
self.dm_channel = Channel(type = discord.ChannelType.private,
members = [self, instance.user], recipient = self)
User.users[self.id] = self
@property
def mention(self):
return f'<@{self.id}>'
@property
def mutual_guilds(self):
return list(filter(
lambda guild : (guild.get_member(self.id)
and guild.get_member(instance.user.id)),
Guild.guilds.values()))
def _delete(self):
self._deleted = True
del User.users[self.id]
for guild in Guild.guilds.values():
if self.id in guild._members:
del guild._members[self.id]
def __str__(self):
return self.name + '#' + self.discriminator
async def send(self, content = None, embeds = [], file = None):
await self.dm_channel.send(
content = content, embeds = embeds, file = file)
# note that this class does NOT subclass Object because member IDs are user IDs
class Member:
# don't set roles immediately; let bot process role events later
def __init__(self, user, guild, perms = discord.Permissions.all()):
(self.user, self.guild, self.guild_permissions) = (user, guild, perms)
self.roles = []
def __str__(self): return str(self.user)
def _copy(self):
copy = Member(self.user, self.guild, self.guild_permissions)
copy.roles = self.roles[:]
return copy
def _add_role(self, role):
before = self._copy()
self.roles.append(role)
role.members.append(self)
#run(instance.on_member_update(before, self))
def _del_role(self, role, _async = False):
before = self._copy()
self.roles.remove(role)
role.members.remove(self)
coro = instance.on_member_update(before, self)
return coro if _async else run(coro)
@property
def display_avatar(self):
# TODO: guild avatars
return Object(replace = lambda format : 'http://avatar.png')
@property
def id(self): return self.user.id
@property
def bot(self): return self.user.bot
@property
def name(self): return self.user.name
@property
def display_name(self): return self.user.name
@property
def mutual_guilds(self):
return self.user.mutual_guilds
def get_role(self, roleid):
return discord.utils.get(self.roles, id = roleid)
def send(self, *args, **kwargs):
return self.user.send(*args, **kwargs)
class Message(Object):
def __init__(self, content = '', embed = None, embeds = [], view = None,
**kwargs):
if embed and embeds:
raise TypeError('embed and embeds are mutually exclusive')
self._deleted = False
self._prev = None
self.application_id = None
self.content = content
self.webhook_id = None
self.attachments = []
self.reactions = []
self.reference = None
self.edited_at = None
self.embeds = [embed] if embed else embeds
self.components = view.children if view else []
self.guild = None
self.poll = None
super().__init__(**kwargs)
@property
def channel_mentions(self):
if self.content:
return [Channel.channels[int(mention)]
for mention in re.findall('(?<=\<#)[0-9]+(?=\>)',
self.content)]
return []
@property
def clean_content(self):
return self.content # only used in reply embeds
@property
def jump_url(self):
return discord.MessageReference(guild_id = self.guild.id,
channel_id = self.channel.id, message_id = self.id).jump_url
@property
def mentions(self):
# mentions can also be in the embed but that's irrelevant here
# also you can always force a link to someone not present
# but it isn't included in the actual mentions property
if self.guild and self.content:
mentions = map(int, re.findall('\<\@\!?([0-9]+)\>', self.content))
if self.guild:
mentions = map(self.guild.get_member, mentions)
return list(mentions)
return []
@property
def role_mentions(self):
if self.content:
return [Role.roles[int(mention)] for mention
in re.findall('\<\@\&([0-9]+)\>', self.content)]
return []
@property
def type(self):
return (discord.MessageType.reply if self.reference
else discord.MessageType.default)
async def delete(self, delay = None):
if not (self.guild or self.author.bot): # guild or own dm message
raise Forbidden()
self.channel._messages.remove(self)
self._deleted = True
await instance.on_raw_message_delete(
discord.raw_models.RawMessageDeleteEvent(data = {
'channel_id': self.channel.id,
'id': self.id}))
async def edit(self, embed = None, embeds = [], view = None):
if (newbeds := [embed] if embed else embeds):
self.embeds = newbeds
if view:
self.components = view.children
def _react(self, emoji, user, _async = False):
react = discord.Reaction(message = self, emoji = emoji,
data = {'count': 1, 'me': None})
if react not in self.reactions:
# FIXME when more than one user adds the same reaction
self.reactions.append(react)
coro = instance.on_raw_reaction_add(
discord.raw_models.RawReactionActionEvent(data = {
'type': discord.enums.ReactionType.normal,
'message_id': self.id,
'user_id': user.id,
'channel_id': self.channel.id,
'message_author_id': self.author.id},
emoji = discord.PartialEmoji(name = emoji),
event_type = None))
return coro if _async else run(coro)
async def add_reaction(self, emoji):
await self._react(emoji, instance.user, _async = True)
async def remove_reaction(self, emoji, member):
del self.reactions[[x.emoji for x in self.reactions].index(emoji)]
async def _bulk_delete(self):
self.channel._messages.remove(self)
self._deleted = True
await instance.on_raw_bulk_message_delete(
discord.raw_models.RawBulkMessageDeleteEvent(data = {
'ids': {self.id}, 'channel_id': self.channel.id}))
class PartialMessage:
def __init__(self, *, channel, id):
(self.channel, self.id, self.guild) = (channel, id, channel.guild)
self._truemsg = discord.utils.get(channel._messages, id = id)
@property
def jump_url(self):
return self._truemsg.jump_url
async def delete(self, delay = None):
await self._truemsg.delete()
async def fetch(self):
return self._truemsg
async def remove_reaction(self, emoji, member):
await self._truemsg.remove_reaction(emoji, member)
class MessageReference:
def __init__(self, message, cached):
self.message, self.cached = message, cached
@property
def cached_message(self):
return self.message if self.cached else None
@property
def channel_id(self):
return self.message.channel.id
@property
def guild_id(self):
return self.message.guild.id
@property
def message_id(self):
return self.message.id
class Webhook(Object):
hooks = {}
def __init__(self, channel, name):
super().__init__()
self._deleted = False
(self._channel, self.name) = (channel, name)
self.token = 't0k3n' + str(self.id)
Webhook.hooks[self.id] = self
def partial(id, token, session):
return Webhook.hooks[id]
async def delete(self):
self._deleted = True
await instance.on_webhooks_update(self._channel)
async def edit_message(self, message_id, content, allowed_mentions,
thread = None):
msg = await (thread or self._channel).fetch_message(message_id)
if self._deleted or msg.webhook_id != self.id or (thread and
thread.parent != self._channel):
raise NotFound()
newmsg = Message(**vars(msg))
newmsg.content = content
newmsg.edited_at = warptime.now()
newmsg._prev = msg
msg.channel._messages[msg.channel._messages.index(msg)] = newmsg
return newmsg
async def fetch(self):
if self._deleted:
raise NotFound()
return self
async def send(self, username, avatar_url, thread = None, **kwargs):
if self._deleted or (thread and thread.parent != self._channel):
raise NotFound()
msg = Message(**kwargs) # note: absorbs other irrelevant arguments
msg.application_id = instance.user.id
msg.webhook_id = self.id
name = username if username else self.name
msg.author = Object(id = self.id, bot = True,
name = name, display_name = name,
display_avatar = avatar_url)
if msg.content:
# simulate external emoji mangling
# i don't understand why this happens
msg.content = re.sub(
'<(:[a-zA-Z90-9_~]+:)[0-9]+>',
lambda match : match.group(1),
msg.content)
await (thread or self._channel)._add(msg)
return msg
class Channel(Object):
channels = {}
def __init__(self, **kwargs):
self._messages = []
self.name = ''
self.guild = None
super().__init__(**kwargs)
Channel.channels[self.id] = self
def __getitem__(self, key):
return self._messages[key]
def __len__(self):
return len(self._messages)
def __bool__(self):
return True
@property
def jump_url(self):
return discord.PartialMessageable(None, self.id,
self.guild.id).jump_url
@property
def members(self):
return self.guild.members
@property
def mention(self):
return f'<#{self.id}>'
@property
def type(self):
return discord.ChannelType.text
async def _add(self, msg):
msg.channel = self
if self.guild:
msg.guild = self.guild
if not msg.author.id in Webhook.hooks:
msg.author = self.guild.get_member(msg.author.id)
self._messages.append(msg)
await instance.on_message(msg)
async def create_webhook(self, name):
return Webhook(self, name)
async def fetch_message(self, msgid):
msg = discord.utils.get(self._messages, id = msgid)
if not msg:
raise NotFound()
return msg
def get_partial_message(self, msgid):
return PartialMessage(channel = self, id = msgid)
def permissions_for(self, user):
# TODO need channel-level permissions
return self.guild.get_member(user.id).guild_permissions
async def send(self, content = None, file = None, reference = None,
**kwargs):
if reference:
try:
await self.fetch_message(reference.id)
except NotFound:
raise HTTPException(50035) from None
msg = Message(author = instance.user, content = content,
reference = reference, **kwargs)
await self._add(msg)
return msg
class Thread(Channel):
threads = {}
def __init__(self, channel, **kwargs):
self.parent = channel
super().__init__(**kwargs)
self.guild = self.parent.guild
Thread.threads[self.id] = self
@property
def type(self):
return discord.ChannelType.public_thread
async def create_webhook(self, name):
raise NotImplementedError()
class Role(Object):
roles = {}
def __init__(self, **kwargs):
self.members = []
self.guild = None
self.managed = False
super().__init__(**kwargs)
Role.roles[self.id] = self
@property
def mention(self):
return f'<@&{self.id}>'
async def delete(self):
await self.guild._del_role(self)
class RoleEveryone:
def __init__(self, guild):
self.guild = guild
self.id = guild.id
self.name = '@everyone'
self.managed = False
# note that this doesn't update when guild._members updates
@property
def members(self): return self.guild._members.values()
class Guild(Object):
guilds = {}
def __init__(self, **kwargs):
self._channels = {} # channel id -> channel
self._roles = {} # role id -> role
self._members = {} # user id -> member
self.name = ''
self.premium_tier = 0
super().__init__(**kwargs)
self._roles[self.id] = RoleEveryone(self)
Guild.guilds[self.id] = self
def __getitem__(self, key):
return discord.utils.get(self._channels.values(), name = key)
@property
def default_role(self):
return self._roles[self.id]
@property
def members(self):
return self._members.values()
@property
def roles(self):
return list(self._roles.values())
def _add_channel(self, name):
chan = Channel(name = name, guild = self)
self._channels[chan.id] = chan
return chan
def _add_role(self, name):
role = Role(guild = self, name = name)
self._roles[role.id] = role
return role
# bot doesn't listen to role creation events
async def _del_role(self, role):
if role == self.default_role:
raise RuntimeError('Can\'t delete @everyone!')
# event order observed experimentally
# discord.py doesn't document these things
for member in role.members:
await member._del_role(role, _async = True)
del self._roles[role.id]
await instance.on_guild_role_delete(role)
def _add_member(self, user, perms = discord.Permissions.all()):
if user.id in self._members:
raise RuntimeError('re-adding a member to a guild')
member = self._members[user.id] = Member(user, self, perms)
member.roles.append(self.default_role)
# NOTE: does on_member_update get called here? probably not but idk
if user.id == instance.user.id:
run(instance.on_guild_join(self))
elif self.get_member(instance.user.id):
run(instance.on_member_join(member))
return self # for chaining
def _remove_member(self, user):
del self._members[user.id]
def get_member(self, user_id):
return self._members.get(user_id)
def get_role(self, role_id):
return self._roles[role_id]
# use the same class for Files and Attachments for simplicity
class Attachment(Object):
def __init__(self, data, **kwargs):
self._data = data
self.content_type = 'text/plain'
self.filename = 'attachment.txt'
super().__init__(**kwargs)
instance.session._add(self.url, data)
def __str__(self):
return self.url
@property
def size(self):
return len(self._data)
@property
def url(self):
return f'https://cdn.discord.com/{self.id}/{self.filename}?ex=aa&is=bb&hm=cc&'
@property
def width(self):
# only used for logging
return 1
@property
def height(self):
return 1
def is_spoiler(self):
return self.filename.startswith('SPOILER_')
async def to_file(self, spoiler):
return self
class Interaction:
def __init__(self, message, user, button):
(self.message, self.user) = (message, user)
self.data = {'custom_id': button}
# TODO check that the message actuall has the buttons
@property
def channel(self):
return self.message.channel
@property
def response(self):
return self # lol
async def send_message(self, **kwargs):
pass # only used for ephemeral messages; bot never sees those
invites = {}
class TestBot(gestalt.Gestalt):
def __init__(self):
self._user = User(name = 'Gestalt', bot = True)
super().__init__(dbfile = ':memory:')
# discord.py complains about Client.loop in this harness
self.loop = asyncio.new_event_loop()
self.session = ClientSession()
self.pk_ratelimit = discord.gateway.GatewayRatelimiter(count = 1000,
per = 1.0)
def log(*args):
pass
@property
def user(self):
return self._user
def get_user(self, id):
return User.users.get(id)
async def fetch_invite(self, code, **_):
if code in invites:
return Object(guild = invites[code])
raise NotFound()
async def fetch_user(self, id):
try:
return User.users[id]
except KeyError:
raise NotFound()
def get_channel(self, id):
return Channel.channels.get(id, Thread.threads.get(id))
def get_guild(self, id):
return Guild.guilds.get(id)
def is_ready(self):
return True
class ClientSession:
class Response:
def __init__(self, data): self._data = data
async def read(self): return self._data
async def text(self, encoding): return self._data
@property
def status(self): return self._data if type(self._data) == int else 200
async def __aenter__(self): return self
async def __aexit__(self, *args): pass
_data = {}
def get(self, url, **kwargs): return self.Response(self._data[url])
def _add(self, path, data): self._data[path] = data
def _pk(self, path, data): self._add(gestalt.PK_ENDPOINT + path, data)
class HTTPException(discord.errors.HTTPException):
def __init__(self, code):
self.code = code
class Forbidden(discord.errors.Forbidden):
def __init__(self):
pass
class NotFound(discord.errors.NotFound):
def __init__(self):
pass
def run(coro):
return instance.loop.run_until_complete(coro)
def send(user, channel, content, reference = None, files = [], orig = False,
**kwargs):
author = channel.guild.get_member(user.id) if channel.guild else user
msg = Message(author = author, content = content, reference = reference,
attachments = files, **kwargs)
run(channel._add(msg))
return channel[-1] if msg._deleted and not orig else msg
def interact(message, user, button):
run(instance.on_interaction(Interaction(message, user, button)))
class GestaltTest(unittest.TestCase):
# ugly hack because parsing gs;p output would be uglier
def get_proxid(self, user, other = None, name = None):
if name:
row = instance.fetchall(
'select proxid from proxies '
'where (userid, cmdname) = (?, ?)',
(user.id, name))
self.assertLess(len(row), 2)
row = row and row[0]
elif other == None:
row = instance.fetchone(
'select proxid from proxies where (userid, type) = (?, ?)',
(user.id, gestalt.ProxyType.override))
elif type(other) == str:
row = instance.fetchone(
'select proxid from proxies '
'where (userid, maskid) = (?, ?)',
(user.id, other))
else:
row = instance.fetchone(
'select proxid from proxies '
'where (userid, otherid) is (?, ?)',
(user.id, other.id))
return row[0] if row else None
def assertRowExists(self, *args):
self.assertIsNotNone(instance.fetchone(*args))
def assertRowNotExists(self, *args):
self.assertIsNone(instance.fetchone(*args))
def assertNotReacted(self, msg):
self.assertEqual(len(msg.reactions), 0)
def assertCommand(self, *args, **kwargs):
msg = send(*args, **kwargs)
self.assertFalse(msg._deleted)
self.assertNotEqual(len(msg.reactions), 0)
self.assertEqual(msg.reactions[0].emoji, gestalt.REACT_CONFIRM)
return msg
def assertNotCommand(self, *args, **kwargs):
msg = send(*args, **kwargs)
self.assertNotReacted(msg)
return msg
def assertVote(self, *args, **kwargs):
msg = self.assertNotCommand(*args, **kwargs)
last = msg.channel[-1]
self.assertTrue(bool(last.components))
self.assertIn(last.id, instance.votes)
return msg
def assertNotVote(self, *args, **kwargs):
msg = self.assertNotCommand(*args, **kwargs)
last = msg.channel[-1]
self.assertFalse(bool(last.components))
self.assertNotIn(last.id, instance.votes)
return msg
def assertProxied(self, *args, **kwargs):
msg = send(*args, **kwargs, orig = True)
self.assertTrue(msg._deleted)
self.assertGreater(msg.channel[-1].id, msg.id)
self.assertIsNotNone(msg.channel[-1].webhook_id)
return msg.channel[-1]
def assertNotProxied(self, *args, **kwargs):
msg = send(*args, **kwargs, orig = True)
self.assertEqual(msg, msg.channel[-1])
self.assertIsNone(msg.webhook_id)
return msg
def assertDeleted(self, *args, **kwargs):
# test that the message was deleted with none others sent
msg = send(*args, **kwargs, orig = True)
self.assertTrue(msg._deleted)
if len(msg.channel):
self.assertLess(msg.channel[-1].id, msg.id)
return msg
def assertNotDeleted(self, *args, **kwargs):
msg = send(*args, **kwargs, orig = True)
self.assertFalse(msg._deleted)
return msg
def assertEditedContent(self, message, content):
self.assertEqual(
run(message.channel.fetch_message(message.id)).content,
content)
def desc(self, msg):
self.assertNotEqual(msg.embeds, [])
return msg.embeds[0].description
def assertReload(self):
attrs = ('votes',) # used to be more lol
origs = [getattr(instance, attr) for attr in attrs]
instance.save()
[setattr(instance, attr, None) for attr in attrs]
instance.load()
for orig, attr in zip(origs, attrs):
self.assertEqual(orig, getattr(instance, attr))
self.assertIsNot(orig, getattr(instance, attr))
# tests run in alphabetical order, so they are numbered to ensure order
def test_01_swaps(self):
chan = g['main']
# alpha opens a swap with beta
self.assertCommand(
alpha, chan, f'gs;swap open {beta.mention} sw text')
alphaid = self.get_proxid(alpha, beta)
self.assertIsNotNone(alphaid)
self.assertIsNone(self.get_proxid(beta, alpha))
self.assertEqual(instance.fetchone(
'select state from proxies where proxid = ?', (alphaid,))[0],
gestalt.ProxyState.inactive)
# simply trying to open the swap again doesn't work
self.assertNotCommand(alpha, chan, f'gs;swap open {beta.mention}')
self.assertEqual(instance.fetchone(
'select state from proxies where proxid = ?', (alphaid,))[0],
gestalt.ProxyState.inactive)
# alpha tests swap; it should fail
self.assertNotProxied(alpha, chan, 'sw no swap')
# beta opens swap
self.assertCommand(
beta, chan, f'gs;swap open {alpha.mention} sw text')
self.assertIsNotNone(self.get_proxid(alpha ,beta))
self.assertIsNotNone(self.get_proxid(beta, alpha))
# alpha and beta test the swap; it should work now
self.assertProxied(alpha, chan, 'sw swap')
self.assertProxied(beta, chan, 'sw swap')
# try to redundantly open another swap; it should fail
self.assertNotCommand(alpha, chan, f'gs;swap open {beta.mention}')
self.assertNotCommand(beta, chan, f'gs;swap open {alpha.mention}')
self.assertEqual(instance.fetchone(
'select count() from proxies where (userid, otherid) = (?, ?)',
(alpha.id, beta.id))[0], 1)
self.assertEqual(instance.fetchone(
'select count() from proxies where (userid, otherid) = (?, ?)',
(beta.id, alpha.id))[0], 1)
# now, with the alpha-beta swap active, alpha opens swap with gamma
# this one should fail due to tags conflict
self.assertNotCommand(
alpha, chan, f'gs;swap open {gamma.mention} sw text')
# but this one should work
self.assertCommand(
alpha, chan, f'gs;swap open {gamma.mention} sww text')
# gamma opens the swap
self.assertCommand(
gamma, chan, f'gs;swap open {alpha.mention} sww text')
self.assertIsNotNone(self.get_proxid(alpha, gamma))
gammaid = self.get_proxid(gamma, alpha)
self.assertIsNotNone(gammaid)
self.assertTrue(
send(alpha, chan, 'sww swap').author.name.index(gamma.name)
!= -1)
self.assertTrue(
send(gamma, chan, 'sww swap').author.name.index(alpha.name)
!= -1)
# the alpha-beta swap should still work
self.assertIsNotNone(alphaid)
self.assertIsNotNone(self.get_proxid(beta, alpha))
self.assertTrue(
send(alpha, chan, 'sw swap').author.name.index(beta.name) != -1)
self.assertTrue(
send(beta, chan, 'sw swap').author.name.index(alpha.name) != -1)
# close the swaps
self.assertCommand(alpha, chan, f'gs;swap close {alphaid}')
self.assertIsNone(self.get_proxid(alpha, beta))
self.assertIsNone(self.get_proxid(beta, alpha))
self.assertIsNotNone(self.get_proxid(alpha, gamma))
self.assertIsNotNone(self.get_proxid(gamma, alpha))
self.assertCommand(gamma, chan, f'gs;swap close {gammaid}')
self.assertIsNone(self.get_proxid(alpha, gamma))
self.assertIsNone(self.get_proxid(gamma, alpha))
self.assertNotProxied(beta, chan, 'sw no swap')
self.assertNotProxied(gamma, chan, 'sww no swap')
# test self-swaps
self.assertCommand(alpha, chan, f'gs;swap open {alpha.mention}')
self.assertIsNotNone(self.get_proxid(alpha, alpha))
self.assertCommand(alpha, chan, 'gs;p test-alpha tags me:text')
self.assertProxied(alpha, chan, 'me:self-swap')
self.assertEqual(chan[-1].author.name, 'test-alpha')
self.assertNotCommand(alpha, chan, f'gs;swap open {alpha.mention}')
self.assertEqual(instance.fetchone(
'select count() from proxies where (userid, otherid) = (?, ?)',
(alpha.id, alpha.id))[0], 1)
self.assertCommand(alpha, chan, 'gs;swap close test-alpha')
self.assertIsNone(self.get_proxid(alpha, alpha))
def test_02_help(self):
send(alpha, g['main'], 'GS; help')
msg = g['main'][-1]
self.assertEqual(len(msg.embeds), 1)
msg._react(gestalt.REACT_DELETE, alpha)
self.assertTrue(msg._deleted)
def test_03_add_delete_collective(self):
"""
# create an @everyone collective
self.assertCommand(alpha, g['main'], 'gs;c new "everyone"')
# make sure it worked
self.assertIsNotNone(self.get_collid(g.default_role))
# try to make a collective on the same role; it shouldn't work
self.assertNotCommand(alpha, g['main'], 'gs;c new "everyone"')
proxid = self.get_proxid(alpha, g.default_role)
self.assertIsNotNone(proxid)
# set the tags
self.assertCommand(alpha, g['main'], f'gs;p {proxid} tags e:text')
# test the proxy
self.assertProxied(alpha, g['main'], 'e:test')
# this proxy will be used in later tests
# now try again with a new role
role = g._add_role('delete me')
# add the role to alpha, then create collective
member = g.get_member(alpha.id)
member._add_role(role)
self.assertCommand(alpha, g['main'], f'gs;c new {role.mention}')
proxid = self.get_proxid(alpha, role)
self.assertIsNotNone(proxid)
# set tags and test it
self.assertCommand(alpha, g['main'], f'gs;p {proxid} tags d:text')
self.assertProxied(alpha, g['main'], 'd:test')
# try removing the role from alpha
member._del_role(role)
self.assertIsNone(self.get_proxid(alpha, role))
member._add_role(role)
self.assertIsNotNone(self.get_proxid(alpha, role))
# delete the collective normally
collid = self.get_collid(role)
self.assertCommand(alpha, g['main'], f'gs;c {collid} delete')
self.assertIsNone(self.get_collid(role))
self.assertIsNone(self.get_proxid(alpha, collid))
# recreate the collective, then delete the role
self.assertCommand(alpha, g['main'], f'gs;c new {role.mention}')
collid = self.get_collid(role)
self.assertIsNotNone(collid)
proxid = self.get_proxid(alpha, collid)
self.assertIsNotNone(proxid)
run(role.delete())
self.assertIsNone(self.get_proxid(alpha, collid))
self.assertIsNone(self.get_collid(role))
"""
def test_04_permissions(self):
# users shouldn't be able to change another's proxy
alphaid = self.get_proxid(alpha, None)
self.assertNotCommand(beta, g['main'], f'gs;p {alphaid} tags no:text')
def test_05_tags_auto(self):
# test every combo of auto, tags, and also the switches thereof
chan = g['main']
self.assertVote(alpha, chan, 'gs;m new test')
interact(chan[-1], alpha, 'yes')
proxid = self.get_proxid(alpha, name = 'test')
self.assertCommand(alpha, chan, 'gs;p test tags e:text')
self.assertNotProxied(alpha, chan, 'no tags, no auto')
self.assertProxied(alpha, chan, 'E:Tags')
self.assertEqual(chan[-1].content, 'Tags')
self.assertCommand(alpha, chan, f'gs;p {proxid} tags "= text"')
self.assertProxied(alpha, chan, '= tags, no auto')
self.assertEqual(chan[-1].content, 'tags, no auto')
self.assertCommand(alpha, chan, f'gs;ap {proxid}')
self.assertProxied(alpha, chan, '= tags, auto')
self.assertEqual(chan[-1].content, 'tags, auto')
self.assertProxied(alpha, chan, 'no tags, auto')
self.assertEqual(chan[-1].content, 'no tags, auto')
self.assertCommand(alpha, chan, 'gs;ap off')
self.assertCommand(alpha, chan, f'gs;p {proxid} tags #text#')
self.assertProxied(alpha, chan, '#tags, no auto#')
self.assertEqual(chan[-1].content, 'tags, no auto')
self.assertCommand(alpha, chan, f'gs;p {proxid} tags text]')
self.assertProxied(alpha, chan, 'postfix tag]')
self.assertCommand(alpha, chan, f'gs;p {proxid} tags -clear')
self.assertNotProxied(alpha, chan, 'postfix tag]')
self.assertNotCommand(alpha, chan, f'gs;p {proxid} tags -clean')
# test keepproxy
self.assertCommand(alpha, chan, f'gs;p {proxid} tags [text]')
self.assertCommand(alpha, chan, f'gs;p {proxid} keepproxy on')
self.assertProxied(alpha, chan, '[message]')
self.assertEqual(chan[-1].content, '[message]')
self.assertCommand(alpha, chan, f'gs;p {proxid} keepproxy off')
self.assertProxied(alpha, chan, '[message]')
self.assertEqual(chan[-1].content, 'message')
self.assertCommand(alpha, chan, f'gs;p {proxid} tags e:text')
# test echo
self.assertCommand(alpha, chan, f'gs;p {proxid} echo on')
(msg, proxied) = (self.assertNotDeleted(alpha, chan, 'e:echo!'), chan[-1])
self.assertGreater(proxied.id, msg.id)
self.assertIsNotNone(proxied.webhook_id)
self.assertEqual(proxied.content, 'echo!')
# echo and keepproxy
self.assertCommand(alpha, chan, f'gs;p {proxid} keepproxy on')
(msg, proxied) = (self.assertNotDeleted(alpha, chan, 'e:echo!'), chan[-1])
self.assertGreater(proxied.id, msg.id)
self.assertIsNotNone(proxied.webhook_id)
self.assertEqual(proxied.content, 'e:echo!')
self.assertCommand(alpha, chan, f'gs;p {proxid} keepproxy off')
self.assertCommand(alpha, chan, f'gs;p {proxid} echo off')
# invalid tags. these should fail
self.assertNotCommand(alpha, chan, f'gs;p {proxid} tags')
self.assertNotCommand(alpha, chan, f'gs;p {proxid} tags text')
self.assertNotCommand(alpha, chan, f'gs;p {proxid} tags txet')
# test autoproxy without tags
# also test proxies added on role add
self.assertVote(alpha, chan, 'gs;m new notags')
interact(chan[-1], alpha, 'no')
proxid = self.get_proxid(alpha, name = 'notags')
self.assertCommand(alpha, chan, f'gs;ap {proxid}')
self.assertProxied(alpha, chan, 'no tags, auto')
self.assertCommand(alpha, chan, 'gs;ap off')
self.assertNotProxied(alpha, chan, 'no tags, no auto')
# test tag precedence over auto
self.assertCommand(alpha, chan, f'gs;ap {proxid}')
self.assertEqual(send(alpha, chan, 'auto').author.name, 'notags')
self.assertEqual(send(alpha, chan, 'e: tags').author.name, 'test')
self.assertCommand(alpha, chan, 'gs;ap off')
self.assertCommand(alpha, chan, 'gs;account config errors on')
self.assertNotProxied(alpha, chan, '>be test.')
self.assertEqual(chan[-1].author.id, alpha.id) # no message on error
self.assertCommand(alpha, chan, 'gs;account config errors off')
self.assertCommand(alpha, chan, 'gs;account config Homestuck on')
self.assertProxied(alpha, chan, '>be test.')
self.assertTrue(
chan[-1].content.startswith('\\> [__Be test.__]('))
self.assertProxied(alpha, chan, '==>')
def test_06_query_delete(self):
g._add_member(deleteme := User(name = 'deleteme'))
chan = g['main']
self.assertCommand(deleteme, chan, f'gs;swap open {deleteme.mention}')
self.assertCommand(deleteme, chan, 'gs;p deleteme tags e:text')
msg = send(deleteme, chan, 'e:reaction test')
msg._react(gestalt.REACT_QUERY, beta)
token = discord.utils.escape_markdown(str(deleteme))
self.assertIn(token, beta.dm_channel[-1].content)
msg._react(gestalt.REACT_DELETE, beta)
self.assertEqual(len(msg.reactions), 0)
self.assertFalse(msg._deleted)
msg._react(gestalt.REACT_DELETE, deleteme)
self.assertTrue(msg._deleted)
msg = send(deleteme, chan, 'e:bye!')
deleteme._delete()
self.assertIsNone(instance.get_user(deleteme.id))
with self.assertRaises(NotFound):
run(instance.fetch_user(deleteme.id))
send(beta, beta.dm_channel, 'buffer')
msg._react(gestalt.REACT_QUERY, beta)
self.assertIn(token, beta.dm_channel[-1].content)
# in swaps, sender or swapee may delete message
self.assertCommand(alpha, chan,
f'gs;swap open {beta.mention} swap:text')
self.assertCommand(beta, chan, f'gs;swap open {alpha.mention}')
msg = self.assertProxied(alpha, chan, 'swap:delete me')
msg._react(gestalt.REACT_DELETE, gamma)
self.assertFalse(msg._deleted)
msg._react(gestalt.REACT_DELETE, alpha)
self.assertTrue(msg._deleted)
msg = self.assertProxied(alpha, chan, 'swap:delete me')
msg._react(gestalt.REACT_DELETE, beta)
self.assertTrue(msg._deleted)
self.assertCommand(alpha, chan,
f'gs;swap close {self.get_proxid(alpha, beta)}')
# test DMs
msg1 = beta.dm_channel[-1]
msg2 = send(beta, beta.dm_channel, 'test')
msg1._react(gestalt.REACT_DELETE, beta)
self.assertTrue(msg1._deleted)
msg2._react(gestalt.REACT_DELETE, beta)
self.assertFalse(msg2._deleted)
# and finally normal messages
msg = self.assertNotProxied(beta, chan, "we're just normal messages")
buf = send(beta, beta.dm_channel, "we're just innocent messages")
msg._react(gestalt.REACT_QUERY, beta)
msg._react(gestalt.REACT_DELETE, beta)
self.assertFalse(msg._deleted)
self.assertEqual(len(msg.reactions), 2)
self.assertEqual(beta.dm_channel[-1], buf)
def test_07_webhook_shenanigans(self):
# test what happens when a webhook is deleted
hookid = send(alpha, g['main'], 'e:reiuskudfvb').webhook_id
self.assertIsNotNone(hookid)
self.assertEqual(run(instance.get_webhook(g['main'])).id, hookid)
# webhook was deleted offline. this should be rare
Webhook.hooks[hookid]._deleted = True
msg = send(alpha, g['main'], 'e:asdhgdfjg')
newhook = msg.webhook_id
self.assertIsNotNone(newhook)
self.assertNotEqual(hookid, newhook)
self.assertEqual(run(instance.get_webhook(g['main'])).id, newhook)
self.assertDeleted(alpha, g['main'], 'gs;e nice edit')
self.assertEditedContent(msg, 'nice edit')
Webhook.hooks[newhook]._deleted = True
self.assertNotDeleted(alpha, g['main'], 'gs;e evil edit!')
self.assertEditedContent(msg, 'nice edit')
self.assertIsNone(run(instance.get_webhook(g['main'])))
# test on_webhooks_update()