@@ -165,4 +165,63 @@ for t in [
165165```
166166and 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+ # Exclude all in-built commands
185+ | where ($it.type == "custom")
186+ # Include all commands starting with "test_"
187+ | where ($it.name | str starts-with "test_")
188+ # Exclude commands marked as "ignored" in the description
189+ | where not ($it.description | str starts-with "ignore")
190+ # Get the name of the test command
191+ | get name
192+ # Prefix each test command with a command to print the test name
193+ | each { |test| [$"print 'Running test: ($test)'", $test] } | flatten
194+ # Concatenate into a command list
195+ | str join "; "
196+ )
197+
198+ nu --commands $"source ($env.CURRENT_FILE); ($tests)"
199+ print "Tests completed successfully"
200+ }
201+
202+ def test_fib [] {
203+ for t in [
204+ [input, expected];
205+ [0, 0],
206+ [1, 1],
207+ [2, 1],
208+ [3, 2],
209+ [4, 3],
210+ [5, 5],
211+ [6, 8],
212+ [7, 13]
213+ ] {
214+ assert equal (fib $t.input) $t.expected
215+ }
216+ }
217+
218+ # ignore
219+ def test_fib_ignored_test [] {
220+ print "This test will not be executed"
221+ }
222+ ```
223+
224+ This is a simple example but could be extended to include many of the things you might expect from
225+ a testing framework, including setup and tear down functions and test discovery across files.
226+
168227[ Nupm ] : https://github.com/nushell/nupm
0 commit comments