ircbot 0.4.2

An async IRC bot framework for Rust powered by Tokio and procedural macros
Documentation
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
//! Runtime tests for the `#[bot]` / `#[command]` / `#[on(...)]` procedural
//! macros: the `Trigger` variants they generate, trigger precedence, the
//! handler count/shape, and the argument-extraction wrapper.
//!
//! Compile-time behaviour (invalid cron / timezone / non-simple type) is
//! covered separately by the trybuild UI tests in `tests/macro_ui.rs`.
//!
//! These tests inspect the private `__handlers()` function generated by
//! `#[bot]`; because they live in the same module as the annotated impl, the
//! private function is accessible.
//!
//! Run with:
//!   cargo test --test macros

use ircbot::handler::HandlerEntry;
use ircbot::testing::TestContext;
use ircbot::{bot, Context, Result, Trigger, User};

// ─── bot under test ──────────────────────────────────────────────────────────

#[bot]
impl MacroBot {
    // [0]
    #[command("ping")]
    async fn ping(&self, ctx: Context) -> Result {
        ctx.say("pong")
    }

    // [1] — target propagation
    #[command("hi", target = "#rust")]
    async fn hi_rust(&self, ctx: Context) -> Result {
        ctx.say("hi")
    }

    // [2] — Message trigger with a single String capture arg
    #[on(message = "hello *")]
    async fn greet(&self, ctx: Context, who: String) -> Result {
        ctx.say(format!("hi {who}"))
    }

    // [3] — Event trigger with a regex
    #[on(event = "JOIN", regex = "(.+)")]
    async fn on_join(&self, ctx: Context) -> Result {
        ctx.say("joined")
    }

    // [4] — Mention trigger
    #[on(mention)]
    async fn on_mention(&self, ctx: Context) -> Result {
        ctx.say("mentioned")
    }

    // [5] — Cron trigger
    #[on(cron = "0 0 * * * *", tz = "UTC")]
    async fn on_cron(&self, ctx: Context) -> Result {
        ctx.say("cron")
    }

    // [6] — precedence: message wins over command/event/mention/cron
    #[on(
        message = "winner",
        command = "loser",
        event = "ALSO_LOSER",
        mention,
        cron = "0 0 * * * *"
    )]
    async fn precedence(&self, ctx: Context) -> Result {
        ctx.say("p")
    }

    // [7] — two String capture args
    #[on(event = "PRIVMSG", regex = r"(\w+) (\w+)")]
    async fn two_args(&self, ctx: Context, a: String, b: String) -> Result {
        ctx.say(format!("{a}-{b}"))
    }

    // [8] — User arg extraction
    #[command("whoami")]
    async fn whoami(&self, ctx: Context, user: User) -> Result {
        ctx.say(user.nick)
    }

    // [9] — typed scalar command args parsed from the tail
    #[command("add")]
    async fn add(&self, ctx: Context, a: i64, b: i64) -> Result {
        ctx.say(format!("{}", a + b))
    }

    // [10] — scalar arg followed by a trailing rest-of-line String
    #[command("repeat")]
    async fn repeat(&self, ctx: Context, n: u32, text: String) -> Result {
        ctx.say(text.repeat(n as usize))
    }

    // [11] — optional trailing scalar arg
    #[command("maybe")]
    async fn maybe(&self, ctx: Context, n: Option<u32>) -> Result {
        ctx.say(format!("{n:?}"))
    }

    // [12] — variadic trailing Vec<String>
    #[command("tags")]
    async fn tags(&self, ctx: Context, items: Vec<String>) -> Result {
        ctx.say(items.join(","))
    }

    // [13] — role-gated command
    #[command("ban", role = "admin")]
    async fn ban(&self, ctx: Context) -> Result {
        ctx.say("banned")
    }

    // Plain (non-annotated) method — must remain callable and produce NO entry.
    fn helper(&self) -> u32 {
        42
    }
}

// ─── helpers ─────────────────────────────────────────────────────────────────

fn handlers() -> Vec<HandlerEntry<MacroBot>> {
    MacroBot::__handlers()
}

