stdlib: refactor into a multi-module library (#8815)

This commit is contained in:
Antoine Stevan
2023-04-09 19:00:20 +02:00
committed by GitHub
parent 637283ffad
commit 4a955d7e76
17 changed files with 774 additions and 746 deletions

153
crates/nu-std/tests/run.nu Normal file
View File

@ -0,0 +1,153 @@
use std *
# show a test record in a pretty way
#
# `$in` must be a `record<file: string, module: string, name: string, pass: bool>`.
#
# the output would be like
# - "<indentation> x <module> <test>" all in red if failed
# - "<indentation> s <module> <test>" all in yellow if skipped
# - "<indentation> <module> <test>" all in green if passed
def show-pretty-test [indent: int = 4] {
let test = $in
[
(" " * $indent)
(match $test.result {
"pass" => { ansi green },
"skip" => { ansi yellow },
_ => { ansi red }
})
(match $test.result {
"pass" => " ",
"skip" => "s",
_ => { char failed }
})
" "
$"($test.module) ($test.name)"
(ansi reset)
] | str join
}
def throw-error [error: record] {
error make {
msg: $"(ansi red)($error.msg)(ansi reset)"
label: {
text: ($error.label)
start: $error.span.start
end: $error.span.end
}
}
}
# Test executor
#
# It executes exported "test_*" commands in "test_*" modules
def main [
--path: path, # Path to look for tests. Default: directory of this file.
--module: string, # Module to run tests. Default: all test modules found.
--command: string, # Test command to run. Default: all test command found in the files.
--list, # list the selected tests without running them.
] {
let module_search_pattern = ('**' | path join ({
stem: ($module | default "test_*")
extension: nu
} | path join))
if not ($path | is-empty) {
if not ($path | path exists) {
throw-error {
msg: "directory_not_found"
label: "no such directory"
span: (metadata $path | get span)
}
}
}
let path = ($path | default $env.FILE_PWD)
if not ($module | is-empty) {
try { ls ($path | path join $module_search_pattern) | null } catch {
throw-error {
msg: "module_not_found"
label: $"no such module in ($path)"
span: (metadata $module | get span)
}
}
}
let tests = (
ls ($path | path join $module_search_pattern)
| each {|row| {file: $row.name name: ($row.name | path parse | get stem)}}
| upsert test {|module|
nu -c $'use ($module.file) *; $nu.scope.commands | select name module_name | to nuon'
| from nuon
| where module_name == $module.name
| where ($it.name | str starts-with "test_")
| get name
}
| flatten
| rename file module name
)
let tests_to_run = (if not ($command | is-empty) {
$tests | where name == $command
} else if not ($module | is-empty) {
$tests | where module == $module
} else {
$tests
})
if $list {
return ($tests_to_run | select module name file)
}
if ($tests_to_run | is-empty) {
error make --unspanned {msg: "no test to run"}
}
let tests = (
$tests_to_run
| group-by module
| transpose name tests
| each {|module|
log info $"Running tests in ($module.name)"
$module.tests | each {|test|
log debug $"Running test ($test.name)"
nu -c $'
use ($test.file) ($test.name)
try {
($test.name)
} catch { |err|
if $err.msg == "ASSERT:SKIP" {
exit 2
} else {
$err | get raw
}
}
'
let result = match $env.LAST_EXIT_CODE {
0 => "pass",
2 => "skip",
_ => "fail",
}
if $result == "skip" {
log warning $"Test case ($test.name) is skipped"
}
$test | merge ({result: $result})
}
}
| flatten
)
if not ($tests | where result == "fail" | is-empty) {
let text = ([
$"(ansi purple)some tests did not pass (char lparen)see complete errors above(char rparen):(ansi reset)"
""
($tests | each {|test| ($test | show-pretty-test 4)} | str join "\n")
""
] | str join "\n")
error make --unspanned { msg: $text }
}
}

View File

@ -0,0 +1,62 @@
use std *
export def test_assert [] {
assert true
assert (1 + 2 == 3)
assert error { assert false }
assert error { assert (1 + 2 == 4) }
}
export def test_assert_equal [] {
assert equal (1 + 2) 3
assert equal (0.1 + 0.2 | into string | into decimal) 0.3 # 0.30000000000000004 == 0.3
assert error { assert equal 1 "foo" }
assert error { assert equal (1 + 2) 4 }
}
export def test_assert_not_equal [] {
assert not equal (1 + 2) 4
assert not equal 1 "foo"
assert not equal (1 + 2) "3"
assert error { assert not equal 1 1 }
}
export def test_assert_error [] {
let failing_code = {|| missing_code_to_run}
assert error $failing_code
let good_code = {|| }
let assert_error_raised = (try { do assert $good_code; false } catch { true })
assert $assert_error_raised "The assert error should raise an error if there is no error in the executed code."
}
export def test_assert_less [] {
assert less 1 2
assert error { assert less 1 1 }
}
export def test_assert_less_or_equal [] {
assert less or equal 1 2
assert less or equal 1 1
assert error { assert less or equal 1 0 }
}
export def test_assert_greater [] {
assert greater 2 1
assert error { assert greater 2 2 }
}
export def test_assert_greater_or_equal [] {
assert greater or equal 1 1
assert greater or equal 2 1
assert error { assert greater or equal 0 1 }
}
export def test_assert_length [] {
assert length [0, 0, 0] 3
assert error { assert length [0, 0] 3 }
}
export def test_assert_skip [] {
assert skip # This test case is skipped on purpose
}

View File

@ -0,0 +1,74 @@
use std "assert length"
use std "assert equal"
def clean [path: path] {
cd $path
cd ..
rm -r $path
}
export def test_dirs_command [] {
# need some directories to play with
let base_path = ($nu.temp-path | path join $"test_dirs_(random uuid)")
let path_a = ($base_path | path join "a")
let path_b = ($base_path | path join "b")
try {
mkdir $base_path $path_a $path_b
cd $base_path
use std "dirs next"
use std "dirs prev"
use std "dirs add"
use std "dirs drop"
use std "dirs show"
assert length $env.DIRS_LIST 1 "list is just pwd after initialization"
assert equal $base_path $env.DIRS_LIST.0 "list is just pwd after initialization"
dirs next
assert equal $base_path $env.DIRS_LIST.0 "next wraps at end of list"
dirs prev
assert equal $base_path $env.DIRS_LIST.0 "prev wraps at top of list"
dirs add $path_b $path_a
assert equal $path_b $env.PWD "add changes PWD to first added dir"
assert length $env.DIRS_LIST 3 "add in fact adds to list"
assert equal $path_a $env.DIRS_LIST.2 "add in fact adds to list"
dirs next 2
assert equal $base_path $env.PWD "next wraps at end of list"
dirs prev 1
assert equal $path_a $env.PWD "prev wraps at start of list"
dirs drop
assert length $env.DIRS_LIST 2 "drop removes from list"
assert equal $base_path $env.PWD "drop changes PWD to next in list (after dropped element)"
assert equal (dirs show) [[active path]; [true $base_path] [false $path_b]] "show table contains expected information"
} catch { |error|
clean $base_path
let error = (
$error
| get debug
| str replace "{" "("
| str replace "}" ")"
| parse 'GenericError("{msg}", "{text}", Some(Span ( start: {start}, end: {end} )), {rest})'
| reject rest
| get 0
)
error make {
msg: $error.msg
label: {
text: $error.text
start: ($error.start | into int)
end: ($error.end | into int)
}
}
}
try { clean $base_path }
}

View File

@ -0,0 +1,39 @@
use std *
def run [system_level, message_level] {
cd $env.FILE_PWD
do {
nu -c $'use std; NU_LOG_LEVEL=($system_level) std log ($message_level) "test message"'
} | complete | get -i stderr
}
def "assert no message" [system_level, message_level] {
let output = (run $system_level $message_level)
assert equal "" $output
}
def "assert message" [system_level, message_level, message_level_str] {
let output = (run $system_level $message_level)
assert str contains $output $message_level_str
assert str contains $output "test message"
}
export def test_critical [] {
assert no message 99 critical
assert message CRITICAL critical CRT
}
export def test_error [] {
assert no message CRITICAL error
assert message ERROR error ERR
}
export def test_warning [] {
assert no message ERROR warning
assert message WARNING warning WRN
}
export def test_info [] {
assert no message WARNING info
assert message INFO info "INF" #INF has to be quoted, otherwise it is the `inf` float
}
export def test_debug [] {
assert no message INFO debug
assert message DEBUG debug DBG
}

View File

@ -0,0 +1,24 @@
use std
export def test_path_add [] {
use std "assert equal"
with-env [PATH []] {
assert equal $env.PATH []
std path add "/foo/"
assert equal $env.PATH ["/foo/"]
std path add "/bar/" "/baz/"
assert equal $env.PATH ["/bar/", "/baz/", "/foo/"]
let-env PATH = []
std path add "foo"
std path add "bar" "baz" --append
assert equal $env.PATH ["foo", "bar", "baz"]
assert equal (std path add "fooooo" --ret) ["fooooo", "foo", "bar", "baz"]
assert equal $env.PATH ["fooooo", "foo", "bar", "baz"]
}
}

View File

@ -0,0 +1,30 @@
use std "xaccess"
use std "xupdate"
use std "xinsert"
use std "assert equal"
export def test_xml_xaccess [] {
let sample_xml = ('<a><b><c a="b"></c></b><c></c><d><e>z</e><e>x</e></d></a>' | from xml)
assert equal ($sample_xml | xaccess [a]) [$sample_xml]
assert equal ($sample_xml | xaccess [*]) [$sample_xml]
assert equal ($sample_xml | xaccess [* d e]) [[tag, attributes, content]; [e, {}, [[tag, attributes, content]; [null, null, z]]], [e, {}, [[tag, attributes, content]; [null, null, x]]]]
assert equal ($sample_xml | xaccess [* d e 1]) [[tag, attributes, content]; [e, {}, [[tag, attributes, content]; [null, null, x]]]]
assert equal ($sample_xml | xaccess [* * * {|e| $e.attributes != {}}]) [[tag, attributes, content]; [c, {a: b}, []]]
}
export def test_xml_xupdate [] {
let sample_xml = ('<a><b><c a="b"></c></b><c></c><d><e>z</e><e>x</e></d></a>' | from xml)
assert equal ($sample_xml | xupdate [*] {|x| $x | update attributes {i: j}}) ('<a i="j"><b><c a="b"></c></b><c></c><d><e>z</e><e>x</e></d></a>' | from xml)
assert equal ($sample_xml | xupdate [* d e *] {|x| $x | update content 'nushell'}) ('<a><b><c a="b"></c></b><c></c><d><e>nushell</e><e>nushell</e></d></a>' | from xml)
assert equal ($sample_xml | xupdate [* * * {|e| $e.attributes != {}}] {|x| $x | update content ['xml']}) {tag: a, attributes: {}, content: [[tag, attributes, content]; [b, {}, [[tag, attributes, content]; [c, {a: b}, [xml]]]], [c, {}, []], [d, {}, [[tag, attributes, content]; [e, {}, [[tag, attributes, content]; [null, null, z]]], [e, {}, [[tag, attributes, content]; [null, null, x]]]]]]}
}
export def test_xml_xinsert [] {
let sample_xml = ('<a><b><c a="b"></c></b><c></c><d><e>z</e><e>x</e></d></a>' | from xml)
assert equal ($sample_xml | xinsert [a] {tag: b attributes:{} content: []}) ('<a><b><c a="b"></c></b><c></c><d><e>z</e><e>x</e></d><b></b></a>' | from xml)
assert equal ($sample_xml | xinsert [a d *] {tag: null attributes: null content: 'n'} | to xml) '<a><b><c a="b"></c></b><c></c><d><e>zn</e><e>xn</e></d></a>'
assert equal ($sample_xml | xinsert [a *] {tag: null attributes: null content: 'n'}) ('<a><b><c a="b"></c>n</b><c>n</c><d><e>z</e><e>x</e>n</d></a>' | from xml)
}