Add tests

This commit is contained in:
Florian Schroedl
2022-01-20 17:00:00 +01:00
parent d24e596ce3
commit 49ebf7329a
5 changed files with 59 additions and 3 deletions

View File

@@ -17,6 +17,8 @@ requires "fusion"
# requires "zero_functional"
# requires "cascade"
import distros
if detectOs(NixOS):
foreignDep "pkgconfig"
# Tasks
task tests, "Run all tests":
echo "Runnign all tests"
exec """testament --backendLogging:off --directory:"./tests/" p "utils/*.nim""""

27
src/utils/str.nim Normal file
View File

@@ -0,0 +1,27 @@
import std/strutils
import std/math
proc safeDelete*(str: string, slice: Slice[int]): string =
## Deletes the items `str[slice]`, ignoring elements out of range.
if slice.a > str.len - 1:
str
else:
let fromIndex = clamp(slice.a, 0..str.len)
let toIndex = clamp(slice.b, 0..str.len - 1)
var strDup = str
strDup.delete(fromIndex..toIndex)
strDup
func findAndDelete*(str: string, chars: set[char], start = 0, last = str.len - 1): string =
## Find the next instance of `chars` from `start`.
## When found delete characters until `last`.
let startChar = str.find(chars, start, last)
if startChar == -1:
str
else:
str.safeDelete(startChar..last)
func deleteAfterNewline*(str: string, start = 0): string =
## Delete string after next Newline from `start`.
findAndDelete(str, Newlines, start)

4
tests/config.nims Normal file
View File

@@ -0,0 +1,4 @@
switch("define", "nimUnittestOutputLevel:PRINT_FAILURES")
switch("warnings", false)
switch("hints", false)
switch("path", "$projectDir/../src")

1
tests/nim.cfg Normal file
View File

@@ -0,0 +1 @@
--path: "../src/"

22
tests/utils/test_str.nim Normal file
View File

@@ -0,0 +1,22 @@
import std/unittest
import utils/str
suite "utils/str":
test "safeDelete":
let t = "abc"
check(t.safeDelete(0..0) == "abc")
check(t.safeDelete(0..1) == "c")
check(t.safeDelete(1..1) == "ac")
check(t.safeDelete(2..2) == "ab")
# Out of bounds slicing
check(t.safeDelete(0..10) == "")
check(t.safeDelete(10..1) == t)
check(t.safeDelete(3..3) == t)
check(t.safeDelete(3..(-1)) == t)
test "findAndDelete":
let t = "foo\nbar"
check(t.deleteAfterNewline() == "foo")
check(t.deleteAfterNewline(start = 4) == t)