API: Testing¶
Stand-ins for driving a view, a modal, or the store in a test with no Discord connection, imported from
cascadeui.testing. Its eight names are public under the stability policy.
stub_client()¶
Returns a new StubClient. A pattern that draws a different tree with a client bound is measured
with one: pass it as bot= where the pattern takes one (the leaderboard and its persistent variant), or assign it
to any view's bot. Counting What a Panel Holds
shows the count.
from cascadeui import MAX_MESSAGE_COMPONENTS
from cascadeui.testing import stub_client
view = MyLeaderboard(user_id=1, guild_id=2, bot=stub_client())
await view.on_load()
view.validate()
assert view.total_components <= MAX_MESSAGE_COMPONENTS
StubClient¶
A discord.Client, built with the guilds intent alone, that opens no connection and needs no token. Its user cache is empty, as
a live bot's is for a member it has not seen, so the tree drawn with it is the one a live bot sends. A section-style
leaderboard row is four components with a client and one without, so a five-row page counts 24 with the stub and 9
with none.
The library calls through a view's client: it re-registers dynamic buttons when the view stops. A
discord.Client subclass whose __init__ skips super().__init__() raises AttributeError naming _connection
there, and the stub takes those calls.
stub_interaction(user_id=1, guild_id=2)¶
Returns a new StubInteraction: what Modal.submit() takes, and an
interaction a view can be built with.
user_id(int): the id ofinteraction.user, which owns a view built with itguild_id(int or None):interaction.guild_id.Nonestands in for a DM
from cascadeui import Modal, TextInput, min_length
from cascadeui.testing import stub_interaction
modal = Modal(title="Rename", inputs=[TextInput(label="Name", validators=[min_length(5)])])
interaction = stub_interaction()
assert await modal.submit(interaction, {"Name": "ab"}) is False
assert "at least 5 characters" in interaction.replies[0]
Testing a Modal Offline teaches it.
StubInteraction¶
An interaction that records what is said through it instead of sending it. Each call is checked against the discord.py method it stands for, so a call discord.py refuses before sending raises here too:
- a misspelled keyword
embedwithembeds, orfilewithfiles- more than ten embeds
- a second answer to the response slot (
discord.InteractionResponded)
| Attribute | Value |
|---|---|
id |
A different number on each one, as a real interaction's |
user |
A discord.Object with the user_id given |
guild_id, guild |
The guild_id given, and None: there is no guild cache offline |
type |
discord.InteractionType.modal_submit |
message |
None, the shape of a modal opened from a slash command |
channel_id, client |
None |
data |
{} |
created_at, expires_at |
When it was built, and fifteen minutes later. is_expired() reads expires_at, as on a real interaction |
Set type to discord.InteractionType.component and message to a view's message to stand in for a click on it.
Set type to discord.InteractionType.application_command and give it as interaction= to a commands.Context to
run a hybrid command as a slash command: the context's send() answers through it. A keyword given as discord.py's
MISSING, which that send() passes for each keyword it was not given, counts as left out, as discord.py counts it.
What it records:
| Attribute | What it holds |
|---|---|
replies |
The text of each message sent through response.send_message() or followup.send(), and "" for one with no text (an embed alone) |
sends |
The keywords of each of those messages, with content as passed (None when absent), as in interaction.sends[0]["files"] |
edits |
The keywords of each edit, through response.edit_message() or edit_original_response() |
defers |
The keywords of each response.defer(), thinking always present |
modals |
Each modal sent through response.send_modal() |
deferred |
True once response.defer() answered it |
deleted |
True once delete_original_response() deleted the original response |
answered |
True once anything was sent, edited, deferred, or opened through it |
replies holds the response and the followups in one list. Which one carries a validator's refusal depends on
whether the acknowledgement timer answered first, so a test checks the text without predicting where it went.
response.is_done() and response.type track the response slot as discord.py does, and response.defer() and
response.edit_message() answer only the interaction types discord.py answers for them, leaving the slot open
otherwise.
Each reply posts a StubMessage in the interaction's channel_id and guild_id. A reply through
response.send_message() is the original response from then on, so a view sent through the double gets that
message, and each later edit the view makes is recorded on it:
interaction = stub_interaction()
message = await Scoreboard(interaction=interaction).send()
assert message is await interaction.original_response()
followup.send(wait=True) returns the message it posted, and None without wait, as discord.py does. With no
reply, the original response is message, the one a click came from. With neither, or once the original response is
deleted, original_response(), edit_original_response(), and delete_original_response() raise
discord.NotFound (code 10008), as Discord does for a response with no message.
A deferred reply (a command's defer(), a click's defer(thinking=True)) posts a "thinking" message, with
flags.loading set and the defer's visibility, which is the original response until something replaces it. A
followup sent while it stands takes its place, as on Discord: it is the original response from then on and keeps the
defer's visibility, whatever ephemeral it asked for. Once the thinking message is deleted (the library deletes its
own public one before a private reply), a followup posts as it asked.
stub_message(channel_id=None, guild_id=2, *, ephemeral=False)¶
Returns a new StubMessage, for a view built without a send: a test that starts with the view's data
loaded, or with a click to drive, gives the view one as its message, and each edit is recorded
there.
channel_id,guild_id(int or None): the ids of the message'schannelandguild. Aguild_idofNonestands in for a DMephemeral(bool): whether the message is private, read from itsflags
from cascadeui.testing import stub_message
view = Scoreboard(user_id=1, guild_id=2)
view.message = stub_message()
await view.reload()
assert view.message.edits
StubMessage¶
A discord.Message, built with no connection, that records each edit instead of sending it.
| Attribute | Value |
|---|---|
id |
A different number on each one, as a real message's |
channel, guild |
A discord.Object with the id given, or None |
flags |
discord.MessageFlags: ephemeral as posted, and components_v2 once a layout view is sent or edited in |
content, embeds, components |
What the message holds now. components are the ones discord.py builds from the view sent or edited in |
attachments |
Empty: it keeps no uploads |
edits |
The keywords of each edit, by whatever route it reached the message: its own edit(), or an interaction's response.edit_message() or edit_original_response() |
deleted |
True once delete() deleted it, or an interaction deleted it as its original response |
An edit keeps what it leaves out, as on Discord: an edit with view= alone keeps the content and embeds. edit()
is checked against discord.py's, so a keyword discord.py refuses raises here too.
fetch() returns the message itself. Once the message is deleted, edit(), delete(), and fetch() raise
discord.NotFound (code 10008). Other discord.Message methods, such as reply(), need a connection and raise.
flush_notifications(store=None) (async)¶
Waits for the state notifications other views are running in the background. dispatch() runs the render of the
view that dispatched before it returns and every other subscriber on a task of its own, so a test that checks what
another view did waits for those first. How an Action Reaches the Views
explains the order.
store(StateStore): the store whose notifications to wait for, by default the library's
await panel.dispatch("SCORE_ADDED", {"points": 3})
await flush_notifications()
assert scoreboard.total == 3
It waits for the notifications running when it is called. A notification that dispatches again starts tasks of its own, which a second call waits for.
Raises TypeError when store is not a StateStore.
build_as_restored(view_class, persistence_key, *, bot=None, user_id=None, guild_id=None, **kwargs) (async)¶
Builds a persistent panel the way a restart's restore builds it, with no Discord connection. It runs the restore's own steps, in its order:
- The class is built from the saved arguments (
kwargs, withtheme,bot, andtimeout, which a saved row never holds, dropped). - A V2 panel nothing has drawn yet is drawn from its
build_ui(). - Its custom_ids are checked.
- It gets the owner and guild the row recorded, then
on_bind(bot)runs.
A build_ui() that reads something only on_bind() supplies fails here as it fails at a restart.
view_class(type): a persistent view classpersistence_key(str): the key the panel was posted underbot(discord.Client): the boton_bind()receives,Noneto skip ituser_id,guild_id(int): the owner and guild the saved row recorded
from cascadeui.testing import build_as_restored, stub_client
view = await build_as_restored(TicketPanel, "tickets", bot=stub_client())
view.validate() # the tree a restarted panel routes clicks to
The panel is not registered and has no message. on_restore(), which a restart runs once the bot is ready, is not
run. Call it to test a redraw.
Raises TypeError when view_class is not a persistent view class, and ValueError when a control's custom_id
would not survive a restart.