laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use crate::console::ConsoleInternals as _;
use std::ffi::OsString;
use std::future::{Future, IntoFuture};
use std::panic::Location;
use std::pin::Pin;

use crate::Application;
use crate::console::{Answer, ChoiceAnswer, Console, ExpectedPrompt, Signal};

/// Runs the application's console commands in tests and captures their output.
///
/// Each method returns a [`TestCommand`]. Await it to run the command and get its result.
///
/// ```
/// use laravel::console::{Console, clap};
/// use laravel::testing::MakesConsoleRequests;
///
/// #[derive(clap::Parser)]
/// #[command(name = "greet")]
/// struct Greet {
///     name: String,
/// }
///
/// #[laravel::console::command]
/// impl Greet {
///     async fn handle(self, console: &mut Console) -> laravel::Result<()> {
///         console.line(format!("Hello, {}!", self.name));
///
///         Ok(())
///     }
/// }
///
/// let app = laravel::Application::configure()
///     .replace_env(laravel::config::Env::default())
///     .with_commands(|commands, _| {
///         commands.add::<Greet>();
///     })
///     .create();
///
/// laravel::testing::__run(async {
///     app.command("greet 'Taylor Otwell'")
///         .await
///         .assert_successful()
///         .assert_output_contains("Hello, Taylor Otwell!");
/// });
/// ```
///
/// Commands run in the test's process. They don't install logging, handle process signals, or
/// export `.env` to the process environment. Otherwise they do their normal work, including
/// writing files. Framework commands such as `migrate` run the same way. The exception is
/// `serve`, which needs the application's binary, so only `serve --help` works in a test.
pub trait MakesConsoleRequests {
    /// Run a command line, such as `"greet 'Taylor Otwell'"`.
    ///
    /// The line is split into arguments at spaces, and quotes and backslash escapes work as they
    /// do in a shell. No shell runs, so variables and command substitutions stay as written.
    ///
    /// # Panics
    ///
    /// Panics when the command line has an unmatched quote or escape.
    #[track_caller]
    fn command(&self, command: &str) -> TestCommand;

    /// Run a command with exact arguments, starting with its name, such as
    /// `["import", "data/users.csv"]`.
    ///
    /// The arguments may be OS strings, so a test can pass a file path that isn't valid UTF-8.
    #[track_caller]
    fn command_args<I, S>(&self, arguments: I) -> TestCommand
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>;
}

impl MakesConsoleRequests for Application {
    #[track_caller]
    fn command(&self, command: &str) -> TestCommand {
        let Some(arguments) = shlex::split(command) else {
            panic!("`{command}` has an unmatched quote or escape");
        };

        TestCommand::new(self, arguments.into_iter().map(OsString::from).collect())
    }

    #[track_caller]
    fn command_args<I, S>(&self, arguments: I) -> TestCommand
    where
        I: IntoIterator<Item = S>,
        S: Into<OsString>,
    {
        TestCommand::new(self, arguments.into_iter().map(Into::into).collect())
    }
}

/// A command to run, from [`MakesConsoleRequests`].
///
/// Its methods script the answers to the command's prompts and the signals it receives. Awaiting
/// it boots the application if needed, runs the command, and returns a [`TestCommandResult`].
///
/// A command that fails exits with a nonzero code and writes its error to stderr, including when
/// the application fails to boot. Awaiting it doesn't panic in that case, so check the result
/// with [`assert_failed`](TestCommandResult::assert_failed).
///
/// Without any `expects_` calls, each prompt takes its default answer, and a prompt without a
/// default fails the command because it can't ask anyone. With `expects_` calls, the command
/// must ask exactly the expected prompts, in order.
///
/// # Panics
///
/// When the test expects prompts, awaiting the command panics if a prompt fails, such as a
/// prompt other than the next expected one or a prompt that rejects its scripted answer. It also
/// panics if the command didn't ask every expected prompt, or didn't trap a signal sent with
/// [`sends_signal`](Self::sends_signal). The panic message includes the exit code and both
/// output streams.
#[derive(Debug)]
#[must_use = "a test command does nothing unless awaited"]
pub struct TestCommand {
    application: Application,
    arguments: Vec<OsString>,
    prompts: Vec<ExpectedPrompt>,
    signals: Vec<Signal>,
    location: &'static Location<'static>,
}

impl TestCommand {
    #[track_caller]
    fn new(application: &Application, arguments: Vec<OsString>) -> Self {
        Self {
            application: application.clone(),
            arguments,
            prompts: Vec::new(),
            signals: Vec::new(),
            location: Location::caller(),
        }
    }

