Skip to content

Commit ab17ded

Browse files
authored
Example showing discovery and running of test commands (#1594)
* Example showing discovery and running of test commands * Updated to conform better with style guide, nupm testing, as well as suggestions from @fdncred
1 parent 0144e32 commit ab17ded

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

book/testing.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,4 +165,57 @@ for t in [
165165
```
166166
and be invoked as `nu tests.nu`
167167

168+
### Basic Test Framework
169+
170+
It is also possible to define tests in Nushell as functions with descriptive names and discover
171+
them dynamically without requiring a [Nupm] package. The following uses `scope commands` and a
172+
second instance of Nushell to run the generated list of tests.
173+
174+
```nushell
175+
use std assert
176+
177+
source fib.nu
178+
179+
def main [] {
180+
print "Running tests..."
181+
182+
let test_commands = (
183+
scope commands
184+
| where ($it.type == "custom")
185+
and ($it.name | str starts-with "test ")
186+
and not ($it.description | str starts-with "ignore")
187+
| get name
188+
| each { |test| [$"print 'Running test: ($test)'", $test] } | flatten
189+
| str join "; "
190+
)
191+
192+
nu --commands $"source ($env.CURRENT_FILE); ($test_commands)"
193+
print "Tests completed successfully"
194+
}
195+
196+
def "test fib" [] {
197+
for t in [
198+
[input, expected];
199+
[0, 0],
200+
[1, 1],
201+
[2, 1],
202+
[3, 2],
203+
[4, 3],
204+
[5, 5],
205+
[6, 8],
206+
[7, 13]
207+
] {
208+
assert equal (fib $t.input) $t.expected
209+
}
210+
}
211+
212+
# ignore
213+
def "test show-ignored-test" [] {
214+
print "This test will not be executed"
215+
}
216+
```
217+
218+
This is a simple example but could be extended to include many of the things you might expect from
219+
a testing framework, including setup and tear down functions and test discovery across files.
220+
168221
[Nupm]: https://github.com/nushell/nupm

0 commit comments

Comments
 (0)