-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbb_test.py
3570 lines (3032 loc) · 99 KB
/
bb_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
"""
Beardless Bot unit tests.
Module-wide ruff ignore codes:
D103: Missing docstring in public function
(Tests don't need docstrings)
PLR2004: Magic value used in comparison
(Several tests compare against magic values)
S101: Assert used
(Most tests rely on assert)
S603: Subprocess call
(Two quality tests ruly on subprocess calls to sys.executable)
SLF001: Private member accessed
(Some of the mocking/monkeypatching requires accessing private members)
"""
# ruff: noqa: D103, PLR2004, S101, S603, SLF001
import asyncio
import json
import logging
import operator
import os
import subprocess
import sys
import weakref
from collections import deque
from copy import copy
from datetime import datetime
from pathlib import Path
from typing import Any, Final, Literal, TypedDict, overload, override
import dotenv
import httpx
import nextcord
import pytest
import requests
from aiohttp import ClientWebSocketResponse
from bs4 import BeautifulSoup
from codespell_lib import main as codespell
from flake8.api import legacy as flake8
from mypy.api import run as mypy
from nextcord.ext import commands
from nextcord.types.channel import TextChannel as TextChannelPayload
from nextcord.types.emoji import Emoji as EmojiPayload
from nextcord.types.emoji import PartialEmoji as PartialEmojiPayload
from nextcord.types.message import Message as MessagePayload
from nextcord.types.message import Reaction as ReactionPayload
from nextcord.types.user import User as UserPayload
from pytest_httpx import HTTPXMock
import Bot
import brawl
import bucks
import logs
import misc
logger = logging.getLogger(__name__)
ImageTypes: set[str] = {
"image/" + i for i in ("png", "jpeg", "jpg", "gif", "webp")
}
FilesToCheck: list[str] = [f.name for f in Path().glob("*.py")]
OwnerBrawlId: Final[int] = 7032472
GuildChannel = (
nextcord.StageChannel
| nextcord.VoiceChannel
| nextcord.TextChannel
| nextcord.CategoryChannel
| nextcord.ForumChannel
)
IconTypes = bytes | nextcord.Asset | nextcord.Attachment | nextcord.File
MessageableChannel = (
nextcord.TextChannel
| nextcord.Thread
| nextcord.DMChannel
| nextcord.PartialMessageable
| nextcord.VoiceChannel
| nextcord.StageChannel
| nextcord.GroupChannel
)
ConnectionStateGetChannelTypes = (
GuildChannel
| nextcord.Thread
| nextcord.PartialMessageable
| nextcord.abc.PrivateChannel
)
SnowflakeTime = datetime | nextcord.abc.Snowflake
StyleGuide = flake8.get_style_guide(ignore=["W191", "W503"])
dotenv.load_dotenv(".env")
BrawlKey: str | None = os.environ.get("BRAWLKEY")
MarkAsync = pytest.mark.asyncio(loop_scope="module")
def response_ok(resp: httpx.Response) -> bool:
"""
Make sure a response has an ok exit code.
Args:
resp (httpx.Response): The response to check
Returns:
bool: Whether the exit code is ok.
"""
return misc.Ok <= resp.status_code < 400
def valid_image_url(resp: httpx.Response) -> bool:
"""
Make sure an image url points to a valid image.
Args:
resp (httpx.Response): The response to check
Returns:
bool: Whether the url points to a valid image.
"""
return response_ok(resp) and resp.headers["content-type"] in ImageTypes
# TODO: Write generic MockState
# https://github.com/LevBernstein/BeardlessBot/issues/48
class MockHTTPClient(nextcord.http.HTTPClient):
"""Drop-in replacement for HTTPClient to enable offline testing."""
@override
def __init__(
self,
loop: asyncio.AbstractEventLoop,
user: nextcord.ClientUser | None = None,
) -> None:
self.loop = loop
self.user = user
self.user_agent = str(user)
self.token = None
self.proxy = None
self.proxy_auth = None
self._locks = weakref.WeakValueDictionary()
self._global_over = asyncio.Event()
self._global_over.set()
@override
async def create_role( # type: ignore[override]
self,
guild_id: nextcord.types.snowflake.Snowflake,
reason: str | None = None,
**fields: Any,
) -> dict[str, Any]:
data = dict(fields)
data["id"] = guild_id
if reason:
logger.info("Role creation reason: %s", reason)
return data
@override
async def send_message( # type: ignore[override]
self,
channel_id: nextcord.types.snowflake.Snowflake,
content: str | None = None,
*,
tts: bool = False,
embed: nextcord.Embed | None = None,
embeds: list[nextcord.Embed] | None = None,
nonce: int | str | None = None,
allowed_mentions: nextcord.AllowedMentions | None = None,
message_reference: nextcord.MessageReference | None = None,
stickers: list[int] | None = None,
components: list[nextcord.Component] | None = None,
flags: int | None = None,
) -> dict[str, Any]:
return {
"attachments": [],
"edited_timestamp": None,
"type": nextcord.Message,
"pinned": False,
"mention_everyone": content and "@everyone" in content,
"tts": tts,
"author": MockUser(),
"content": content or "",
"nonce": nonce,
"allowed_mentions": allowed_mentions,
"message_reference": message_reference,
"components": components,
"stickers": stickers,
"flags": flags,
"channel_id": channel_id,
"embeds": [embed] if embed else embeds or [],
}
@override
async def leave_guild(
self, guild_id: nextcord.types.snowflake.Snowflake,
) -> None:
if (
self.user
and hasattr(self.user, "guild")
and self.user.guild
and self.user.guild.id == guild_id
):
self.user.guild = None
class MockHistoryIterator(nextcord.iterators.HistoryIterator):
"""Mock HistoryIterator class for offline testing."""
@override
def __init__(
self,
messageable: nextcord.abc.Messageable,
limit: int | None = None,
before: SnowflakeTime | None = None,
after: SnowflakeTime | None = None,
around: SnowflakeTime | None = None,
oldest_first: bool | None = False,
) -> None:
self.messageable = messageable
self.limit = min(limit or 100, 100)
self.messages: asyncio.Queue[nextcord.Message] = asyncio.Queue()
self.reverse = (
(after is not None) if oldest_first is None else oldest_first
)
@override
async def fill_messages(self) -> None:
if not hasattr(self, "channel"):
self.channel = await self.messageable._get_channel()
assert hasattr(self.channel, "messages")
assert isinstance(self.channel.messages, list)
assert self.limit is not None
data = (
list(reversed(self.channel.messages))
if self.reverse
else self.channel.messages
)
for _ in range(min(len(data), self.limit)):
await self.messages.put(data.pop())
class MockMember(nextcord.Member):
"""Mock Member class for offline testing."""
@override
def __init__(
self,
user: nextcord.User | None = None,
nick: str | None = None,
roles: list[nextcord.Role] | None = None,
guild: nextcord.Guild | None = None,
custom_avatar: bool = True,
perms: nextcord.Permissions | None = None,
admin_powers: bool = False,
) -> None:
self._user = user or MockUser()
self._user.bot = False
self.nick = nick
self.guild = guild or MockGuild()
self.activities = ()
self._user._banner = None
self.roleList = [MockRole("everyone", self.guild.id)] + (roles or [])
self._roles = nextcord.utils.SnowflakeList([])
self._timeout = None
self._avatar = (
"7b6ea511d6e0ef6d1cdb2f7b53946c03" if custom_avatar else None
)
self.perms = (
nextcord.Permissions.all()
if admin_powers
else (perms or nextcord.Permissions.none())
)
self.joined_at = self.created_at
@override
@property
def guild_permissions(self) -> nextcord.Permissions:
return self.perms
@guild_permissions.setter
def guild_permissions(self, perms: nextcord.Permissions) -> None:
self.perms = perms
@override
@property
def roles(self) -> list[nextcord.Role]:
return self.roleList
@roles.setter
def roles(self, roles: list[nextcord.Role]) -> None:
self.roleList = roles
@override
async def add_roles(
self,
*roles: nextcord.abc.Snowflake,
reason: str | None = None,
atomic: bool = True,
) -> None:
logger.info(
"Role add reason: %s. Atomic operation: %s", reason, atomic,
)
for role in roles:
assert isinstance(role, nextcord.Role)
if role not in self.roleList:
self.roleList.append(role)
@override
async def send( # type: ignore[override]
self, *args: str | None, **kwargs: Any,
) -> None:
# It's not worth trying to match the original signature. Trust me.
ch = await self._get_channel()
await ch.send(*args, **kwargs)
@override
async def _get_channel(self) -> nextcord.DMChannel:
return await self._user._get_channel()
@override
def history(
self,
*,
limit: int | None = 100,
before: SnowflakeTime | None = None,
after: SnowflakeTime | None = None,
around: SnowflakeTime | None = None,
oldest_first: bool | None = False,
) -> nextcord.iterators.HistoryIterator:
return self._user.history(
limit=limit,
before=before,
after=after,
around=around,
oldest_first=oldest_first,
)
class MockUser(nextcord.User):
"""
Mock User class for offline testing.
MockUser also contains some features of nextcord.Member for the sake of
testing the Bot user's permissions.
"""
class MockUserState(nextcord.state.ConnectionState):
"""Drop-in replacement for ConnetionState."""
# TODO: move MockUserState out, apply to all classes, make generic
# https://github.com/LevBernstein/BeardlessBot/issues/48
@override
def __init__(self, message_number: int = 0) -> None:
self._guilds: dict[int, nextcord.Guild] = {}
self.allowed_mentions = nextcord.AllowedMentions(everyone=True)
self.loop = asyncio.get_event_loop()
self.http = MockHTTPClient(self.loop)
self.user = None
self.last_message_id = message_number
self.channel = MockChannel()
@override
def create_message(
self, *, channel: MessageableChannel, data: MessagePayload,
) -> nextcord.Message:
data["id"] = self.user.id if self.user else "0"
data["components"] = []
data["message_reference"] = {
"message_id": self.last_message_id,
"channel_id": str(channel.id),
}
self.last_message_id += 1
message = nextcord.Message(state=self, channel=channel, data=data)
assert self.channel._state._messages is not None
self.channel._state._messages.append(message)
return message
@override
def store_user(
self, data: UserPayload | nextcord.User,
) -> nextcord.User:
if isinstance(data, nextcord.User):
return data
stored_user = (
self.user or MockUser(user_id=int(data.get("id", "0")))
)
assert isinstance(stored_user, nextcord.User)
return stored_user
@override
def get_channel(
self, channel_id: int | None,
) -> ConnectionStateGetChannelTypes | None:
return (
MockChannel(channel_id=channel_id)
if channel_id is not None
else self.channel
)
@override
def __init__(
self,
name: str = "testname",
discriminator: str = "0000",
user_id: int = 123456789,
messages: list[nextcord.Message] | None = None,
*,
custom_avatar: bool = True,
admin_powers: bool = False,
) -> None:
self.name = name
self.global_name = name
self.id = user_id
self.discriminator = discriminator
self.bot = False
self.activity = None
self.system = False
self.messages = messages or []
self._public_flags = 0
self._state = self.MockUserState(message_number=len(self.messages))
# TODO: Switch to DMChannel
self._state._private_channels_by_user = {
user_id: MockChannel(), # type: ignore[dict-item]
}
self._avatar = (
"7b6ea511d6e0ef6d1cdb2f7b53946c03" if custom_avatar else None
)
self.set_user_state()
self.guild_permissions = (
nextcord.Permissions.all()
if admin_powers
else nextcord.Permissions.none()
)
def set_user_state(self) -> None:
"""Assign the User object to its ConnectionState."""
self._state.user = MockBot.MockClientUser(self)
self._state.http.user_agent = str(self._state.user)
@override
def history(
self,
*,
limit: int | None = 100,
before: SnowflakeTime | None = None,
after: SnowflakeTime | None = None,
around: SnowflakeTime | None = None,
oldest_first: bool | None = False,
) -> nextcord.iterators.HistoryIterator:
channel = self._state.get_channel(None)
assert isinstance(channel, nextcord.abc.Messageable)
return MockHistoryIterator(
channel,
limit,
before,
after,
around,
oldest_first,
)
@override
async def _get_channel(self) -> MessageableChannel: # type: ignore[override]
# TODO: switch to DMChannel
ch = self._state.get_channel(None)
assert isinstance(ch, MessageableChannel)
return ch
class MockChannel(nextcord.TextChannel):
"""Drop-in replacement for TextChannel to enable offline testing."""
class MockChannelState(nextcord.state.ConnectionState):
"""Drop-in replacement for ConnetionState."""
@override
def __init__(
self,
user: nextcord.ClientUser | None = None,
message_number: int = 0,
) -> None:
self.loop = asyncio.get_event_loop()
self.http = MockHTTPClient(self.loop, user)
self.allowed_mentions = nextcord.AllowedMentions(everyone=True)
self.user = user
self.last_message_id = message_number
self._messages: deque[nextcord.Message] = deque()
@override
def create_message(
self, *, channel: MessageableChannel, data: MessagePayload,
) -> nextcord.Message:
data["id"] = self.last_message_id
data["components"] = []
user = self.user or MockUser()
data["author"] = UserPayload(
id=user.id,
username=user.name,
discriminator=user.discriminator,
avatar=user._avatar,
)
data["message_reference"] = {
"message_id": self.last_message_id,
"channel_id": str(channel.id),
}
self.last_message_id += 1
message = nextcord.Message(state=self, channel=channel, data=data)
self._messages.append(message)
return message
@override
def store_user(self, data: UserPayload) -> nextcord.User:
stored_user = self.user or MockUser(user_id=int(data["id"]))
assert isinstance(stored_user, nextcord.User)
return stored_user
class MockPermPayload(TypedDict):
"""Drop-in replacement for PermissionOverwritePayload."""
id: nextcord.types.snowflake.Snowflake
type: Literal[0, 1]
allow: str
deny: str
@override
def __init__(
self,
name: str = "testchannelname",
guild: nextcord.Guild | None = None,
messages: list[nextcord.Message] | None = None,
channel_id: int = 123456789,
) -> None:
self.name = name
self.id = channel_id
self.position = 0
self.slowmode_delay = 0
self.nsfw = False
self.topic = None
self.category_id = 0
self.guild = guild or nextcord.utils.MISSING
self.messages = messages or []
self._type: Literal[0] = 0
self._state = self.MockChannelState(message_number=len(self.messages))
self.assign_channel_to_guild(self.guild)
self._overwrites = []
@overload
@override
async def set_permissions(
self,
target: nextcord.Member | nextcord.Role,
*,
overwrite: nextcord.PermissionOverwrite | None = ...,
reason: str | None = ...,
) -> None:
...
@overload
@override
async def set_permissions(
self,
target: nextcord.Member | nextcord.Role,
*,
reason: str | None = ...,
**permissions: bool,
) -> None:
...
@override
async def set_permissions(
self,
target: nextcord.Member | nextcord.Role,
*,
reason: str | None = None,
**kwargs: Any,
) -> None:
if reason:
logger.info("Permissions set reason: %s", reason)
overwrite = kwargs.pop("overwrite", None)
permissions: dict[str, bool] = kwargs
if overwrite is None and len(permissions) != 0:
overwrite = nextcord.PermissionOverwrite(**permissions)
if overwrite is not None:
allow, deny = overwrite.pair()
perm_type: Literal[0, 1] = (
0 if isinstance(target, nextcord.Role) else 1
)
payload = self.MockPermPayload(
id=target.id,
allow=allow.value,
deny=deny.value,
type=perm_type,
)
guild_payload = TextChannelPayload(
guild_id=self.guild.id,
position=self.position,
permission_overwrites=[payload],
nsfw=self.nsfw,
id=self.id,
name=self.name,
rate_limit_per_user=0,
default_auto_archive_duration=60,
default_thread_rate_limit_per_user=0,
type=self._type,
parent_id=None,
)
self._fill_overwrites(guild_payload)
logger.info(
"Setting perms on channel: %s for target: %s, reason: %s",
self.id,
target.id,
reason,
)
else:
# TODO: proper removal logic here--remove from _overwrites
logger.info(
"Deleting perms on channel: %s for target: %s, reason: %s",
self.id,
target.id,
reason,
)
@override
def history(
self,
*,
limit: int | None = 100,
before: SnowflakeTime | None = None,
after: SnowflakeTime | None = None,
around: SnowflakeTime | None = None,
oldest_first: bool | None = False,
) -> nextcord.iterators.HistoryIterator:
return MockHistoryIterator(
self,
limit,
before,
after,
around,
oldest_first,
)
@override
async def send(self, *args: str | None, **kwargs: Any) -> nextcord.Message:
msg = await super().send(*args, **kwargs)
self.messages.append(msg)
return msg
def assign_channel_to_guild(self, guild: nextcord.Guild) -> None:
"""
Add a channel to its Guild's list of channels.
Args:
guild (nextcord.Guild): The Guild to which the channel belongs
"""
if guild and self not in guild.channels:
guild.channels.append(self)
# TODO: Write message.edit()
class MockMessage(nextcord.Message):
"""Drop-in replacement for Message to enable offline testing."""
class MockMessageState(nextcord.state.ConnectionState):
"""Drop-in replacement for ConnetionState."""
@override
def __init__(
self, user: nextcord.User, guild: nextcord.Guild | None = None,
) -> None:
self.loop = asyncio.get_event_loop()
self.http = MockHTTPClient(
self.loop, user=MockBot.MockClientUser(user),
)
self.guild = guild or MockGuild()
@override
def get_reaction_emoji(
self, data: EmojiPayload,
) -> nextcord.emoji.Emoji:
return MockEmoji(self.guild, data, MockMessage())
@override
def __init__(
self,
content: str | None = "testcontent",
author: nextcord.User | nextcord.Member | None = None,
guild: nextcord.Guild | None = None,
channel: nextcord.TextChannel | None = None,
embeds: list[nextcord.Embed] | None = None,
embed: nextcord.Embed | None = None,
) -> None:
self.author = author or MockMember()
self.content = content or ""
self.id = 123456789
self.type = nextcord.MessageType.default
self.guild = guild
self.channel = channel or MockChannel(guild=self.guild or MockGuild())
self.mentions = []
self.embeds = embeds or ([embed] if embed is not None else [])
self.mention_everyone = False
self.flags = nextcord.MessageFlags()
self._state = self.MockMessageState(
(
self.author
if isinstance(self.author, nextcord.User)
else self.author._user
), guild,
)
assert self.channel._state._messages is not None
self.channel._state._messages.append(self)
@override
async def delete(self, *, delay: float | None = None) -> None:
assert self.channel._state._messages is not None
if delay:
await asyncio.sleep(delay)
self.channel._state._messages.remove(self)
@staticmethod
def get_mock_reaction_payload(
name: str = "MockEmojiName",
emoji_id: int = 0,
*,
me: bool = False,
count: int = 1,
) -> ReactionPayload:
"""
Create the payload for a Reaction.
Args:
name (str): The reaction emoji's name (default is "MockEmojiName")
emoji_id (int): The emoji's id (default is 0)
me (bool): If the BotUser sent this reaction (default is False)
count (int): Number of users who added this reaction for a given
nextcord.Message (default is 1)
Returns:
ReactionPayload: The TypedDict that will be used to create a new
Reaction, constructed with the provided arguments.
"""
return ReactionPayload(
me=me,
count=count,
emoji=PartialEmojiPayload(id=emoji_id, name=name),
)
class MockRole(nextcord.Role):
"""Drop-in replacement for Role to enable offline testing."""
@override
def __init__(
self,
name: str = "Test Role",
role_id: int = 123456789,
permissions: int | nextcord.Permissions = 1879573680,
colour: int = 0,
) -> None:
self.name = name
self.id = role_id
self.hoist = False
self.mentionable = True
self.position = 1
self._permissions = (
permissions if isinstance(permissions, int) else permissions.value
)
self._colour = colour
class MockGuild(nextcord.Guild):
"""Drop-in replacement for Guild to enable offline testing."""
class MockGuildState(nextcord.state.ConnectionState):
"""Drop-in replacement for ConnetionState."""
@override
def __init__(self, guild_id: int = 0) -> None:
user = MockBot.MockClientUser()
self.member_cache_flags = nextcord.MemberCacheFlags.all()
self.shard_count = 1
self.loop = asyncio.get_event_loop()
self.user = user
self.http = MockHTTPClient(self.loop, user=user)
self._intents = nextcord.Intents.all()
self._guilds = {guild_id: nextcord.utils.MISSING}
@override
async def chunk_guild(
self,
guild: nextcord.Guild,
*,
wait: bool = True,
cache: bool | None = None,
) -> list[nextcord.Member]:
guild._member_count = len(guild._members)
logger.info(
"Chunked Guild %s with wait=%s and cache=%s",
guild,
wait,
cache,
)
return guild.members
@override
async def query_members(
self,
guild: nextcord.Guild,
query: str | None,
limit: int,
user_ids: list[int] | None,
cache: bool,
presences: bool,
) -> list[nextcord.Member]:
logger.info(
"Queried members in Guild %s with query=%s, presences=%s",
guild,
query,
presences,
)
members: list[nextcord.Member] = []
if self.user is not None and limit >= 1:
await self.chunk_guild(guild, cache=cache)
if not user_ids or (self.user.id in user_ids):
assert hasattr(self.user, "base_user")
members.append(
MockMember(self.user.base_user, guild=guild),
)
return members
@override
def __init__(
self,
members: list[nextcord.Member] | None = None,
name: str = "Test Guild",
guild_id: int = 0,
channels: list[nextcord.TextChannel] | None = None,
roles: list[nextcord.Role] | None = None,
chunked: bool = True,
) -> None:
self.name = name
self.id = guild_id
self._state = self.MockGuildState(self.id)
self._members = dict(enumerate(members or []))
self._member_count = len(self._members) if chunked else 0
self._channels = dict(
enumerate(channels or [MockChannel()]),
)
self._roles = dict(enumerate(
[MockRole(name="everyone", role_id=0)]
+ (roles if roles is not None else [MockRole()]),
))
self.owner_id = 123456789
for role in self._roles.values():
self.assign_guild_to_role(role)
for ch in self._channels.values():
self.assign_guild_to_channel(ch)
@override
@property
def me(self) -> nextcord.Member:
assert self._state.user is not None
user = (
self._state.user.base_user
if hasattr(self._state.user, "base_user")
else self._state.user
)
assert isinstance(user, nextcord.User)
return MockMember(
user,
guild=self,
perms=(
user.guild_permissions
if hasattr(user, "guild_permissions")
else None
),
)
@overload
@override
async def create_role(
self,
*,
reason: str | None = ...,
name: str = ...,
permissions: nextcord.Permissions = ...,
colour: nextcord.Colour | int = ...,
hoist: bool = ...,
mentionable: bool = ...,
icon: str | IconTypes | None = ...,
) -> nextcord.Role:
...
@overload
@override
async def create_role(
self,
*,
reason: str | None = ...,
name: str = ...,
permissions: nextcord.Permissions = ...,
color: nextcord.Colour | int = ...,
hoist: bool = ...,
mentionable: bool = ...,
icon: str | IconTypes | None = ...,
) -> nextcord.Role:
...
@override
async def create_role(
self,
*,
name: str = "TestRole",
permissions: nextcord.Permissions | None = None,
color: nextcord.Colour | int = 0,
colour: nextcord.Colour | int = 0,
hoist: bool = False,
mentionable: bool = False,
icon: str | IconTypes | None = None,
reason: str | None = None,
) -> nextcord.Role:
col = color or colour or nextcord.Colour.default()
perms = permissions or nextcord.Permissions.none()
fields = {
"name": name,
"permissions": str(perms.value),
"mentionable": mentionable,
"hoist": hoist,
"color": col if isinstance(col, int) else col.value,
}
if isinstance(icon, str):
fields["unicode_emoji"] = icon
else:
fields["icon"] = await nextcord.utils.obj_to_base64_data(icon)
data = await self._state.http.create_role(
self.id, reason=reason, **fields,
)
role = nextcord.Role(guild=self, data=data, state=self._state)
self._roles[len(self.roles)] = role
return role
def assign_guild_to_role(self, role: nextcord.Role) -> None:
"""
Set a Role's Guild to this Guild.
Args:
role (nextcord.Role): The role whose Guild will be set
"""
role.guild = self
def assign_guild_to_channel(self, channel: GuildChannel) -> None:
"""
Set a GuildChannel's Guild to this Guild.
Args:
channel (GuildChannel): The channel whose Guild will be set
"""
channel.guild = self
@override
def get_member(self, user_id: int, /) -> nextcord.Member | None:
return MockMember(MockUser(user_id=user_id))
class MockThread(nextcord.Thread):
"""Drop-in replacement for Thread to enable offline testing."""
@override
def __init__(
self,
*,
name: str = "testThread",
owner: nextcord.User | None = None,
channel_id: int = 0,
me: nextcord.Member | None = None,
parent: nextcord.TextChannel | None = None,
archived: bool = False,
locked: bool = False,
) -> None:
Bot.BeardlessBot = MockBot(Bot.BeardlessBot)
channel = (
parent or MockChannel(channel_id=channel_id, guild=MockGuild())
)
self.guild = channel.guild
self._state = channel._state