nu_plugin_test_support/
plugin_test.rs

1use std::{cmp::Ordering, convert::Infallible, sync::Arc};
2
3use nu_ansi_term::Style;
4use nu_cmd_lang::create_default_context;
5use nu_engine::eval_block;
6use nu_parser::parse;
7use nu_plugin::{Plugin, PluginCommand};
8use nu_plugin_engine::{PluginCustomValueWithSource, PluginSource, WithSource};
9use nu_plugin_protocol::PluginCustomValue;
10use nu_protocol::{
11    CustomValue, Example, IntoSpanned as _, LabeledError, PipelineData, ShellError, Signals, Span,
12    Value,
13    debugger::WithoutDebug,
14    engine::{EngineState, Stack, StateWorkingSet},
15    report_shell_error,
16};
17
18use crate::{diff::diff_by_line, fake_register::fake_register};
19
20/// An object through which plugins can be tested.
21pub struct PluginTest {
22    engine_state: EngineState,
23    source: Arc<PluginSource>,
24    entry_num: usize,
25}
26
27impl PluginTest {
28    /// Create a new test for the given `plugin` named `name`.
29    ///
30    /// # Example
31    ///
32    /// ```rust,no_run
33    /// # use nu_plugin_test_support::PluginTest;
34    /// # use nu_protocol::ShellError;
35    /// # use nu_plugin::*;
36    /// # fn test(MyPlugin: impl Plugin + Send + 'static) -> Result<PluginTest, ShellError> {
37    /// PluginTest::new("my_plugin", MyPlugin.into())
38    /// # }
39    /// ```
40    pub fn new(
41        name: &str,
42        plugin: Arc<impl Plugin + Send + 'static>,
43    ) -> Result<PluginTest, ShellError> {
44        let mut engine_state = create_default_context();
45        let mut working_set = StateWorkingSet::new(&engine_state);
46
47        let reg_plugin = fake_register(&mut working_set, name, plugin)?;
48        let source = Arc::new(PluginSource::new(reg_plugin));
49
50        engine_state.merge_delta(working_set.render())?;
51
52        Ok(PluginTest {
53            engine_state,
54            source,
55            entry_num: 1,
56        })
57    }
58
59    /// Get the [`EngineState`].
60    pub fn engine_state(&self) -> &EngineState {
61        &self.engine_state
62    }
63
64    /// Get a mutable reference to the [`EngineState`].
65    pub fn engine_state_mut(&mut self) -> &mut EngineState {
66        &mut self.engine_state
67    }
68
69    /// Make additional command declarations available for use by tests.
70    ///
71    /// This can be used to pull in commands from `nu-cmd-lang` for example, as required.
72    pub fn add_decl(
73        &mut self,
74        decl: Box<dyn nu_protocol::engine::Command>,
75    ) -> Result<&mut Self, ShellError> {
76        let mut working_set = StateWorkingSet::new(&self.engine_state);
77        working_set.add_decl(decl);
78        self.engine_state.merge_delta(working_set.render())?;
79        Ok(self)
80    }
81
82    /// Evaluate some Nushell source code with the plugin commands in scope with the given input to
83    /// the pipeline.
84    ///
85    /// # Example
86    ///
87    /// ```rust,no_run
88    /// # use nu_plugin_test_support::PluginTest;
89    /// # use nu_protocol::{IntoInterruptiblePipelineData, ShellError, Signals, Span, Value};
90    /// # use nu_plugin::*;
91    /// # fn test(MyPlugin: impl Plugin + Send + 'static) -> Result<(), ShellError> {
92    /// let result = PluginTest::new("my_plugin", MyPlugin.into())?
93    ///     .eval_with(
94    ///         "my-command",
95    ///         vec![Value::test_int(42)].into_pipeline_data(Span::test_data(), Signals::empty())
96    ///     )?
97    ///     .into_value(Span::test_data())?;
98    /// assert_eq!(Value::test_string("42"), result);
99    /// # Ok(())
100    /// # }
101    /// ```
102    pub fn eval_with(
103        &mut self,
104        nu_source: &str,
105        input: PipelineData,
106    ) -> Result<PipelineData, ShellError> {
107        let mut working_set = StateWorkingSet::new(&self.engine_state);
108        let fname = format!("entry #{}", self.entry_num);
109        self.entry_num += 1;
110
111        // Parse the source code
112        let block = parse(&mut working_set, Some(&fname), nu_source.as_bytes(), false);
113
114        // Check for parse errors
115        let error = if !working_set.parse_errors.is_empty() {
116            // ShellError doesn't have ParseError, use LabeledError to contain it.
117            let mut error = LabeledError::new("Example failed to parse");
118            error.inner.extend(
119                working_set
120                    .parse_errors
121                    .iter()
122                    .map(LabeledError::from_diagnostic),
123            );
124            Some(ShellError::LabeledError(error.into()))
125        } else {
126            None
127        };
128
129        // Merge into state
130        self.engine_state.merge_delta(working_set.render())?;
131
132        // Return error if set. We merge the delta even if we have errors so that printing the error
133        // based on the engine state still works.
134        if let Some(error) = error {
135            return Err(error);
136        }
137
138        // Serialize custom values in the input
139        let source = self.source.clone();
140        let input = if matches!(input, PipelineData::ByteStream(..)) {
141            input
142        } else {
143            input.map(
144                move |mut value| {
145                    let result = PluginCustomValue::serialize_custom_values_in(&mut value)
146                        // Make sure to mark them with the source so they pass correctly, too.
147                        .and_then(|_| {
148                            PluginCustomValueWithSource::add_source_in(&mut value, &source)
149                        });
150                    match result {
151                        Ok(()) => value,
152                        Err(err) => Value::error(err, value.span()),
153                    }
154                },
155                &Signals::empty(),
156            )?
157        };
158
159        // Eval the block with the input
160        let mut stack = Stack::new().collect_value();
161        let data = eval_block::<WithoutDebug>(&self.engine_state, &mut stack, &block, input)?;
162        if matches!(data, PipelineData::ByteStream(..)) {
163            Ok(data)
164        } else {
165            data.map(
166                |mut value| {
167                    // Make sure to deserialize custom values
168                    let result = PluginCustomValueWithSource::remove_source_in(&mut value)
169                        .and_then(|_| PluginCustomValue::deserialize_custom_values_in(&mut value));
170                    match result {
171                        Ok(()) => value,
172                        Err(err) => Value::error(err, value.span()),
173                    }
174                },
175                &Signals::empty(),
176            )
177        }
178    }
179
180    /// Evaluate some Nushell source code with the plugin commands in scope.
181    ///
182    /// # Example
183    ///
184    /// ```rust,no_run
185    /// # use nu_plugin_test_support::PluginTest;
186    /// # use nu_protocol::{ShellError, Span, Value, IntoInterruptiblePipelineData};
187    /// # use nu_plugin::*;
188    /// # fn test(MyPlugin: impl Plugin + Send + 'static) -> Result<(), ShellError> {
189    /// let result = PluginTest::new("my_plugin", MyPlugin.into())?
190    ///     .eval("42 | my-command")?
191    ///     .into_value(Span::test_data())?;
192    /// assert_eq!(Value::test_string("42"), result);
193    /// # Ok(())
194    /// # }
195    /// ```
196    pub fn eval(&mut self, nu_source: &str) -> Result<PipelineData, ShellError> {
197        self.eval_with(nu_source, PipelineData::empty())
198    }
199
200    /// Test a list of plugin examples. Prints an error for each failing example.
201    ///
202    /// See [`.test_command_examples()`] for easier usage of this method on a command's examples.
203    ///
204    /// # Example
205    ///
206    /// ```rust,no_run
207    /// # use nu_plugin_test_support::PluginTest;
208    /// # use nu_protocol::{ShellError, Example, Value};
209    /// # use nu_plugin::*;
210    /// # fn test(MyPlugin: impl Plugin + Send + 'static) -> Result<(), ShellError> {
211    /// PluginTest::new("my_plugin", MyPlugin.into())?
212    ///     .test_examples(&[
213    ///         Example {
214    ///             example: "my-command",
215    ///             description: "Run my-command",
216    ///             result: Some(Value::test_string("my-command output")),
217    ///         },
218    ///     ])
219    /// # }
220    /// ```
221    pub fn test_examples(&mut self, examples: &[Example]) -> Result<(), ShellError> {
222        let mut failed = false;
223
224        for example in examples {
225            let bold = Style::new().bold();
226            let mut failed_header = || {
227                failed = true;
228                eprintln!("{} {}", bold.paint("Example:"), example.example);
229                eprintln!("{} {}", bold.paint("Description:"), example.description);
230            };
231            if let Some(expectation) = &example.result {
232                match self.eval(example.example) {
233                    Ok(data) => {
234                        let mut value = data.into_value(Span::test_data())?;
235
236                        // Set all of the spans in the value to test_data() to avoid unnecessary
237                        // differences when printing
238                        let _: Result<(), Infallible> = value.recurse_mut(&mut |here| {
239                            here.set_span(Span::test_data());
240                            Ok(())
241                        });
242
243                        // Check for equality with the result
244                        if !self.value_eq(expectation, &value)? {
245                            // If they're not equal, print a diff of the debug format
246                            let (expectation_formatted, value_formatted) =
247                                match (expectation, &value) {
248                                    (
249                                        Value::Custom { val: ex_val, .. },
250                                        Value::Custom { val: v_val, .. },
251                                    ) => {
252                                        // We have to serialize both custom values before handing them to the plugin
253                                        let expectation_serialized =
254                                            PluginCustomValue::serialize_from_custom_value(
255                                                ex_val.as_ref(),
256                                                expectation.span(),
257                                            )?
258                                            .with_source(self.source.clone());
259
260                                        let value_serialized =
261                                            PluginCustomValue::serialize_from_custom_value(
262                                                v_val.as_ref(),
263                                                expectation.span(),
264                                            )?
265                                            .with_source(self.source.clone());
266
267                                        let persistent =
268                                            self.source.persistent(None)?.get_plugin(None)?;
269                                        let expectation_base = persistent
270                                            .custom_value_to_base_value(
271                                                expectation_serialized
272                                                    .into_spanned(expectation.span()),
273                                            )?;
274                                        let value_base = persistent.custom_value_to_base_value(
275                                            value_serialized.into_spanned(value.span()),
276                                        )?;
277
278                                        (
279                                            format!("{expectation_base:#?}"),
280                                            format!("{value_base:#?}"),
281                                        )
282                                    }
283                                    _ => (format!("{expectation:#?}"), format!("{value:#?}")),
284                                };
285
286                            let diff = diff_by_line(&expectation_formatted, &value_formatted);
287                            failed_header();
288                            eprintln!("{} {}", bold.paint("Result:"), diff);
289                        }
290                    }
291                    Err(err) => {
292                        // Report the error
293                        failed_header();
294                        report_shell_error(&self.engine_state, &err);
295                    }
296                }
297            }
298        }
299
300        if !failed {
301            Ok(())
302        } else {
303            Err(ShellError::GenericError {
304                error: "Some examples failed. See the error output for details".into(),
305                msg: "".into(),
306                span: None,
307                help: None,
308                inner: vec![],
309            })
310        }
311    }
312
313    /// Test examples from a command.
314    ///
315    /// # Example
316    ///
317    /// ```rust,no_run
318    /// # use nu_plugin_test_support::PluginTest;
319    /// # use nu_protocol::ShellError;
320    /// # use nu_plugin::*;
321    /// # fn test(MyPlugin: impl Plugin + Send + 'static, MyCommand: impl PluginCommand) -> Result<(), ShellError> {
322    /// PluginTest::new("my_plugin", MyPlugin.into())?
323    ///     .test_command_examples(&MyCommand)
324    /// # }
325    /// ```
326    pub fn test_command_examples(
327        &mut self,
328        command: &impl PluginCommand,
329    ) -> Result<(), ShellError> {
330        self.test_examples(&command.examples())
331    }
332
333    /// This implements custom value comparison with `plugin.custom_value_partial_cmp()` to behave
334    /// as similarly as possible to comparison in the engine.
335    ///
336    /// NOTE: Try to keep these reflecting the same comparison as `Value::partial_cmp` does under
337    /// normal circumstances. Otherwise people will be very confused.
338    fn value_eq(&self, a: &Value, b: &Value) -> Result<bool, ShellError> {
339        match (a, b) {
340            (Value::Custom { val, .. }, _) => {
341                // We have to serialize both custom values before handing them to the plugin
342                let serialized =
343                    PluginCustomValue::serialize_from_custom_value(val.as_ref(), a.span())?
344                        .with_source(self.source.clone());
345                let mut b_serialized = b.clone();
346                PluginCustomValue::serialize_custom_values_in(&mut b_serialized)?;
347                PluginCustomValueWithSource::add_source_in(&mut b_serialized, &self.source)?;
348                // Now get the plugin reference and execute the comparison
349                let persistent = self.source.persistent(None)?.get_plugin(None)?;
350                let ordering = persistent.custom_value_partial_cmp(serialized, b_serialized)?;
351                Ok(matches!(
352                    ordering.map(Ordering::from),
353                    Some(Ordering::Equal)
354                ))
355            }
356            // All container types need to be here except Closure.
357            (Value::List { vals: a_vals, .. }, Value::List { vals: b_vals, .. }) => {
358                // Must be the same length, with all elements equivalent
359                Ok(a_vals.len() == b_vals.len() && {
360                    for (a_el, b_el) in a_vals.iter().zip(b_vals) {
361                        if !self.value_eq(a_el, b_el)? {
362                            return Ok(false);
363                        }
364                    }
365                    true
366                })
367            }
368            (Value::Record { val: a_rec, .. }, Value::Record { val: b_rec, .. }) => {
369                // Must be the same length
370                if a_rec.len() != b_rec.len() {
371                    return Ok(false);
372                }
373
374                // reorder cols and vals to make more logically compare.
375                // more general, if two record have same col and values,
376                // the order of cols shouldn't affect the equal property.
377                let mut a_rec = a_rec.clone().into_owned();
378                let mut b_rec = b_rec.clone().into_owned();
379                a_rec.sort_cols();
380                b_rec.sort_cols();
381
382                // Check columns first
383                for (a, b) in a_rec.columns().zip(b_rec.columns()) {
384                    if a != b {
385                        return Ok(false);
386                    }
387                }
388                // Then check the values
389                for (a, b) in a_rec.values().zip(b_rec.values()) {
390                    if !self.value_eq(a, b)? {
391                        return Ok(false);
392                    }
393                }
394                // All equal, and same length
395                Ok(true)
396            }
397            // Fall back to regular eq.
398            _ => Ok(a == b),
399        }
400    }
401
402    /// This implements custom value comparison with `plugin.custom_value_to_base_value()` to behave
403    /// as similarly as possible to comparison in the engine.
404    pub fn custom_value_to_base_value(
405        &self,
406        val: &dyn CustomValue,
407        span: Span,
408    ) -> Result<Value, ShellError> {
409        let serialized = PluginCustomValue::serialize_from_custom_value(val, span)?
410            .with_source(self.source.clone());
411        let persistent = self.source.persistent(None)?.get_plugin(None)?;
412        persistent.custom_value_to_base_value(serialized.into_spanned(span))
413    }
414}