Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions book/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,63 @@ 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
# Exclude all in-built commands
| where ($it.type == "custom")
# Include all commands starting with "test_"
| where ($it.name | str starts-with "test_")
# Exclude commands marked as "ignored" in the description
| where not ($it.description | str starts-with "ignore")
# Get the name of the test command
| get name
# Prefix each test command with a command to print the test name
| each { |test| [$"print 'Running test: ($test)'", $test] } | flatten
# Concatenate into a command list
| str join "; "
)

nu --commands $"source ($env.CURRENT_FILE); ($tests)"
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_fib_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