# Testing

A test client answers requests inside the process and records every one it sends, so a bot's tests need no token
and no network. The test kit is `vaegram::test`.

## Example

```rust
use vaegram::filters;
use vaegram::test::{CallKind, TestMessage};
use vaegram::Client;

#[tokio::main]
async fn main() {
    let (client, recorder) = Client::recording();
    client.on_message(filters::command("start"), |msg| async move { msg.reply("Welcome!").await });

    recorder.feed(TestMessage::private(42, "/start")).await;

    assert_eq!(recorder.sent_texts(42), ["Welcome!"]);
    assert!(recorder.calls().iter().any(|call| matches!(
        &call.kind,
        CallKind::SendMessage { reply_to_message_id: Some(_), .. }
    )));
}
```

## How it works

### A client that never connects

`Client::recording()` returns a bot client, id 1000, and a `CallRecorder`. The client answers the requests bots send
most with what Telegram would answer, numbering messages from 1 up (`src/test/mod.rs:27-46`), and the recorder
keeps each request it sent. `Client::scripted()` returns a `Script` instead: strict, so a request it has no answer
for fails, until `auto_reply(true)` turns the same defaults on. Both keep their login and peers in memory and never
retry (`src/test/mod.rs:144`). Make them inside a Tokio runtime, such as the one `#[tokio::test]` starts.

`TestBuilder` sets the account and the client's settings first (`src/test/mod.rs:135-205`):
`bot(id, Some("username"))` or `user(id, premium)`, then `ordered(true)`, `max_concurrent_handlers(n)`,
`parse_mode(mode)` and `auto_sleep(policy)`; `recording()` or `scripted()` finishes.

### Feeding updates

`recorder.feed(update)` hands an update to the handlers and waits for them to finish. `dispatch(update)` returns
once they start, and `settle()` waits for everything running; `feed` is the two together
(`src/test/harness.rs:86-107`). `recv()` waits for the next request the client sends, for a handler running on its
own task.

Build updates with `TestMessage::private(user_id, text)` or `TestMessage::in_chat(chat, user, text)`, which take
`.reply_to(id)`, `.thread_id(topic)`, `.id(id)` and `.outgoing(true)`, and with
`TestCallbackQuery::new(user_id, chat_id, message_id, data)`. `TestChat::private`, `group`, `supergroup` and
`channel` build the chat, and `TestChat::supergroup(id).forum(true)` adds topics; `TestUser::new(id)` is the
sender. The users and chats an update names land in the client's peer cache, so `client.send_message(42, ..)` works
afterwards; `know_user` and `know_chat` add peers no update named. `TestUpdate::EditedMessage(msg)` feeds an edit.

A handler that waits for a second update, in `ask` or `listen`, would keep `feed` waiting for it. Dispatch the
first update, await the question with `recv`, feed the answer, then settle:

```rust
use vaegram::filters;
use vaegram::test::TestMessage;
use vaegram::Client;

# async fn f() {
let (client, recorder) = Client::recording();
client.on_message(filters::command("name"), |msg| async move {
    let answer = msg.client().ask(msg.chat.id, "What's your name?").await?;
    msg.reply(format!("Hi, {}", answer.text())).await
});

recorder.dispatch(TestMessage::private(42, "/name")).await;
assert!(recorder.recv().await.is_some(), "the question was sent");
recorder.feed(TestMessage::private(42, "Ann")).await;
recorder.settle().await;
assert_eq!(recorder.sent_texts(42), ["What's your name?", "Hi, Ann"]);
# }
```

### What the bot sent

`calls()` returns every `RecordedCall` since the last `take_calls()`: its `method` is the TL name, such as
`"messages.sendMessage"`, and its `kind` is a `CallKind` for the requests bots send most. Match with `..`, since a
variant may gain fields. `sent_texts(chat_id)` is the shortcut for the texts of the text messages sent there; media
sends and edits are not in it.

### Choosing answers

A `Script` answers in this order: the next reply queued for the method with `reply_next` or `fail_next`, the
method's `on_call` responder, the default answer when `auto_reply` is on (`src/test/mod.rs:294-297`). A queued
`Reply` is `OkDefault`, `Bool(b)`, `SentMessage { id }`, or `Error(error)`:

```rust
use std::time::Duration;

use vaegram::test::Reply;
use vaegram::{Client, RpcError};

# async fn f() {
let (client, script) = Client::scripted();
script.auto_reply(true);
script.fail_next("messages.sendMessage", RpcError::new(420, "FLOOD_WAIT", Some(30)));

// A test client never retries: the flood wait comes straight back.
let error = client.send_message(42, "hi").await.unwrap_err();
assert_eq!(error.flood_wait(), Some(Duration::from_secs(30)));

script.on_call("messages.sendMessage", |_call| Reply::SentMessage { id: 7 });
assert_eq!(client.send_message(42, "hi").await.unwrap().id, 7);
# }
```

A request the script has no answer for fails with `TestError::Unscripted` inside `Error::Other`; read it back with
`error.downcast_ref::<TestError>()`.

### The update loop

`recorder.push_stream(update)` feeds `run` the way the connection does, through the tracker that holds updates on a
`pts` gap, and `close_stream()` ends it. Start `run` on a task of its own first. Use it only to test that layer:
`feed` and `dispatch` skip it.

### What a test client does not do

It never dials Telegram, and a file transfer to another data center fails at once. On a recording client, and on a
script with `auto_reply` on, a request without a default answer, such as fetching old messages, fails with
`TestError::NoDefaultAnswer`; answer it with `on_call`. A strict script, with `auto_reply` off, answers nothing it was
not given, so every request without a queued reply or an `on_call` responder fails with `TestError::Unscripted`.

## Common mistakes

- `feed` hangs in a handler that waits in `ask`: dispatch the first update, take the question with `recv`, feed
  the answer, then settle (`src/test/harness.rs:88-107`).
- Asserting too early: a conversation or a spawned task runs on its own task; settle before you assert.
- Matching a `CallKind` without `..`: each variant may gain fields (`src/test/calls.rs:36-39`).
- Creating a test client outside a runtime: `Client::recording` panics; call it inside `#[tokio::test]`.
- Expecting media in `sent_texts`: it lists `SendMessage` only (`src/test/mod.rs:279-289`); match
  `CallKind::SendMedia` in `calls`.
- Expecting a peer to be known: only users and chats an update named, or `know_user`/`know_chat`, are cached.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/test/index.html) for `TestBuilder`, `CallRecorder` and `Script`.
- [Receiving updates](/docs/receiving-updates.md) for the handlers and `run` the kit drives.
- [Filters](/docs/filters.md) for picking the updates to feed.
- [Dialogues](/docs/dialogues.md) and [Conversations](/docs/conversations.md) for the flows a test usually drives.