/// Invoke a handler entry with a context taken from `tc`, returning the first
/// reply line written.
async fn invoke(entry: &HandlerEntry<MacroBot>, mut tc: TestContext) -> Option<String> {
    let bot = std::sync::Arc::new(MacroBot::default());
    (entry.handler)(bot, tc.take_ctx()).await.unwrap();
    tc.next_reply()
}

// ─── trigger variants ────────────────────────────────────────────────────────

#[test]
fn command_attr_yields_command_trigger() {
    match &handlers()[0].trigger {
        Trigger::Command { name, target, .. } => {
            assert_eq!(name, "ping");
            assert_eq!(target.as_deref(), None);
        }
        other => panic!("expected Command, got {other:?}"),
    }
}

#[test]
fn command_target_propagates() {
    match &handlers()[1].trigger {
        Trigger::Command { name, target, .. } => {
            assert_eq!(name, "hi");
            assert_eq!(target.as_deref(), Some("#rust"));
        }
        other => panic!("expected Command, got {other:?}"),
    }
}

#[test]
fn on_message_yields_message_trigger() {
    match &handlers()[2].trigger {
        Trigger::Message { pattern, .. } => assert_eq!(pattern, "hello *"),
        other => panic!("expected Message, got {other:?}"),
    }
}

#[test]
fn on_event_with_regex_yields_event_trigger() {
    match &handlers()[3].trigger {
        Trigger::Event {
            event,
            target,
            regex,
        } => {
            assert_eq!(event, "JOIN");
            assert_eq!(target.as_deref(), None);
            assert_eq!(regex.as_deref(), Some("(.+)"));
        }
        other => panic!("expected Event, got {other:?}"),
    }
}

#[test]
fn on_mention_yields_mention_trigger() {
    assert!(matches!(
        &handlers()[4].trigger,
        Trigger::Mention { target: None }
    ));
}

#[test]
fn on_cron_yields_cron_trigger() {
    match &handlers()[5].trigger {
        Trigger::Cron { schedule, tz, .. } => {
            assert_eq!(schedule, "0 0 * * * *");
            assert_eq!(tz, "UTC");
        }
        other => panic!("expected Cron, got {other:?}"),
    }
}

#[test]
fn message_wins_trigger_precedence() {
    // message > command > event > mention > cron — only the message survives.
    match &handlers()[6].trigger {
        Trigger::Message { pattern, .. } => assert_eq!(pattern, "winner"),
        other => panic!("expected Message (precedence), got {other:?}"),
    }
}

// ─── handler count / shape ───────────────────────────────────────────────────

#[test]
fn only_annotated_methods_produce_handler_entries() {
    // 14 annotated methods; the plain `helper` produces no entry.
    assert_eq!(handlers().len(), 14);
}

#[test]
fn command_role_propagates() {
    match &handlers()[13].trigger {
        Trigger::Command { name, role, .. } => {
            assert_eq!(name, "ban");
            assert_eq!(role.as_deref(), Some("admin"));
        }
        other => panic!("expected Command, got {other:?}"),
    }
}

#[test]
fn command_without_role_has_none() {
    match &handlers()[0].trigger {
        Trigger::Command { name, role, .. } => {
            assert_eq!(name, "ping");
            assert_eq!(role.as_deref(), None);
        }
        other => panic!("expected Command, got {other:?}"),
    }
}

#[test]
fn plain_method_remains_callable() {
    assert_eq!(MacroBot::default().helper(), 42);
}

// ─── argument extraction (build_wrapper) ─────────────────────────────────────

#[tokio::test]
async fn string_arg_filled_from_captures_when_present() {
    let entry = &handlers()[2]; // greet(who: String)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["world".to_string()])
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :hi world\r\n".to_string())
    );
}

#[tokio::test]
async fn string_arg_falls_back_to_message_text_when_no_captures() {
    let entry = &handlers()[2]; // greet(who: String)
    let tc = TestContext::builder()
        .target("#test")
        .text("raw body")
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :hi raw body\r\n".to_string())
    );
}