    /// Expect the command's next prompt to be a text question, and answer it.
    ///
    /// ```no_run
    /// use laravel::testing::MakesConsoleRequests;
    ///
    /// # async fn example(app: laravel::Application) {
    /// app.command("make:user")
    ///     .expects_question("Name?", "Taylor")
    ///     .expects_confirmation("Make them an admin?", false)
    ///     .await
    ///     .assert_successful();
    /// # }
    /// ```
    pub fn expects_question(self, question: impl Into<String>, answer: impl Into<String>) -> Self {
        self.expect(question.into(), Answer::Text(answer.into()))
    }

    /// Expect the command's next prompt to be a confirmation, and answer it.
    pub fn expects_confirmation(self, question: impl Into<String>, answer: bool) -> Self {
        self.expect(question.into(), Answer::Confirmation(answer))
    }

    /// Expect the command's next prompt to be a choice, and answer with one of its values.
    ///
    /// A string literal answers a menu of `String` or `&str` values. Any other answer must have
    /// the menu's value type. An answer of another type fails the prompt with a message that
    /// names both types.
    ///
    /// ```no_run
    /// use laravel::testing::MakesConsoleRequests;
    ///
    /// #[derive(Clone, PartialEq, Eq)]
    /// enum Environment {
    ///     Production,
    ///     Staging,
    /// }
    ///
    /// # async fn example(app: laravel::Application) {
    /// app.command("deploy")
    ///     .expects_choice("Environment?", Environment::Staging)
    ///     .await
    ///     .assert_successful();
    /// # }
    /// ```
    pub fn expects_choice<T: Send + 'static>(self, question: impl Into<String>, answer: T) -> Self {
        self.expect(question.into(), Answer::Choice(ChoiceAnswer::new(answer)))
    }

    /// Expect the command's next prompt to be a multiselect, and answer with these values.
    ///
    /// Each answer must be one of the menu's options, and may appear only once. The answers must
    /// have the menu's value type, even when there are none. String literals also answer a menu
    /// of `String` values. For borrowed text that isn't a literal, pass owned `String`s.
    ///
    /// ```no_run
    /// use laravel::testing::MakesConsoleRequests;
    ///
    /// # async fn example(app: laravel::Application) {
    /// app.command("make:user")
    ///     .expects_multiselect("Roles?", ["editor"])
    ///     .await
    ///     .assert_successful();
    /// # }
    /// ```
    pub fn expects_multiselect<I, S>(self, question: impl Into<String>, answers: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Send + 'static,
    {
        self.expect(
            question.into(),
            Answer::Multiple(ChoiceAnswer::new(answers.into_iter().collect::<Vec<S>>())),
        )
    }

    /// Expect the command's next prompt to be a password, and answer it.
    ///
    /// Failure messages and `Debug` output hide the answer.
    pub fn expects_password(self, question: impl Into<String>, answer: impl Into<String>) -> Self {
        self.expect(question.into(), Answer::Secret(answer.into()))
    }

    fn expect(mut self, question: String, answer: Answer) -> Self {
        self.prompts.push(ExpectedPrompt { question, answer });
        self
    }

    /// Send the command a signal once it traps that signal.
    ///
    /// The signal arrives the next time the command's handler yields. Signals arrive in the order
    /// you send them, and only this command receives them. The test sends no real process signal
    /// and installs no OS handler.
    ///
    /// ```no_run
    /// use laravel::console::Signal;
    /// use laravel::testing::MakesConsoleRequests;
    ///
    /// # async fn example(app: laravel::Application) {
    /// app.command("queue:work")
    ///     .sends_signal(Signal::Interrupt)
    ///     .await
    ///     .assert_successful();
    /// # }
    /// ```
    pub fn sends_signal(mut self, signal: Signal) -> Self {
        self.signals.push(signal);
        self
    }
}

impl IntoFuture for TestCommand {
    type Output = TestCommandResult;
    type IntoFuture = Pin<Box<dyn Future<Output = TestCommandResult> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let mut console = Console::captured();
            console.expect_prompts(self.prompts);
            console.signals.expect(self.signals);

            let exit_code = self
                .application
                .run_command(OsString::from("app"), self.arguments, &mut console)
                .await;

            let mut unmet = console.unmet_prompts();
            unmet.extend(console.signals.unmet());
            let questions = std::mem::take(&mut console.questions);
            let (output, error_output) = console.into_output();
            let result = TestCommandResult {
                exit_code,
                output,
                error_output,
                questions,
            };

            assert!(
                unmet.is_empty(),
                "{}\n\n{}\n\nat {}",
                unmet.join("\n"),
                result.diagnostics(),
                self.location
            );

