Skip to content

Commit

Permalink
Example showing discovery and running of test commands (#1594)
Browse files Browse the repository at this point in the history
* Example showing discovery and running of test commands

* Updated to conform better with style guide, nupm testing, as well as suggestions from @fdncred
  • Loading branch information
vyadh authored Oct 28, 2024
1 parent 0144e32 commit ab17ded
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions book/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,57 @@ for t in [
```
and be invoked as `nu tests.nu`

### Basic Test Framework

It is also possible to define tests in Nushell as functions with descriptive names and discover
them dynamically without requiring a [Nupm] package. The following uses `scope commands` and a
second instance of Nushell to run the generated list of tests.

```nushell
use std assert
source fib.nu
def main [] {
print "Running tests..."
let test_commands = (
scope commands
| where ($it.type == "custom")
and ($it.name | str starts-with "test ")
and not ($it.description | str starts-with "ignore")
| get name
| each { |test| [$"print 'Running test: ($test)'", $test] } | flatten
| str join "; "
)
nu --commands $"source ($env.CURRENT_FILE); ($test_commands)"
print "Tests completed successfully"
}
def "test fib" [] {
for t in [
[input, expected];
[0, 0],
[1, 1],
[2, 1],
[3, 2],
[4, 3],
[5, 5],
[6, 8],
[7, 13]
] {
assert equal (fib $t.input) $t.expected
}
}
# ignore
def "test show-ignored-test" [] {
print "This test will not be executed"
}
```

This is a simple example but could be extended to include many of the things you might expect from
a testing framework, including setup and tear down functions and test discovery across files.

[Nupm]: https://github.com/nushell/nupm

0 comments on commit ab17ded

Please sign in to comment.