#[tokio::test]
async fn two_string_args_pull_successive_captures() {
    let entry = &handlers()[7]; // two_args(a, b: String)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["foo".to_string(), "bar".to_string()])
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :foo-bar\r\n".to_string())
    );
}

#[tokio::test]
async fn user_arg_filled_from_sender() {
    let entry = &handlers()[8]; // whoami(user: User)
    let tc = TestContext::builder()
        .target("#test")
        .sender_nick("zaphod")
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :zaphod\r\n".to_string())
    );
}

// ─── typed command arguments ─────────────────────────────────────────────────

#[tokio::test]
async fn typed_scalar_args_parsed_from_command_tail() {
    let entry = &handlers()[9]; // add(a: i64, b: i64)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["3 4".to_string()])
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :7\r\n".to_string())
    );
}

#[tokio::test]
async fn typed_scalar_parse_failure_replies_usage() {
    let entry = &handlers()[9]; // add(a: i64, b: i64)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["foo 4".to_string()])
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :tester, usage: !add <a> <b>\r\n".to_string())
    );
}

#[tokio::test]
async fn missing_required_arg_replies_usage() {
    let entry = &handlers()[9]; // add(a: i64, b: i64)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["3".to_string()])
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :tester, usage: !add <a> <b>\r\n".to_string())
    );
}

#[tokio::test]
async fn trailing_string_captures_rest_of_line() {
    let entry = &handlers()[10]; // repeat(n: u32, text: String)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["2 ab cd".to_string()])
        .build();
    // n = 2, text = "ab cd" (rest, verbatim) -> repeated twice.
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :ab cdab cd\r\n".to_string())
    );
}

#[tokio::test]
async fn optional_arg_is_some_when_present() {
    let entry = &handlers()[11]; // maybe(n: Option<u32>)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["42".to_string()])
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :Some(42)\r\n".to_string())
    );
}

#[tokio::test]
async fn optional_arg_is_none_when_absent() {
    let entry = &handlers()[11]; // maybe(n: Option<u32>)
    let tc = TestContext::builder().target("#test").build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :None\r\n".to_string())
    );
}

#[tokio::test]
async fn optional_arg_present_but_unparseable_replies_usage() {
    let entry = &handlers()[11]; // maybe(n: Option<u32>)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["notanumber".to_string()])
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :tester, usage: !maybe [n]\r\n".to_string())
    );
}

#[tokio::test]
async fn variadic_vec_collects_remaining_tokens() {
    let entry = &handlers()[12]; // tags(items: Vec<String>)
    let tc = TestContext::builder()
        .target("#test")
        .captures(vec!["red green blue".to_string()])
        .build();
    assert_eq!(
        invoke(entry, tc).await,
        Some("PRIVMSG #test :red,green,blue\r\n".to_string())
    );
}

// ─── from_state constructor ────────────────────────────────────────────────────

/// State whose `Default` is *not* test-safe: it records whether it was built
/// the easy way, so a test can prove `from_state` skipped `Default`.
struct StateBotState {
    greeting: String,
    from_default: bool,
}

impl Default for StateBotState {
    fn default() -> Self {
        // Stand-in for real work (opening a DB, reading the environment, …)
        // that a unit test must not trigger.
        StateBotState {
            greeting: "default".to_string(),
            from_default: true,
        }
    }
}

#[bot(state = StateBotState)]
impl StateBot {
    #[on(mention)]
    async fn hello(&self, ctx: Context, _text: String) -> Result {
        ctx.reply(self.state.greeting.clone())
    }
}

#[tokio::test]
async fn from_state_injects_given_state_and_skips_default() {
    let bot = StateBot::from_state(StateBotState {
        greeting: "hi!".to_string(),
        from_default: false,
    });
    // The injected state is used verbatim — `Default` never ran.
    assert!(!bot.state.from_default);

    let mut tc = TestContext::channel("#test", "alice", "statebot: yo");
    bot.hello(tc.take_ctx(), "yo".to_string()).await.unwrap();
    assert_eq!(
        tc.next_reply(),
        Some("PRIVMSG #test :alice, hi!\r\n".to_string())
    );
}