            result
        })
    }
}

/// How a command ended, with assertions.
///
/// The result holds the command's exit code, and its stdout and stderr, which the test captures
/// separately and without terminal styling. When an assertion fails, its message includes the
/// exit code and both output streams.
#[derive(Debug)]
pub struct TestCommandResult {
    exit_code: u8,
    output: String,
    error_output: String,
    questions: Vec<String>,
}

impl TestCommandResult {
    /// The command's exit code.
    #[must_use]
    pub const fn exit_code(&self) -> u8 {
        self.exit_code
    }

    /// The command's stdout, without terminal styling.
    #[must_use]
    pub fn output(&self) -> &str {
        &self.output
    }

    /// The command's stderr, without terminal styling.
    #[must_use]
    pub fn error_output(&self) -> &str {
        &self.error_output
    }

    /// The questions of the prompts the command asked, in order.
    ///
    /// The list includes prompts that took their default answer, and prompts that failed the
    /// command because they had no default and the test scripted no answers.
    #[must_use]
    pub fn questions(&self) -> &[String] {
        &self.questions
    }

    /// Assert the exit code.
    ///
    /// # Panics
    ///
    /// Panics when the command exited with another code.
    #[track_caller]
    pub fn assert_exit_code(&self, expected: u8) -> &Self {
        assert!(
            self.exit_code == expected,
            "expected exit code {expected}\n{}",
            self.diagnostics()
        );
        self
    }

    /// Assert that the command succeeded with exit code `0`.
    ///
    /// # Panics
    ///
    /// Panics when the command exited with another code.
    #[track_caller]
    pub fn assert_successful(&self) -> &Self {
        self.assert_exit_code(0)
    }

    /// Assert that the command failed with a nonzero exit code.
    ///
    /// # Panics
    ///
    /// Panics when the command exited with `0`.
    #[track_caller]
    pub fn assert_failed(&self) -> &Self {
        assert!(
            self.exit_code != 0,
            "expected the command to fail\n{}",
            self.diagnostics()
        );
        self
    }

    /// Assert that stdout contains the given text.
    ///
    /// # Panics
    ///
    /// Panics when stdout doesn't contain the text.
    #[track_caller]
    pub fn assert_output_contains(&self, expected: &str) -> &Self {
        assert!(
            self.output.contains(expected),
            "expected stdout to contain {expected:?}\n{}",
            self.diagnostics()
        );
        self
    }

    /// Assert that stderr contains the given text.
    ///
    /// # Panics
    ///
    /// Panics when stderr doesn't contain the text.
    #[track_caller]
    pub fn assert_error_output_contains(&self, expected: &str) -> &Self {
        assert!(
            self.error_output.contains(expected),
            "expected stderr to contain {expected:?}\n{}",
            self.diagnostics()
        );
        self
    }

    /// Assert that stdout doesn't contain the given text.
    ///
    /// # Panics
    ///
    /// Panics when stdout contains the text.
    #[track_caller]
    pub fn assert_output_missing(&self, unexpected: &str) -> &Self {
        assert!(
            !self.output.contains(unexpected),
            "expected stdout not to contain {unexpected:?}\n{}",
            self.diagnostics()
        );
        self
    }

    /// Assert that stderr doesn't contain the given text.
    ///
    /// # Panics
    ///
    /// Panics when stderr contains the text.
    #[track_caller]
    pub fn assert_error_output_missing(&self, unexpected: &str) -> &Self {
        assert!(
            !self.error_output.contains(unexpected),
            "expected stderr not to contain {unexpected:?}\n{}",
            self.diagnostics()
        );
        self
    }

    /// Assert that the command printed nothing to stdout or stderr.
    ///
    /// # Panics
    ///
    /// Panics when the command printed something.
    #[track_caller]
    pub fn assert_no_output(&self) -> &Self {
        assert!(
            self.output.is_empty() && self.error_output.is_empty(),
            "expected no output\n{}",
            self.diagnostics()
        );
        self
    }

    /// Assert that the command asked a prompt with this exact question.
    ///
    /// # Panics
    ///
    /// Panics when the command didn't ask the question.
    #[track_caller]
    pub fn assert_asked(&self, question: &str) -> &Self {
        assert!(
            self.questions.iter().any(|asked| asked == question),
            "expected question {question:?}; asked: {:?}\n{}",
            self.questions,
            self.diagnostics()
        );
        self
    }

    fn diagnostics(&self) -> String {
        format!(
            "exit code: {}\nstdout:\n{}\nstderr:\n{}",
            self.exit_code, self.output, self.error_output
        )
    }
}