GitHub

chat_test

API reference for chat_test.

A whole chat in memory, and the checks every adapter must pass (Effect's effect/chat/ChatTest).

chat_test.layer() gives Chat, its Registry and one fake adapter, with the ChatTest service to drive it: make threads, post as a user, click, submit, fail the next call. conformance is the suite of rules a real adapter must pass, as plain effects keyed by rule name, and check_message, check_event and check_interaction check the invariants of what an adapter reads::

@fx.gen
def program():
    test = yield from ChatTest()
    chat = yield from Chat()
    thread = yield from test.make_thread()
    yield from chat.post(thread, markdown="hello")
    return [m.text for m in (yield from test.messages(thread))]

fx.run_blocking(program.pipe(fx.provide(chat_test.layer())))  # ['hello']

Re-exports

Types

TypeDefinitionDescription
ParseMentiontype ParseMention = Callable[[str], MentionToken | None]

Parses one mention token, as the platform writes it, into its kind and id; None when the slice is not a token.

Ruletype Rule = Effect[None, ConformanceFailure, _chat.Chat | Registry]

One conformance rule: it needs the adapter under test registered in Chat.

Classes

Functions

code_points

code_points(markdown, actions=()) -> int

The fake's default measure: the number of code points, actions free.

ParameterTypeDescription
markdownstr
actionsSequence[U.Action] = ()

Returns int

def code_points(markdown: str, actions: Sequence[U.Action] = ()) -> int:
    """The fake's default ``measure``: the number of code points, actions
    free."""
    return len(markdown)

layer

layer(*, platform='test', self_id='bot', capabilities=CAPABILITIES, measure=code_points, interaction_deadline='3 seconds', **limits) -> Layer[_chat.Chat | Registry | ChatTest]

A whole chat in memory: Chat, its registry and one fake adapter.

  • Every capability is on by default; measure counts code points.
  • The default limits are 4000 per message and 10 files of up to 10 MiB. With nativeStream a stream takes up to message_length and lasts 10 minutes; with buttons or selects a message takes 25 elements and an element's id plus encoded value 100 code points; with modals a modal's id plus metadata takes 100 and a modal 5 fields; with commands follow_up_age is 15 minutes. Keyword arguments named after Limits fields override them.
  • The native stream behaves the way Slack's was found to: an append past stream_length fails TooLarge and adds nothing, a stream past stream_age on Clock is closed, an append without flush holds back an unclosed < tail of up to 100 characters or a trailing high surrogate, and an open stream refuses edit and delete.
  • interact gives a handler 3 seconds by default, on Clock.
  • Two layers merged with different platforms share one Chat, so routing can be tested; the ChatTest in context is the last one.
ParameterTypeDescription
platformstr = 'test'
self_idstr = 'bot'
capabilitiesSequence[Capability] = CAPABILITIES
measureMeasure = code_points
interaction_deadlineDurationInput = '3 seconds'
limitsUnpack[LimitsOverrides] = {}

Returns Layer[_chat.Chat | Registry | ChatTest]

def layer(
    *,
    platform: str = "test",
    self_id: str = "bot",
    capabilities: Sequence[Capability] = CAPABILITIES,
    measure: Measure = code_points,
    interaction_deadline: DurationInput = "3 seconds",
    **limits: Unpack[LimitsOverrides],
) -> Layer[_chat.Chat | Registry | ChatTest]:
    """A whole chat in memory: ``Chat``, its registry and one fake adapter.

    - Every capability is on by default; ``measure`` counts code points.
    - The default limits are 4000 per message and 10 files of up to 10 MiB.
      With ``nativeStream`` a stream takes up to ``message_length`` and
      lasts 10 minutes; with ``buttons`` or ``selects`` a message takes 25
      elements and an element's id plus encoded value 100 code points; with
      ``modals`` a modal's id plus metadata takes 100 and a modal 5 fields;
      with ``commands`` ``follow_up_age`` is 15 minutes. Keyword arguments
      named after ``Limits`` fields override them.
    - The native stream behaves the way Slack's was found to: an append
      past ``stream_length`` fails ``TooLarge`` and adds nothing, a stream
      past ``stream_age`` on ``Clock`` is closed, an append without
      ``flush`` holds back an unclosed ``<`` tail of up to 100 characters or
      a trailing high surrogate, and an open stream refuses ``edit`` and
      ``delete``.
    - ``interact`` gives a handler 3 seconds by default, on ``Clock``.
    - Two layers merged with different platforms share one ``Chat``, so
      routing can be tested; the ``ChatTest`` in context is the last one.
    """

    @fx.gen
    def make() -> Generator[Effect[Any, Never, Registry], Any, Service]:
        registry = yield from Registry()
        fake = _Fake(
            platform=platform,
            self_id=self_id,
            capabilities=frozenset(capabilities),
            limits=limits,
            measure=measure,
            interaction_deadline=interaction_deadline,
        )
        yield from registry.register(_FakeAdapter(fake))
        return Service(fake)

    return _layer_effect(ChatTest, make).pipe(_provide_merge(_chat.layer))

check_event

check_event(event, *, platform, parse_mention) -> Effect[None, ConformanceFailure]

Checks the invariants every event holds: a message event's message passes check_message and shares the event's thread; the thread is the platform's and survives its string codec; the event round-trips through its schema with the same dedupe_key every decode; a reaction's key differs between added and removed.

ParameterTypeDescription
eventChatEvent
platformstr
parse_mentionParseMention

Returns Effect[None, ConformanceFailure]

def check_event(
    event: ChatEvent, *, platform: str, parse_mention: ParseMention
) -> Effect[None, ConformanceFailure]:
    """Checks the invariants every event holds: a message event's message
    passes ``check_message`` and shares the event's thread; the thread is
    the platform's and survives its string codec; the event round-trips
    through its schema with the same ``dedupe_key`` every decode; a
    reaction's key differs between added and removed."""
    rule = "checkEvent"

    @fx.gen
    def run() -> Generator[Effect[Any, ConformanceFailure], Any]:
        yield from _check_thread(rule, event.thread, platform)
        if isinstance(event, MessageCreated):
            yield from _check_message_with(rule, event.message, platform, parse_mention)
            yield from check(
                rule,
                chat_thread.equals(event.thread, event.message.thread),
                "the event's thread equal to the message's",
                lambda: chat_thread.to_string(event.thread),
            )
        elif isinstance(event, (_event.ReactionAdded, _event.ReactionRemoved)):
            flipped: ChatEvent = (
                _event.ReactionRemoved
                if isinstance(event, _event.ReactionAdded)
                else _event.ReactionAdded
            )(
                thread=event.thread,
                message_id=event.message_id,
                message_author_id=event.message_author_id,
                user_id=event.user_id,
                emoji=event.emoji,
                timestamp=event.timestamp,
                raw=event.raw,
            )
            yield from check(
                rule,
                _event.dedupe_key(flipped) != _event.dedupe_key(event),
                "different keys for an added and a removed reaction",
                lambda: _event.dedupe_key(event),
            )
        first: ChatEvent = yield from _round_trip(rule, _EVENT_JSON, event)
        second: ChatEvent = yield from _round_trip(rule, _EVENT_JSON, event)
        key = _event.dedupe_key(event)
        yield from check(
            rule,
            _event.dedupe_key(first) == key and _event.dedupe_key(second) == key,
            "the same dedupe_key for every decode",
            lambda: f"{_event.dedupe_key(first)} and {_event.dedupe_key(second)}",
        )

    return run

check_interaction

check_interaction(interaction, *, platform) -> Effect[None, ConformanceFailure]

Checks the invariants every interaction holds: the thread is the platform's and survives its string codec; the interaction round-trips through its schema, raw included; a ModalSubmitted's message_id is non-empty when there (a command's modal has none); a CommandInvoked has a non-empty id.

ParameterTypeDescription
interactionci.Interaction
platformstr

Returns Effect[None, ConformanceFailure]

def check_interaction(
    interaction: ci.Interaction, *, platform: str
) -> Effect[None, ConformanceFailure]:
    """Checks the invariants every interaction holds: the thread is the
    platform's and survives its string codec; the interaction round-trips
    through its schema, ``raw`` included; a ``ModalSubmitted``'s
    ``message_id`` is non-empty when there (a command's modal has none); a
    ``CommandInvoked`` has a non-empty ``id``."""
    rule = "checkInteraction"
    checks = _check_thread(rule, interaction.thread, platform)
    if isinstance(interaction, ci.ModalSubmitted):
        checks = checks.and_then(
            check(
                rule,
                interaction.message_id != "",
                "a submit with no message_id or a non-empty one",
                lambda: "an empty message_id",
            )
        )
    if isinstance(interaction, ci.CommandInvoked):
        checks = checks.and_then(
            check(
                rule, interaction.id != "", "a command with a non-empty id", lambda: "an empty id"
            )
        )
    return checks.and_then(_round_trip(rule, _INTERACTION_JSON, interaction)).as_(None)

check_message

check_message(message, *, platform, parse_mention) -> Effect[None, ConformanceFailure]

Checks the invariants every message holds, for fixture tests and live runs: every mention sits inside text without overlap and its slice parses with parse_mention as its kind and id; thread.platform is the platform and the thread survives its string codec; the message encodes and decodes through its schema unchanged, raw included; every attachment has an id and no URL; reply_to.is_self is set exactly when reply_to.author_id is.

ParameterTypeDescription
messageChatMessage
platformstr
parse_mentionParseMention

Returns Effect[None, ConformanceFailure]

def check_message(
    message: ChatMessage, *, platform: str, parse_mention: ParseMention
) -> Effect[None, ConformanceFailure]:
    """Checks the invariants every message holds, for fixture tests and live
    runs: every mention sits inside ``text`` without overlap and its slice
    parses with ``parse_mention`` as its kind and id; ``thread.platform`` is
    the platform and the thread survives its string codec; the message
    encodes and decodes through its schema unchanged, ``raw`` included;
    every attachment has an id and no URL; ``reply_to.is_self`` is set
    exactly when ``reply_to.author_id`` is."""
    return _check_message_with("checkMessage", message, platform, parse_mention)

same_message

same_message(a, b) -> bool

Whether two reads of a message are the same message: id, thread, author.id/is_bot/is_self, text, mentions, reply_to, timestamp and the attachment ids in order. raw, author.name and the optional attachment fields are left out.

ParameterTypeDescription
aChatMessage
bChatMessage

Returns bool

def same_message(a: ChatMessage, b: ChatMessage) -> bool:
    """Whether two reads of a message are the same message: ``id``,
    ``thread``, ``author.id``/``is_bot``/``is_self``, ``text``,
    ``mentions``, ``reply_to``, ``timestamp`` and the attachment ids in
    order. ``raw``, ``author.name`` and the optional attachment fields are
    left out."""
    return (
        a.id == b.id
        and chat_thread.equals(a.thread, b.thread)
        and a.author.id == b.author.id
        and a.author.is_bot == b.author.is_bot
        and a.author.is_self == b.author.is_self
        and a.text == b.text
        and _same_mentions(a.mentions, b.mentions)
        and _same_reply_to(a.reply_to, b.reply_to)
        and a.timestamp == b.timestamp
        and [x.id for x in a.attachments] == [y.id for y in b.attachments]
    )

conformance

conformance(*, platform, thread, user_posts, parse_mention, refuse_files=None, interactions=None, fail_next=None) -> dict[str, Rule]

The conformance suite, as plain effects keyed by rule name, so any test runner can run them.

  • Each rule needs the adapter under test registered in Chat, and user_posts to make another identity's message appear in thread, a channel the suite may write to.
  • A rule is never skipped. When the descriptor lacks a capability a rule needs, the rule becomes its inverse: the op fails Unsupported. There is an unsupported/{capability} rule for every capability; with the capability listed it fails if the op fails Unsupported.
  • The retries/* rules exist only with fail_next, post/refusedFile only with refuse_files, the click rules only with interactions, and the command/* rules and unsupported/ephemeral only with interactions.command.
  • Every rule deletes what it posted when it ends, pass or fail, when the platform can delete.

Rule names are stable and an existing rule is never tightened. The retries/retrySafe rule waits for real time, so run the suite on a live Clock.

ParameterTypeDescription
platformstr
threadChatThread
user_postsCallable[[ChatThread, str], Effect[ChatEvent]]
parse_mentionParseMention
refuse_filesCallable[[], Effect[None]] | None = None
interactionsInteractions | None = None
fail_nextCallable[[str, AnyReason], Effect[None]] | None = None

Returns dict[str, Rule]

def conformance(
    *,
    platform: str,
    thread: ChatThread,
    user_posts: Callable[[ChatThread, str], Effect[ChatEvent]],
    parse_mention: ParseMention,
    refuse_files: Callable[[], Effect[None]] | None = None,
    interactions: Interactions | None = None,
    fail_next: Callable[[str, AnyReason], Effect[None]] | None = None,
) -> dict[str, Rule]:
    """The conformance suite, as plain effects keyed by rule name, so any
    test runner can run them.

    - Each rule needs the adapter under test registered in ``Chat``, and
      ``user_posts`` to make another identity's message appear in
      ``thread``, a channel the suite may write to.
    - A rule is never skipped. When the descriptor lacks a capability a rule
      needs, the rule becomes its inverse: the op fails ``Unsupported``.
      There is an ``unsupported/{capability}`` rule for every capability;
      with the capability listed it fails if the op fails ``Unsupported``.
    - The ``retries/*`` rules exist only with ``fail_next``,
      ``post/refusedFile`` only with ``refuse_files``, the click rules only
      with ``interactions``, and the ``command/*`` rules and
      ``unsupported/ephemeral`` only with ``interactions.command``.
    - Every rule deletes what it posted when it ends, pass or fail, when
      the platform can delete.

    Rule names are stable and an existing rule is never tightened. The
    ``retries/retrySafe`` rule waits for real time, so run the suite on a
    live ``Clock``.
    """
    options = Options(
        platform=platform,
        thread=thread,
        user_posts=user_posts,
        parse_mention=parse_mention,
        refuse_files=refuse_files,
        interactions=interactions,
        fail_next=fail_next,
    )
    rules: dict[str, Rule] = {}

    def rule(name: str, needs: Sequence[Capability], body: _Body) -> None:
        @fx.gen
        def run() -> Generator[Effect[Any, ConformanceFailure, Any], Any]:
            chat: _chat.Service = yield from _chat.Chat()
            descriptor: Descriptor = yield from chat.descriptor(platform).map_error(
                lambda error: failure(name, "a registered adapter", describe_error(error), error)
            )
            t = Tester(name, chat, descriptor, options)
            missing = first_missing(needs, descriptor.capabilities)
            yield from (body(t) if missing is None else t.probe(missing)).ensuring(t.cleanup)

        rules[name] = run

    _post_rules(rule, options)
    _message_rules(rule)
    _stream_rules(rule, options)
    _action_rules(rule)
    if interactions is not None:
        _click_rules(rule)
    if interactions is not None and interactions.command is not None:
        _command_rules(rule)
    for capability in CAPABILITIES:
        if capability not in ("modals", "modalErrors", "ephemeral"):
            rule(f"unsupported/{capability}", [], _probe(capability))
    if fail_next is not None:
        _retry_rules(rule, fail_next)
    return rules