use doAssert in tests (#16486)

This commit is contained in:
flywind 2020-12-28 07:13:21 -06:00 • committed by GitHub
commit 6d442a40a6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
78 changed files with 1056 additions and 1056 deletions

View file

@ -135,8 +135,8 @@ let
n = @["c", "b"] n = @["c", "b"]
q = @[("c", "2"), ("b", "1")] q = @[("c", "2"), ("b", "1")]
assert n.sortedByIt(it) == @["b", "c"], "fine" doAssert n.sortedByIt(it) == @["b", "c"], "fine"
assert q.sortedByIt(it[0]) == @[("b", "1"), ("c", "2")], "fails under arc" doAssert q.sortedByIt(it[0]) == @[("b", "1"), ("c", "2")], "fails under arc"
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------

View file

@ -62,7 +62,7 @@ proc main =
let mem = getOccupiedMem() let mem = getOccupiedMem()
main() main()
assert msgCount == swarmSize * messagesToSend doAssert msgCount == swarmSize * messagesToSend
echo "result: ", msgCount echo "result: ", msgCount
GC_fullCollect() GC_fullCollect()
echo "memory: ", formatSize(getOccupiedMem() - mem) echo "memory: ", formatSize(getOccupiedMem() - mem)

View file

@ -84,5 +84,5 @@ proc main(): Future[void] =
for i in 0..9: for i in 0..9:
waitFor main() waitFor main()
GC_fullCollect() GC_fullCollect()
assert getOccupiedMem() < 1024 doAssert getOccupiedMem() < 1024
echo "success" echo "success"

View file

@ -93,9 +93,9 @@ block tgenericassign:
var ret: seq[tuple[name: string, a: TAny]] = @[] var ret: seq[tuple[name: string, a: TAny]] = @[]
for i in 0 .. 8000: for i in 0 .. 8000:
var tup = ($name, newAny(nil, nil)) var tup = ($name, newAny(nil, nil))
assert(tup[0] == "example") doAssert(tup[0] == "example")
ret.add(tup) ret.add(tup)
assert(ret[ret.len()-1][0] == "example") doAssert(ret[ret.len()-1][0] == "example")

View file

@ -5,9 +5,9 @@ proc doubleSleep(hardSleep: int) {.async.} =
sleep(hardSleep) sleep(hardSleep)
template assertTime(target, timeTook: float): untyped {.dirty.} = template assertTime(target, timeTook: float): untyped {.dirty.} =
assert(timeTook*1000 > target - 1000, "Took too short, should've taken " & doAssert(timeTook*1000 > target - 1000, "Took too short, should've taken " &
$target & "ms, but took " & $(timeTook*1000) & "ms") $target & "ms, but took " & $(timeTook*1000) & "ms")
assert(timeTook*1000 < target + 1000, "Took too long, should've taken " & doAssert(timeTook*1000 < target + 1000, "Took too long, should've taken " &
$target & "ms, but took " & $(timeTook*1000) & "ms") $target & "ms, but took " & $(timeTook*1000) & "ms")
var var

View file

@ -7,7 +7,7 @@ discard """
''' '''
""" """
assert compileOption("threads"), "this test will not do anything useful without --threads:on" doAssert compileOption("threads"), "this test will not do anything useful without --threads:on"
import asyncdispatch import asyncdispatch

View file

@ -4,7 +4,7 @@ discard """
file: "asyncmacro.nim" file: "asyncmacro.nim"
""" """
assert compileOption("threads"), "this test will not do anything useful without --threads:on" doAssert compileOption("threads"), "this test will not do anything useful without --threads:on"
import asyncdispatch import asyncdispatch

View file

@ -52,5 +52,5 @@ while true:
poll() poll()
if clientCount == swarmSize: break if clientCount == swarmSize: break
assert msgCount == swarmSize * messagesToSend doAssert msgCount == swarmSize * messagesToSend
doAssert msgCount == 2000 doAssert msgCount == 2000

View file

@ -21,12 +21,12 @@ proc runServer() {.async.} =
var lastN = 0 var lastN = 0
while true: while true:
let frame = await client.recv(FrameSize) let frame = await client.recv(FrameSize)
assert frame.len == FrameSize doAssert frame.len == FrameSize
let n = frame[0..<6].parseInt() let n = frame[0..<6].parseInt()
echo "RCVD #", n, ": ", frame[0..80], "..." echo "RCVD #", n, ": ", frame[0..80], "..."
if n != lastN + 1: if n != lastN + 1:
echo &"******** ERROR: Server received #{n}, but last was #{lastN}!" echo &"******** ERROR: Server received #{n}, but last was #{lastN}!"
assert n == lastN + 1 doAssert n == lastN + 1
lastN = n lastN = n
await sleepAsync 100 await sleepAsync 100

View file

@ -84,7 +84,7 @@ while true:
if recvCount == swarmSize * messagesToSend: if recvCount == swarmSize * messagesToSend:
break break
assert msgCount == swarmSize * messagesToSend doAssert msgCount == swarmSize * messagesToSend
assert sendports == recvports doAssert sendports == recvports
echo msgCount echo msgCount

View file

@ -69,5 +69,5 @@ when defined(ssl):
elif defined(linux) and int.sizeof == 8: elif defined(linux) and int.sizeof == 8:
# currently: msgCount == 10 # currently: msgCount == 10
flakyAssert cond() flakyAssert cond()
assert msgCount > 0 doAssert msgCount > 0
else: assert cond(), $msgCount else: doAssert cond(), $msgCount

View file

@ -7,7 +7,7 @@ type Foo = ref object
i: int i: int
proc next(foo: Foo): Option[Foo] = proc next(foo: Foo): Option[Foo] =
try: assert(foo.i == 0) try: doAssert(foo.i == 0)
except: return # 2º: none except: return # 2º: none
return some(foo) # 1º: some return some(foo) # 1º: some
@ -17,6 +17,6 @@ proc test =
while isSome(opt) and foo.i < 10: while isSome(opt) and foo.i < 10:
inc(foo.i) inc(foo.i)
opt = next(foo) # 2º None opt = next(foo) # 2º None
assert foo.i == 1, $foo.i doAssert foo.i == 1, $foo.i
test() test()

View file

@ -6,7 +6,7 @@ iterator myitems*[T](a: var seq[T]): var T {.inline.} =
while i < L: while i < L:
yield a[i] yield a[i]
inc(i) inc(i)
assert(len(a) == L, "the length of the seq changed while iterating over it") doAssert(len(a) == L, "the length of the seq changed while iterating over it")
# Works fine # Works fine
var xs = @[1,2,3] var xs = @[1,2,3]

View file

@ -24,7 +24,7 @@ block tseq2:
# multiply two int sequences: # multiply two int sequences:
for i in 0..len(a)-1: result[i] = a[i] * b[i] for i in 0..len(a)-1: result[i] = a[i] * b[i]
assert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9]) doAssert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9])

View file

@ -50,20 +50,20 @@ block thashes:
var t = initTable[int,int]() var t = initTable[int,int]()
t[0] = 42 t[0] = 42
t[1] = t[0] + 1 t[1] = t[0] + 1
assert(t[0] == 42) doAssert(t[0] == 42)
assert(t[1] == 43) doAssert(t[1] == 43)
let t2 = {1: 1, 2: 2}.toTable let t2 = {1: 1, 2: 2}.toTable
assert(t2[2] == 2) doAssert(t2[2] == 2)
# Test with char # Test with char
block: block:
var t = initTable[char,int]() var t = initTable[char,int]()
t['0'] = 42 t['0'] = 42
t['1'] = t['0'] + 1 t['1'] = t['0'] + 1
assert(t['0'] == 42) doAssert(t['0'] == 42)
assert(t['1'] == 43) doAssert(t['1'] == 43)
let t2 = {'1': 1, '2': 2}.toTable let t2 = {'1': 1, '2': 2}.toTable
assert(t2['2'] == 2) doAssert(t2['2'] == 2)
# Test with enum # Test with enum
block: block:
@ -72,10 +72,10 @@ block thashes:
var t = initTable[E,int]() var t = initTable[E,int]()
t[eA] = 42 t[eA] = 42
t[eB] = t[eA] + 1 t[eB] = t[eA] + 1
assert(t[eA] == 42) doAssert(t[eA] == 42)
assert(t[eB] == 43) doAssert(t[eB] == 43)
let t2 = {eA: 1, eB: 2}.toTable let t2 = {eA: 1, eB: 2}.toTable
assert(t2[eB] == 2) doAssert(t2[eB] == 2)
# Test with range # Test with range
block: block:
@ -84,10 +84,10 @@ block thashes:
var t = initTable[R,int]() # causes warning, why? var t = initTable[R,int]() # causes warning, why?
t[1] = 42 # causes warning, why? t[1] = 42 # causes warning, why?
t[2] = t[1] + 1 t[2] = t[1] + 1
assert(t[1] == 42) doAssert(t[1] == 42)
assert(t[2] == 43) doAssert(t[2] == 43)
let t2 = {1.R: 1, 2.R: 2}.toTable let t2 = {1.R: 1, 2.R: 2}.toTable
assert(t2[2.R] == 2) doAssert(t2[2.R] == 2)
# Test which combines the generics for tuples + ordinals # Test which combines the generics for tuples + ordinals
block: block:
@ -96,10 +96,10 @@ block thashes:
var t = initTable[(string, E, int, char), int]() var t = initTable[(string, E, int, char), int]()
t[("a", eA, 0, '0')] = 42 t[("a", eA, 0, '0')] = 42
t[("b", eB, 1, '1')] = t[("a", eA, 0, '0')] + 1 t[("b", eB, 1, '1')] = t[("a", eA, 0, '0')] + 1
assert(t[("a", eA, 0, '0')] == 42) doAssert(t[("a", eA, 0, '0')] == 42)
assert(t[("b", eB, 1, '1')] == 43) doAssert(t[("b", eB, 1, '1')] == 43)
let t2 = {("a", eA, 0, '0'): 1, ("b", eB, 1, '1'): 2}.toTable let t2 = {("a", eA, 0, '0'): 1, ("b", eB, 1, '1'): 2}.toTable
assert(t2[("b", eB, 1, '1')] == 2) doAssert(t2[("b", eB, 1, '1')] == 2)
# Test to check if overloading is possible # Test to check if overloading is possible
# Unfortunately, this does not seem to work for int # Unfortunately, this does not seem to work for int
@ -165,9 +165,9 @@ block tableconstr:
ignoreExpr({2: 3, "key": "value"}) ignoreExpr({2: 3, "key": "value"})
# NEW: # NEW:
assert 56 in 50..100 doAssert 56 in 50..100
assert 56 in ..60 doAssert 56 in ..60
block ttables2: block ttables2:
@ -239,8 +239,8 @@ block tablesref:
t[(1,1)] = "11" t[(1,1)] = "11"
for x in 0..1: for x in 0..1:
for y in 0..1: for y in 0..1:
assert t[(x,y)] == $x & $y doAssert t[(x,y)] == $x & $y
assert t.sortedPairs == doAssert t.sortedPairs ==
@[((x: 0, y: 0), "00"), ((x: 0, y: 1), "01"), ((x: 1, y: 0), "10"), ((x: 1, y: 1), "11")] @[((x: 0, y: 0), "00"), ((x: 0, y: 1), "01"), ((x: 1, y: 0), "10"), ((x: 1, y: 1), "11")]
block tableTest2: block tableTest2:
@ -253,31 +253,31 @@ block tablesref:
t["012"] = 67.9 t["012"] = 67.9
t["123"] = 1.5 # test overwriting t["123"] = 1.5 # test overwriting
assert t["123"] == 1.5 doAssert t["123"] == 1.5
try: try:
echo t["111"] # deleted echo t["111"] # deleted
except KeyError: except KeyError:
discard discard
assert(not hasKey(t, "111")) doAssert(not hasKey(t, "111"))
assert "111" notin t doAssert "111" notin t
for key, val in items(data): t[key] = val.toFloat for key, val in items(data): t[key] = val.toFloat
for key, val in items(data): assert t[key] == val.toFloat for key, val in items(data): doAssert t[key] == val.toFloat
block orderedTableTest1: block orderedTableTest1:
var t = newOrderedTable[string, int](2) var t = newOrderedTable[string, int](2)
for key, val in items(data): t[key] = val for key, val in items(data): t[key] = val
for key, val in items(data): assert t[key] == val for key, val in items(data): doAssert t[key] == val
var i = 0 var i = 0
# `pairs` needs to yield in insertion order: # `pairs` needs to yield in insertion order:
for key, val in pairs(t): for key, val in pairs(t):
assert key == data[i][0] doAssert key == data[i][0]
assert val == data[i][1] doAssert val == data[i][1]
inc(i) inc(i)
for key, val in mpairs(t): val = 99 for key, val in mpairs(t): val = 99
for val in mvalues(t): assert val == 99 for val in mvalues(t): doAssert val == 99
block countTableTest1: block countTableTest1:
var s = data.toTable var s = data.toTable
@ -286,11 +286,11 @@ block tablesref:
for x in [t, r]: for x in [t, r]:
for k in s.keys: for k in s.keys:
x.inc(k) x.inc(k)
assert x[k] == 1 doAssert x[k] == 1
x.inc("90", 3) x.inc("90", 3)
x.inc("12", 2) x.inc("12", 2)
x.inc("34", 1) x.inc("34", 1)
assert t.largest()[0] == "90" doAssert t.largest()[0] == "90"
t.sort() t.sort()
r.sort(SortOrder.Ascending) r.sort(SortOrder.Ascending)
@ -301,9 +301,9 @@ block tablesref:
var i = 0 var i = 0
for (k, v) in ps: for (k, v) in ps:
case i case i
of 0: assert k == "90" and v == 4 of 0: doAssert k == "90" and v == 4
of 1: assert k == "12" and v == 3 of 1: doAssert k == "12" and v == 3
of 2: assert k == "34" and v == 2 of 2: doAssert k == "34" and v == 2
else: break else: break
inc i inc i
@ -327,17 +327,17 @@ block tablesref:
block nilTest: block nilTest:
var i, j: TableRef[int, int] = nil var i, j: TableRef[int, int] = nil
assert i == j doAssert i == j
j = newTable[int, int]() j = newTable[int, int]()
assert i != j doAssert i != j
assert j != i doAssert j != i
i = newTable[int, int]() i = newTable[int, int]()
assert i == j doAssert i == j
proc orderedTableSortTest() = proc orderedTableSortTest() =
var t = newOrderedTable[string, int](2) var t = newOrderedTable[string, int](2)
for key, val in items(data): t[key] = val for key, val in items(data): t[key] = val
for key, val in items(data): assert t[key] == val for key, val in items(data): doAssert t[key] == val
proc cmper(x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key) proc cmper(x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key)
t.sort(cmper) t.sort(cmper)
var i = 0 var i = 0
@ -369,25 +369,25 @@ block tablesref:
t["test"] = 1.2345 t["test"] = 1.2345
t["111"] = 1.000043 t["111"] = 1.000043
t["123"] = 1.23 t["123"] = 1.23
assert t.len() != 0 doAssert t.len() != 0
t.clear() t.clear()
assert t.len() == 0 doAssert t.len() == 0
block clearOrderedTableTest: block clearOrderedTableTest:
var t = newOrderedTable[string, int](2) var t = newOrderedTable[string, int](2)
for key, val in items(data): t[key] = val for key, val in items(data): t[key] = val
assert t.len() != 0 doAssert t.len() != 0
t.clear() t.clear()
assert t.len() == 0 doAssert t.len() == 0
block clearCountTableTest: block clearCountTableTest:
var t = newCountTable[string]() var t = newCountTable[string]()
t.inc("90", 3) t.inc("90", 3)
t.inc("12", 2) t.inc("12", 2)
t.inc("34", 1) t.inc("34", 1)
assert t.len() != 0 doAssert t.len() != 0
t.clear() t.clear()
assert t.len() == 0 doAssert t.len() == 0
orderedTableSortTest() orderedTableSortTest()
echo "3" echo "3"
@ -415,7 +415,7 @@ block: # https://github.com/nim-lang/Nim/issues/13496
doAssert sortedPairs(t) == @[(15, 1), (17, 3), (19, 2)] doAssert sortedPairs(t) == @[(15, 1), (17, 3), (19, 2)]
var s = newSeq[int]() var s = newSeq[int]()
for v in t.values: s.add(v) for v in t.values: s.add(v)
assert s.len == 3 doAssert s.len == 3
doAssert sortedItems(s) == @[1, 2, 3] doAssert sortedItems(s) == @[1, 2, 3]
when t is OrderedTable|OrderedTableRef: when t is OrderedTable|OrderedTableRef:
doAssert toSeq(t.keys) == @[15, 19, 17] doAssert toSeq(t.keys) == @[15, 19, 17]
@ -433,14 +433,14 @@ block: # https://github.com/nim-lang/Nim/issues/13496
block testNonPowerOf2: block testNonPowerOf2:
var a = initTable[int, int](7) var a = initTable[int, int](7)
a[1] = 10 a[1] = 10
assert a[1] == 10 doAssert a[1] == 10
var b = initTable[int, int](9) var b = initTable[int, int](9)
b[1] = 10 b[1] = 10
assert b[1] == 10 doAssert b[1] == 10
block emptyOrdered: block emptyOrdered:
var t1: OrderedTable[int, string] var t1: OrderedTable[int, string]
var t2: OrderedTable[int, string] var t2: OrderedTable[int, string]
assert t1 == t2 doAssert t1 == t2

View file

@ -48,8 +48,8 @@ block tableTest1:
t[(1,1)] = "11" t[(1,1)] = "11"
for x in 0..1: for x in 0..1:
for y in 0..1: for y in 0..1:
assert t[(x,y)] == $x & $y doAssert t[(x,y)] == $x & $y
assert t.sortedPairs == @[((x: 0, y: 0), "00"), ((x: 0, y: 1), "01"), ((x: 1, y: 0), "10"), ((x: 1, y: 1), "11")] doAssert t.sortedPairs == @[((x: 0, y: 0), "00"), ((x: 0, y: 1), "01"), ((x: 1, y: 0), "10"), ((x: 1, y: 1), "11")]
block tableTest2: block tableTest2:
var t = initTable[string, float]() var t = initTable[string, float]()
@ -61,74 +61,74 @@ block tableTest2:
t["012"] = 67.9 t["012"] = 67.9
t["123"] = 1.5 # test overwriting t["123"] = 1.5 # test overwriting
assert t["123"] == 1.5 doAssert t["123"] == 1.5
try: try:
echo t["111"] # deleted echo t["111"] # deleted
except KeyError: except KeyError:
discard discard
assert(not hasKey(t, "111")) doAssert(not hasKey(t, "111"))
assert "123" in t doAssert "123" in t
assert("111" notin t) doAssert("111" notin t)
for key, val in items(data): t[key] = val.toFloat for key, val in items(data): t[key] = val.toFloat
for key, val in items(data): assert t[key] == val.toFloat for key, val in items(data): doAssert t[key] == val.toFloat
assert(not t.hasKeyOrPut("456", 4.0)) # test absent key doAssert(not t.hasKeyOrPut("456", 4.0)) # test absent key
assert t.hasKeyOrPut("012", 3.0) # test present key doAssert t.hasKeyOrPut("012", 3.0) # test present key
var x = t.mgetOrPut("111", 1.5) # test absent key var x = t.mgetOrPut("111", 1.5) # test absent key
x = x * 2 x = x * 2
assert x == 3.0 doAssert x == 3.0
x = t.mgetOrPut("test", 1.5) # test present key x = t.mgetOrPut("test", 1.5) # test present key
x = x * 2 x = x * 2
assert x == 2 * 1.2345 doAssert x == 2 * 1.2345
block orderedTableTest1: block orderedTableTest1:
var t = initOrderedTable[string, int](2) var t = initOrderedTable[string, int](2)
for key, val in items(data): t[key] = val for key, val in items(data): t[key] = val
for key, val in items(data): assert t[key] == val for key, val in items(data): doAssert t[key] == val
var i = 0 var i = 0
# `pairs` needs to yield in insertion order: # `pairs` needs to yield in insertion order:
for key, val in pairs(t): for key, val in pairs(t):
assert key == data[i][0] doAssert key == data[i][0]
assert val == data[i][1] doAssert val == data[i][1]
inc(i) inc(i)
for key, val in mpairs(t): val = 99 for key, val in mpairs(t): val = 99
for val in mvalues(t): assert val == 99 for val in mvalues(t): doAssert val == 99
block orderedTableTest2: block orderedTableTest2:
var var
s = initOrderedTable[string, int]() s = initOrderedTable[string, int]()
t = initOrderedTable[string, int]() t = initOrderedTable[string, int]()
assert s == t doAssert s == t
for key, val in items(data): t[key] = val for key, val in items(data): t[key] = val
assert s != t doAssert s != t
for key, val in items(sorteddata): s[key] = val for key, val in items(sorteddata): s[key] = val
assert s != t doAssert s != t
t.clear() t.clear()
assert s != t doAssert s != t
for key, val in items(sorteddata): t[key] = val for key, val in items(sorteddata): t[key] = val
assert s == t doAssert s == t
block countTableTest1: block countTableTest1:
var s = data.toTable var s = data.toTable
var t = initCountTable[string]() var t = initCountTable[string]()
for k in s.keys: t.inc(k) for k in s.keys: t.inc(k)
for k in t.keys: assert t[k] == 1 for k in t.keys: doAssert t[k] == 1
t.inc("90", 3) t.inc("90", 3)
t.inc("12", 2) t.inc("12", 2)
t.inc("34", 1) t.inc("34", 1)
assert t.largest()[0] == "90" doAssert t.largest()[0] == "90"
t.sort() t.sort()
var i = 0 var i = 0
for k, v in t.pairs: for k, v in t.pairs:
case i case i
of 0: assert k == "90" and v == 4 of 0: doAssert k == "90" and v == 4
of 1: assert k == "12" and v == 3 of 1: doAssert k == "12" and v == 3
of 2: assert k == "34" and v == 2 of 2: doAssert k == "34" and v == 2
else: break else: break
inc i inc i
@ -136,19 +136,19 @@ block countTableTest2:
var var
s = initCountTable[int]() s = initCountTable[int]()
t = initCountTable[int]() t = initCountTable[int]()
assert s == t doAssert s == t
s.inc(1) s.inc(1)
assert s != t doAssert s != t
t.inc(2) t.inc(2)
assert s != t doAssert s != t
t.inc(1) t.inc(1)
assert s != t doAssert s != t
s.inc(2) s.inc(2)
assert s == t doAssert s == t
s.inc(1) s.inc(1)
assert s != t doAssert s != t
t.inc(1) t.inc(1)
assert s == t doAssert s == t
block mpairsTableTest1: block mpairsTableTest1:
var t = initTable[string, int]() var t = initTable[string, int]()
@ -162,9 +162,9 @@ block mpairsTableTest1:
for k, v in t.pairs: for k, v in t.pairs:
if k == "a" or k == "c": if k == "a" or k == "c":
assert v == 9 doAssert v == 9
else: else:
assert v != 1 and v != 3 doAssert v != 1 and v != 3
block SyntaxTest: block SyntaxTest:
var x = toTable[int, string]({:}) var x = toTable[int, string]({:})
@ -174,10 +174,10 @@ block zeroHashKeysTest:
let initialLen = t.len let initialLen = t.len
var testTable = t var testTable = t
testTable[nullHashKey] = value testTable[nullHashKey] = value
assert testTable[nullHashKey] == value doAssert testTable[nullHashKey] == value
assert testTable.len == initialLen + 1 doAssert testTable.len == initialLen + 1
testTable.del(nullHashKey) testTable.del(nullHashKey)
assert testTable.len == initialLen doAssert testTable.len == initialLen
# with empty table # with empty table
doZeroHashValueTest(toTable[int,int]({:}), 0, 42) doZeroHashValueTest(toTable[int,int]({:}), 0, 42)
@ -194,46 +194,46 @@ block zeroHashKeysTest:
block clearTableTest: block clearTableTest:
var t = data.toTable var t = data.toTable
assert t.len() != 0 doAssert t.len() != 0
t.clear() t.clear()
assert t.len() == 0 doAssert t.len() == 0
block clearOrderedTableTest: block clearOrderedTableTest:
var t = data.toOrderedTable var t = data.toOrderedTable
assert t.len() != 0 doAssert t.len() != 0
t.clear() t.clear()
assert t.len() == 0 doAssert t.len() == 0
block clearCountTableTest: block clearCountTableTest:
var t = initCountTable[string]() var t = initCountTable[string]()
t.inc("90", 3) t.inc("90", 3)
t.inc("12", 2) t.inc("12", 2)
t.inc("34", 1) t.inc("34", 1)
assert t.len() != 0 doAssert t.len() != 0
t.clear() t.clear()
assert t.len() == 0 doAssert t.len() == 0
block withKeyTest: block withKeyTest:
var t: SharedTable[int, int] var t: SharedTable[int, int]
t.init() t.init()
t.withKey(1) do (k: int, v: var int, pairExists: var bool): t.withKey(1) do (k: int, v: var int, pairExists: var bool):
assert(v == 0) doAssert(v == 0)
pairExists = true pairExists = true
v = 42 v = 42
assert(t.mget(1) == 42) doAssert(t.mget(1) == 42)
t.withKey(1) do (k: int, v: var int, pairExists: var bool): t.withKey(1) do (k: int, v: var int, pairExists: var bool):
assert(v == 42) doAssert(v == 42)
pairExists = false pairExists = false
try: try:
discard t.mget(1) discard t.mget(1)
assert(false, "KeyError expected") doAssert(false, "KeyError expected")
except KeyError: except KeyError:
discard discard
t.withKey(2) do (k: int, v: var int, pairExists: var bool): t.withKey(2) do (k: int, v: var int, pairExists: var bool):
pairExists = false pairExists = false
try: try:
discard t.mget(2) discard t.mget(2)
assert(false, "KeyError expected") doAssert(false, "KeyError expected")
except KeyError: except KeyError:
discard discard
@ -242,20 +242,20 @@ block takeTest:
t["key"] = 123 t["key"] = 123
var val = 0 var val = 0
assert(t.take("key", val)) doAssert(t.take("key", val))
assert(val == 123) doAssert(val == 123)
val = -1 val = -1
assert(not t.take("key", val)) doAssert(not t.take("key", val))
assert(val == -1) doAssert(val == -1)
assert(not t.take("otherkey", val)) doAssert(not t.take("otherkey", val))
assert(val == -1) doAssert(val == -1)
proc orderedTableSortTest() = proc orderedTableSortTest() =
var t = initOrderedTable[string, int](2) var t = initOrderedTable[string, int](2)
for key, val in items(data): t[key] = val for key, val in items(data): t[key] = val
for key, val in items(data): assert t[key] == val for key, val in items(data): doAssert t[key] == val
t.sort(proc (x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key)) t.sort(proc (x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key))
var i = 0 var i = 0
# `pairs` needs to yield in sorted order: # `pairs` needs to yield in sorted order:

View file

@ -42,14 +42,14 @@ proc main =
st.add("www.weather.com", "63.111.66.11") st.add("www.weather.com", "63.111.66.11")
st.add("www.yahoo.com", "216.109.118.65") st.add("www.yahoo.com", "216.109.118.65")
assert st.getOrDefault("www.cs.princeton.edu") == "abc" doAssert st.getOrDefault("www.cs.princeton.edu") == "abc"
assert st.getOrDefault("www.harvardsucks.com") == "" doAssert st.getOrDefault("www.harvardsucks.com") == ""
assert st.getOrDefault("www.simpsons.com") == "209.052.165.60" doAssert st.getOrDefault("www.simpsons.com") == "209.052.165.60"
assert st.getOrDefault("www.apple.com") == "17.112.152.32" doAssert st.getOrDefault("www.apple.com") == "17.112.152.32"
assert st.getOrDefault("www.ebay.com") == "66.135.192.87" doAssert st.getOrDefault("www.ebay.com") == "66.135.192.87"
assert st.getOrDefault("www.dell.com") == "143.166.224.230" doAssert st.getOrDefault("www.dell.com") == "143.166.224.230"
assert(st.len == 16) doAssert(st.len == 16)
for k, v in st: for k, v in st:
echo k, ": ", v echo k, ": ", v

View file

@ -20,16 +20,16 @@ type
of true: y*: float of true: y*: float
var x = new(MyObject2) var x = new(MyObject2)
assert x of MyObject2 doAssert x of MyObject2
assert x.subobj of MyObject1 doAssert x.subobj of MyObject1
assert x.more[2] of MyObject1 doAssert x.more[2] of MyObject1
assert x.more[2] of RootObj doAssert x.more[2] of RootObj
var y: MyObject2 var y: MyObject2
assert y of MyObject2 doAssert y of MyObject2
assert y.subobj of MyObject1 doAssert y.subobj of MyObject1
assert y.more[2] of MyObject1 doAssert y.more[2] of MyObject1
assert y.more[2] of RootObj doAssert y.more[2] of RootObj
echo "true" echo "true"

View file

@ -60,12 +60,12 @@ block titerator1:
for key, val in fieldPairs(x): for key, val in fieldPairs(x):
echo key, ": ", val echo key, ": ", val
assert x != y doAssert x != y
assert x == x doAssert x == x
assert(not (x < x)) doAssert(not (x < x))
assert x <= x doAssert x <= x
assert y < x doAssert y < x
assert y <= x doAssert y <= x
block titerator2: block titerator2:

View file

@ -55,8 +55,8 @@ block t88:
let c = ChildClass[string].new("Base", "Child") let c = ChildClass[string].new("Base", "Child")
assert c.baseMethod == "Base" doAssert c.baseMethod == "Base"
assert c.overriddenMethod == "Child" doAssert c.overriddenMethod == "Child"
@ -128,7 +128,7 @@ block t1789:
bar: array[N, T] bar: array[N, T]
proc `[]`[N, T](f: Bar[N, T], n: range[0..(N - 1)]): T = proc `[]`[N, T](f: Bar[N, T], n: range[0..(N - 1)]): T =
assert high(n) == N-1 doAssert high(n) == N-1
result = f.bar[n] result = f.bar[n]
var b: Bar[3, int] var b: Bar[3, int]
@ -734,7 +734,7 @@ block t1684:
proc newDerived(idx: int): DerivedType {.inline.} = DerivedType(idx: idx) proc newDerived(idx: int): DerivedType {.inline.} = DerivedType(idx: idx)
let d = newDerived(2) let d = newDerived(2)
assert(d.index == 2) doAssert(d.index == 2)

View file

@ -58,23 +58,23 @@ block tgenericdefaults:
var x1: TFoo[int, float] var x1: TFoo[int, float]
static: static:
assert type(x1.x) is int doAssert type(x1.x) is int
assert type(x1.y) is float doAssert type(x1.y) is float
assert type(x1.z) is int doAssert type(x1.z) is int
var x2: TFoo[string, R = float, U = seq[int]] var x2: TFoo[string, R = float, U = seq[int]]
static: static:
assert type(x2.x) is string doAssert type(x2.x) is string
assert type(x2.y) is seq[int] doAssert type(x2.y) is seq[int]
assert type(x2.z) is float doAssert type(x2.z) is float
var x3: TBar[float] var x3: TBar[float]
static: static:
assert type(x3.x) is float doAssert type(x3.x) is float
assert type(x3.y) is array[4, float] doAssert type(x3.y) is array[4, float]
assert type(x3.z) is float doAssert type(x3.z) is float
@ -150,31 +150,31 @@ block tsharedcases:
doAssert high(f2.data2) == 3 # int8.len - 1 == 3 doAssert high(f2.data2) == 3 # int8.len - 1 == 3
static: static:
assert high(f1.data1) == ord(C) doAssert high(f1.data1) == ord(C)
assert high(f1.data2) == 5 # length of MyEnum minus one, because we used T.high doAssert high(f1.data2) == 5 # length of MyEnum minus one, because we used T.high
assert high(f2.data1) == 126 doAssert high(f2.data1) == 126
assert high(f2.data2) == 3 doAssert high(f2.data2) == 3
assert high(f1.data3) == 6 # length of MyEnum doAssert high(f1.data3) == 6 # length of MyEnum
assert high(f2.data3) == 4 # length of int8 doAssert high(f2.data3) == 4 # length of int8
assert f2.data3[0] is float doAssert f2.data3[0] is float
block tmap_auto: block tmap_auto:
let x = map(@[1, 2, 3], x => x+10) let x = map(@[1, 2, 3], x => x+10)
assert x == @[11, 12, 13] doAssert x == @[11, 12, 13]
let y = map(@[(1,"a"), (2,"b"), (3,"c")], x => $x[0] & x[1]) let y = map(@[(1,"a"), (2,"b"), (3,"c")], x => $x[0] & x[1])
assert y == @["1a", "2b", "3c"] doAssert y == @["1a", "2b", "3c"]
proc eatsTwoArgProc[T,S,U](a: T, b: S, f: proc(t: T, s: S): U): U = proc eatsTwoArgProc[T,S,U](a: T, b: S, f: proc(t: T, s: S): U): U =
f(a,b) f(a,b)
let z = eatsTwoArgProc(1, "a", (t,s) => $t & s) let z = eatsTwoArgProc(1, "a", (t,s) => $t & s)
assert z == "1a" doAssert z == "1a"

View file

@ -147,7 +147,7 @@ proc literal*[N, T, P](pattern: P, kind: N): Rule[N, T] =
let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int = let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int =
if start == len(text): if start == len(text):
return -1 return -1
assert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)]) doAssert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
when P is string or P is seq[N]: when P is string or P is seq[N]:
debug(debugLex, "Literal[" & $kind & "]: testing " & $pattern & " at " & $start & ": " & $text[start..start+len(pattern)-1]) debug(debugLex, "Literal[" & $kind & "]: testing " & $pattern & " at " & $start & ": " & $text[start..start+len(pattern)-1])
if text.continuesWith(pattern, start): if text.continuesWith(pattern, start):
@ -177,7 +177,7 @@ proc token[N, T](pattern: T, kind: N): Rule[N, T] =
debug(debugLex, "Token[" & $kind & "]: testing " & pattern & " at " & $start) debug(debugLex, "Token[" & $kind & "]: testing " & pattern & " at " & $start)
if start == len(text): if start == len(text):
return -1 return -1
assert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)]) doAssert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
let m = text.match(re(pattern), start) let m = text.match(re(pattern), start)
if m.isSome: if m.isSome:
let node = initNode(start, len(m.get.match), kind) let node = initNode(start, len(m.get.match), kind)
@ -192,7 +192,7 @@ proc chartest[N, T, S](testfunc: proc(s: S): bool, kind: N): Rule[N, T] =
let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int = let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int =
if start == len(text): if start == len(text):
return -1 return -1
assert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)]) doAssert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
if testfunc(text[start]): if testfunc(text[start]):
nodes.add(initNode(start, 1, kind)) nodes.add(initNode(start, 1, kind))
result = 1 result = 1
@ -252,11 +252,11 @@ proc fail*[N, T](message: string, kind: N): Rule[N, T] =
proc `+`*[N, T](left: Rule[N, T], right: Rule[N, T]): Rule[N, T] = proc `+`*[N, T](left: Rule[N, T], right: Rule[N, T]): Rule[N, T] =
let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int = let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int =
var mynodes = newSeq[Node[N]]() var mynodes = newSeq[Node[N]]()
assert(not isNil(left.parser), "Left hand side parser is nil") doAssert(not isNil(left.parser), "Left hand side parser is nil")
let leftlength = left.parser(text, start, mynodes) let leftlength = left.parser(text, start, mynodes)
if leftlength == -1: if leftlength == -1:
return leftlength return leftlength
assert(not isNil(right.parser), "Right hand side parser is nil") doAssert(not isNil(right.parser), "Right hand side parser is nil")
let rightlength = right.parser(text, start+leftlength, mynodes) let rightlength = right.parser(text, start+leftlength, mynodes)
if rightlength == -1: if rightlength == -1:
return rightlength return rightlength
@ -267,13 +267,13 @@ proc `+`*[N, T](left: Rule[N, T], right: Rule[N, T]): Rule[N, T] =
proc `/`*[N, T](left: Rule[N, T], right: Rule[N, T]): Rule[N, T] = proc `/`*[N, T](left: Rule[N, T], right: Rule[N, T]): Rule[N, T] =
let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int = let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int =
var mynodes = newSeq[Node[N]]() var mynodes = newSeq[Node[N]]()
assert(not isNil(left.parser), "Left hand side of / is not fully defined") doAssert(not isNil(left.parser), "Left hand side of / is not fully defined")
let leftlength = left.parser(text, start, mynodes) let leftlength = left.parser(text, start, mynodes)
if leftlength != -1: if leftlength != -1:
nodes.add(mynodes) nodes.add(mynodes)
return leftlength return leftlength
mynodes = newSeq[Node[N]]() mynodes = newSeq[Node[N]]()
assert(not isNil(right.parser), "Right hand side of / is not fully defined") doAssert(not isNil(right.parser), "Right hand side of / is not fully defined")
let rightlength = right.parser(text, start, mynodes) let rightlength = right.parser(text, start, mynodes)
if rightlength == -1: if rightlength == -1:
return rightlength return rightlength
@ -360,7 +360,7 @@ proc `/`*[N, T](rule: Rule[N, T]): Rule[N, T] =
result = newRule[N, T](parser, rule.kind) result = newRule[N, T](parser, rule.kind)
proc `->`*(rule: Rule, production: Rule) = proc `->`*(rule: Rule, production: Rule) =
assert(not isnil(production.parser), "Right hand side of -> is nil - has the rule been defined yet?") doAssert(not isnil(production.parser), "Right hand side of -> is nil - has the rule been defined yet?")
rule.parser = production.parser rule.parser = production.parser
template grammar*[K](Kind, Text, Symbol: typedesc; default: K, code: untyped): typed {.hint[XDeclaredButNotUsed]: off.} = template grammar*[K](Kind, Text, Symbol: typedesc; default: K, code: untyped): typed {.hint[XDeclaredButNotUsed]: off.} =

View file

@ -1,9 +1,9 @@
# test the valid literals # test the valid literals
assert 0b10 == 2 doAssert 0b10 == 2
assert 0B10 == 2 doAssert 0B10 == 2
assert 0x10 == 16 doAssert 0x10 == 16
assert 0X10 == 16 doAssert 0X10 == 16
assert 0o10 == 8 doAssert 0o10 == 8
# the following is deprecated: # the following is deprecated:
assert 0c10 == 8 doAssert 0c10 == 8
assert 0C10 == 8 doAssert 0C10 == 8

View file

@ -20,7 +20,7 @@ when not defined(windows):
# the test fails. # the test fails.
var rc1 = selector.select(t) var rc1 = selector.select(t)
var rc2 = selector.select(t) var rc2 = selector.select(t)
assert len(rc1) <= 1 and len(rc2) <= 1 doAssert len(rc1) <= 1 and len(rc2) <= 1
data.s1 += ord(len(rc1) == 1) data.s1 += ord(len(rc1) == 1)
data.s2 += ord(len(rc2) == 1) data.s2 += ord(len(rc2) == 1)
selector.unregister(timer) selector.unregister(timer)
@ -32,9 +32,9 @@ when not defined(windows):
# this can't be too large as it'll actually wait that long: # this can't be too large as it'll actually wait that long:
# timer_notification_test.n * t2 # timer_notification_test.n * t2
var rc5 = selector.select(t2) var rc5 = selector.select(t2)
assert len(rc4) + len(rc5) <= 1 doAssert len(rc4) + len(rc5) <= 1
data.s3 += ord(len(rc4) + len(rc5) == 1) data.s3 += ord(len(rc4) + len(rc5) == 1)
assert(selector.isEmpty()) doAssert(selector.isEmpty())
selector.close() selector.close()
proc timerNotificationTest() = proc timerNotificationTest() =

View file

@ -17,8 +17,8 @@ proc unpack[T](v: string): T =
var s = "123" var s = "123"
assert(unpack[string](s) is string) doAssert(unpack[string](s) is string)
assert(unpack[int](s) is int) doAssert(unpack[int](s) is int)
echo unpack[int](s) echo unpack[int](s)
echo unpack[string](s) echo unpack[string](s)
@ -37,7 +37,7 @@ proc unit(t: typedesc[int]): t = 0
proc unit(t: typedesc[string]): t = "" proc unit(t: typedesc[string]): t = ""
proc unit(t: typedesc[float]): t = 0.0 proc unit(t: typedesc[float]): t = 0.0
assert unit(int) == 0 doAssert unit(int) == 0
assert unit(string) == "" doAssert unit(string) == ""
assert unit(float) == 0.0 doAssert unit(float) == 0.0

View file

@ -10,127 +10,127 @@ discard """
# unsigned < signed # unsigned < signed
assert 10'u8 < 20'i8 doAssert 10'u8 < 20'i8
assert 10'u8 < 20'i16 doAssert 10'u8 < 20'i16
assert 10'u8 < 20'i32 doAssert 10'u8 < 20'i32
assert 10'u8 < 20'i64 doAssert 10'u8 < 20'i64
assert 10'u16 < 20'i8 doAssert 10'u16 < 20'i8
assert 10'u16 < 20'i16 doAssert 10'u16 < 20'i16
assert 10'u16 < 20'i32 doAssert 10'u16 < 20'i32
assert 10'u16 < 20'i64 doAssert 10'u16 < 20'i64
assert 10'u32 < 20'i8 doAssert 10'u32 < 20'i8
assert 10'u32 < 20'i16 doAssert 10'u32 < 20'i16
assert 10'u32 < 20'i32 doAssert 10'u32 < 20'i32
assert 10'u32 < 20'i64 doAssert 10'u32 < 20'i64
# assert 10'u64 < 20'i8 # doAssert 10'u64 < 20'i8
# assert 10'u64 < 20'i16 # doAssert 10'u64 < 20'i16
# assert 10'u64 < 20'i32 # doAssert 10'u64 < 20'i32
# assert 10'u64 < 20'i64 # doAssert 10'u64 < 20'i64
# signed < unsigned # signed < unsigned
assert 10'i8 < 20'u8 doAssert 10'i8 < 20'u8
assert 10'i8 < 20'u16 doAssert 10'i8 < 20'u16
assert 10'i8 < 20'u32 doAssert 10'i8 < 20'u32
# assert 10'i8 < 20'u64 # doAssert 10'i8 < 20'u64
assert 10'i16 < 20'u8 doAssert 10'i16 < 20'u8
assert 10'i16 < 20'u16 doAssert 10'i16 < 20'u16
assert 10'i16 < 20'u32 doAssert 10'i16 < 20'u32
# assert 10'i16 < 20'u64 # doAssert 10'i16 < 20'u64
assert 10'i32 < 20'u8 doAssert 10'i32 < 20'u8
assert 10'i32 < 20'u16 doAssert 10'i32 < 20'u16
assert 10'i32 < 20'u32 doAssert 10'i32 < 20'u32
# assert 10'i32 < 20'u64 # doAssert 10'i32 < 20'u64
assert 10'i64 < 20'u8 doAssert 10'i64 < 20'u8
assert 10'i64 < 20'u16 doAssert 10'i64 < 20'u16
assert 10'i64 < 20'u32 doAssert 10'i64 < 20'u32
# assert 10'i64 < 20'u64 # doAssert 10'i64 < 20'u64
# unsigned <= signed # unsigned <= signed
assert 10'u8 <= 20'i8 doAssert 10'u8 <= 20'i8
assert 10'u8 <= 20'i16 doAssert 10'u8 <= 20'i16
assert 10'u8 <= 20'i32 doAssert 10'u8 <= 20'i32
assert 10'u8 <= 20'i64 doAssert 10'u8 <= 20'i64
assert 10'u16 <= 20'i8 doAssert 10'u16 <= 20'i8
assert 10'u16 <= 20'i16 doAssert 10'u16 <= 20'i16
assert 10'u16 <= 20'i32 doAssert 10'u16 <= 20'i32
assert 10'u16 <= 20'i64 doAssert 10'u16 <= 20'i64
assert 10'u32 <= 20'i8 doAssert 10'u32 <= 20'i8
assert 10'u32 <= 20'i16 doAssert 10'u32 <= 20'i16
assert 10'u32 <= 20'i32 doAssert 10'u32 <= 20'i32
assert 10'u32 <= 20'i64 doAssert 10'u32 <= 20'i64
# assert 10'u64 <= 20'i8 # doAssert 10'u64 <= 20'i8
# assert 10'u64 <= 20'i16 # doAssert 10'u64 <= 20'i16
# assert 10'u64 <= 20'i32 # doAssert 10'u64 <= 20'i32
# assert 10'u64 <= 20'i64 # doAssert 10'u64 <= 20'i64
# signed <= unsigned # signed <= unsigned
assert 10'i8 <= 20'u8 doAssert 10'i8 <= 20'u8
assert 10'i8 <= 20'u16 doAssert 10'i8 <= 20'u16
assert 10'i8 <= 20'u32 doAssert 10'i8 <= 20'u32
# assert 10'i8 <= 20'u64 # doAssert 10'i8 <= 20'u64
assert 10'i16 <= 20'u8 doAssert 10'i16 <= 20'u8
assert 10'i16 <= 20'u16 doAssert 10'i16 <= 20'u16
assert 10'i16 <= 20'u32 doAssert 10'i16 <= 20'u32
# assert 10'i16 <= 20'u64 # doAssert 10'i16 <= 20'u64
assert 10'i32 <= 20'u8 doAssert 10'i32 <= 20'u8
assert 10'i32 <= 20'u16 doAssert 10'i32 <= 20'u16
assert 10'i32 <= 20'u32 doAssert 10'i32 <= 20'u32
# assert 10'i32 <= 20'u64 # doAssert 10'i32 <= 20'u64
assert 10'i64 <= 20'u8 doAssert 10'i64 <= 20'u8
assert 10'i64 <= 20'u16 doAssert 10'i64 <= 20'u16
assert 10'i64 <= 20'u32 doAssert 10'i64 <= 20'u32
# assert 10'i64 <= 20'u64 # doAssert 10'i64 <= 20'u64
# signed == unsigned # signed == unsigned
assert 10'i8 == 10'u8 doAssert 10'i8 == 10'u8
assert 10'i8 == 10'u16 doAssert 10'i8 == 10'u16
assert 10'i8 == 10'u32 doAssert 10'i8 == 10'u32
# assert 10'i8 == 10'u64 # doAssert 10'i8 == 10'u64
assert 10'i16 == 10'u8 doAssert 10'i16 == 10'u8
assert 10'i16 == 10'u16 doAssert 10'i16 == 10'u16
assert 10'i16 == 10'u32 doAssert 10'i16 == 10'u32
# assert 10'i16 == 10'u64 # doAssert 10'i16 == 10'u64
assert 10'i32 == 10'u8 doAssert 10'i32 == 10'u8
assert 10'i32 == 10'u16 doAssert 10'i32 == 10'u16
assert 10'i32 == 10'u32 doAssert 10'i32 == 10'u32
# assert 10'i32 == 10'u64 # doAssert 10'i32 == 10'u64
assert 10'i64 == 10'u8 doAssert 10'i64 == 10'u8
assert 10'i64 == 10'u16 doAssert 10'i64 == 10'u16
assert 10'i64 == 10'u32 doAssert 10'i64 == 10'u32
# assert 10'i64 == 10'u64 # doAssert 10'i64 == 10'u64
# unsigned == signed # unsigned == signed
assert 10'u8 == 10'i8 doAssert 10'u8 == 10'i8
assert 10'u8 == 10'i16 doAssert 10'u8 == 10'i16
assert 10'u8 == 10'i32 doAssert 10'u8 == 10'i32
# assert 10'u8 == 10'i64 # doAssert 10'u8 == 10'i64
assert 10'u16 == 10'i8 doAssert 10'u16 == 10'i8
assert 10'u16 == 10'i16 doAssert 10'u16 == 10'i16
assert 10'u16 == 10'i32 doAssert 10'u16 == 10'i32
# assert 10'u16 == 10'i64 # doAssert 10'u16 == 10'i64
assert 10'u32 == 10'i8 doAssert 10'u32 == 10'i8
assert 10'u32 == 10'i16 doAssert 10'u32 == 10'i16
assert 10'u32 == 10'i32 doAssert 10'u32 == 10'i32
# assert 10'u32 == 10'i64 # doAssert 10'u32 == 10'i64
# assert 10'u64 == 10'i8 # doAssert 10'u64 == 10'i8
# assert 10'u64 == 10'i16 # doAssert 10'u64 == 10'i16
# assert 10'u64 == 10'i32 # doAssert 10'u64 == 10'i32
# assert 10'u64 == 10'i64 # doAssert 10'u64 == 10'i64

View file

@ -51,56 +51,56 @@ doAssert(existsEnv("dummy") == false)
# issue #7393 # issue #7393
let wd = getCurrentDir() let wd = getCurrentDir()
cd("..") cd("..")
assert wd != getCurrentDir() doAssert wd != getCurrentDir()
cd(wd) cd(wd)
assert wd == getCurrentDir() doAssert wd == getCurrentDir()
when false: when false:
# this doesn't work in a 'koch testintall' environment # this doesn't work in a 'koch testintall' environment
assert findExe("nim") != "" doAssert findExe("nim") != ""
# general tests # general tests
mode = ScriptMode.Verbose mode = ScriptMode.Verbose
assert getCommand() == "c" doAssert getCommand() == "c"
setCommand("cpp") setCommand("cpp")
assert getCommand() == "cpp" doAssert getCommand() == "cpp"
setCommand("c") setCommand("c")
assert cmpic("HeLLO", "hello") == 0 doAssert cmpic("HeLLO", "hello") == 0
assert fileExists("tests/newconfig/tfoo.nims") == true doAssert fileExists("tests/newconfig/tfoo.nims") == true
assert dirExists("tests") == true doAssert dirExists("tests") == true
assert fileExists("tests/newconfig/tfoo.nims") == true doAssert fileExists("tests/newconfig/tfoo.nims") == true
assert dirExists("tests") == true doAssert dirExists("tests") == true
discard selfExe() discard selfExe()
when defined(windows): when defined(windows):
assert toExe("nim") == "nim.exe" doAssert toExe("nim") == "nim.exe"
assert toDll("nim") == "nim.dll" doAssert toDll("nim") == "nim.dll"
else: else:
assert toExe("nim") == "nim" doAssert toExe("nim") == "nim"
assert toDll("nim") == "libnim.so" doAssert toDll("nim") == "libnim.so"
rmDir("tempXYZ") rmDir("tempXYZ")
doAssertRaises(OSError): doAssertRaises(OSError):
rmDir("tempXYZ", checkDir = true) rmDir("tempXYZ", checkDir = true)
assert dirExists("tempXYZ") == false doAssert dirExists("tempXYZ") == false
mkDir("tempXYZ") mkDir("tempXYZ")
assert dirExists("tempXYZ") == true doAssert dirExists("tempXYZ") == true
assert fileExists("tempXYZ/koch.nim") == false doAssert fileExists("tempXYZ/koch.nim") == false
when false: when false:
# this doesn't work in a 'koch testintall' environment # this doesn't work in a 'koch testintall' environment
cpFile("koch.nim", "tempXYZ/koch.nim") cpFile("koch.nim", "tempXYZ/koch.nim")
assert fileExists("tempXYZ/koch.nim") == true doAssert fileExists("tempXYZ/koch.nim") == true
cpDir("nimsuggest", "tempXYZ/.") cpDir("nimsuggest", "tempXYZ/.")
assert dirExists("tempXYZ/tests") == true doAssert dirExists("tempXYZ/tests") == true
assert fileExists("tempXYZ/nimsuggest.nim") == true doAssert fileExists("tempXYZ/nimsuggest.nim") == true
rmFile("tempXYZ/koch.nim") rmFile("tempXYZ/koch.nim")
assert fileExists("tempXYZ/koch.nim") == false doAssert fileExists("tempXYZ/koch.nim") == false
rmDir("tempXYZ") rmDir("tempXYZ")
assert dirExists("tempXYZ") == false doAssert dirExists("tempXYZ") == false

View file

@ -7,7 +7,7 @@ Future is no longer empty, 42
import threadpool import threadpool
proc foo: string = "Dog" proc foo: string = "Dog"
var x: FlowVar[string] = spawn foo() var x: FlowVar[string] = spawn foo()
assert(^x == "Dog") doAssert(^x == "Dog")
block: block:
type type
@ -19,20 +19,20 @@ block:
discard discard
var obj = Box(empty: false, contents: "Hello") var obj = Box(empty: false, contents: "Hello")
assert obj.contents == "Hello" doAssert obj.contents == "Hello"
var obj2 = Box(empty: true) var obj2 = Box(empty: true)
doAssertRaises(FieldDefect): doAssertRaises(FieldDefect):
echo(obj2.contents) echo(obj2.contents)
import json import json
assert parseJson("null").kind == JNull doAssert parseJson("null").kind == JNull
assert parseJson("true").kind == JBool doAssert parseJson("true").kind == JBool
assert parseJson("42").kind == JInt doAssert parseJson("42").kind == JInt
assert parseJson("3.14").kind == JFloat doAssert parseJson("3.14").kind == JFloat
assert parseJson("\"Hi\"").kind == JString doAssert parseJson("\"Hi\"").kind == JString
assert parseJson("""{ "key": "value" }""").kind == JObject doAssert parseJson("""{ "key": "value" }""").kind == JObject
assert parseJson("[1, 2, 3, 4]").kind == JArray doAssert parseJson("[1, 2, 3, 4]").kind == JArray
import json import json
let data = """ let data = """
@ -40,15 +40,15 @@ let data = """
""" """
let obj = parseJson(data) let obj = parseJson(data)
assert obj.kind == JObject doAssert obj.kind == JObject
assert obj["username"].kind == JString doAssert obj["username"].kind == JString
assert obj["username"].str == "Dominik" doAssert obj["username"].str == "Dominik"
block: block:
proc count10(): int = proc count10(): int =
for i in 0 ..< 10: for i in 0 ..< 10:
result.inc result.inc
assert count10() == 10 doAssert count10() == 10
type type
Point = tuple[x, y: int] Point = tuple[x, y: int]

View file

@ -23,22 +23,22 @@ type
# This will test that all the values are what we expect. # This will test that all the values are what we expect.
proc assertTree(root: Node) = proc assertTree(root: Node) =
# check root of tree # check root of tree
assert root.kind == Operator doAssert root.kind == Operator
assert root.operator == '*' doAssert root.operator == '*'
# check left subtree # check left subtree
assert root.left.value == 5 doAssert root.left.value == 5
assert root.left.kind == Literal doAssert root.left.kind == Literal
# check right subtree # check right subtree
assert root.right.kind == Operator doAssert root.right.kind == Operator
assert root.right.operator == '+' doAssert root.right.operator == '+'
assert root.right.left.value == 5 doAssert root.right.left.value == 5
assert root.right.left.kind == Literal doAssert root.right.left.kind == Literal
assert root.right.right.value == 10 doAssert root.right.right.value == 10
assert root.right.right.kind == Literal doAssert root.right.right.kind == Literal
proc newLiteralNode(value: int): Node = proc newLiteralNode(value: int): Node =
result = Node( result = Node(

View file

@ -13,12 +13,12 @@ when defined(linux):
let initCount = countFds() let initCount = countFds()
let p = osproc.startProcess("echo", options={poUsePath}) let p = osproc.startProcess("echo", options={poUsePath})
assert countFds() == initCount + 3 doAssert countFds() == initCount + 3
p.close p.close
assert countFds() == initCount doAssert countFds() == initCount
let p1 = osproc.startProcess("echo", options={poUsePath}) let p1 = osproc.startProcess("echo", options={poUsePath})
discard p1.inputStream discard p1.inputStream
assert countFds() == initCount + 3 doAssert countFds() == initCount + 3
p.close p.close
assert countFds() == initCount doAssert countFds() == initCount

View file

@ -16,31 +16,31 @@ var z: ptr int
const C = @[1, 2, 3] const C = @[1, 2, 3]
static: static:
assert x is ref doAssert x is ref
assert y is distinct doAssert y is distinct
assert z is ptr doAssert z is ptr
assert C is static doAssert C is static
assert C[1] is static[int] doAssert C[1] is static[int]
assert C[0] is static[SomeInteger] doAssert C[0] is static[SomeInteger]
assert C isnot static[string] doAssert C isnot static[string]
assert C is SEQ|OBJ doAssert C is SEQ|OBJ
assert C isnot OBJ|TPL doAssert C isnot OBJ|TPL
assert int is int doAssert int is int
assert int is T doAssert int is T
assert int is SomeInteger doAssert int is SomeInteger
assert seq[int] is type doAssert seq[int] is type
assert seq[int] is type[seq] doAssert seq[int] is type[seq]
assert seq[int] isnot type[seq[float]] doAssert seq[int] isnot type[seq[float]]
assert i isnot type[int] doAssert i isnot type[int]
assert type(i) is type[int] doAssert type(i) is type[int]
assert x isnot T doAssert x isnot T
assert y isnot S doAssert y isnot S
assert z isnot enum doAssert z isnot enum
assert x isnot object doAssert x isnot object
assert y isnot tuple doAssert y isnot tuple
assert z isnot seq doAssert z isnot seq
# XXX: These cases don't work properly at the moment: # XXX: These cases don't work properly at the moment:
# assert type[int] isnot int # doAssert type[int] isnot int
# assert type(int) isnot int # doAssert type(int) isnot int

View file

@ -10,13 +10,13 @@ type
var var
b: bits b: bits
assert b.flag == 0 doAssert b.flag == 0
b.flag = 1 b.flag = 1
assert b.flag == 1 doAssert b.flag == 1
b.flag = 2 b.flag = 2
assert b.flag == 0 doAssert b.flag == 0
b.opts = 7 b.opts = 7
assert b.opts == 7 doAssert b.opts == 7
b.opts = 9 b.opts = 9
assert b.opts == -7 doAssert b.opts == -7

View file

@ -8,7 +8,7 @@ block:
proc myProc():int {.myAttr.} = 2 proc myProc():int {.myAttr.} = 2
const hasMyAttr = myProc.hasCustomPragma(myAttr) const hasMyAttr = myProc.hasCustomPragma(myAttr)
static: static:
assert(hasMyAttr) doAssert(hasMyAttr)
block: block:
template myAttr(a: string) {.pragma.} template myAttr(a: string) {.pragma.}
@ -19,8 +19,8 @@ block:
var o: MyObj var o: MyObj
static: static:
assert o.myField2.hasCustomPragma(myAttr) doAssert o.myField2.hasCustomPragma(myAttr)
assert(not o.myField1.hasCustomPragma(myAttr)) doAssert(not o.myField1.hasCustomPragma(myAttr))
import custom_pragma import custom_pragma
block: # A bit more advanced case block: # A bit more advanced case
@ -42,31 +42,31 @@ block: # A bit more advanced case
var s: MySerializable var s: MySerializable
const aDefVal = s.a.getCustomPragmaVal(defaultValue) const aDefVal = s.a.getCustomPragmaVal(defaultValue)
static: assert(aDefVal == 5) static: doAssert(aDefVal == 5)
const aSerKey = s.a.getCustomPragmaVal(serializationKey) const aSerKey = s.a.getCustomPragmaVal(serializationKey)
static: assert(aSerKey == "asdf") static: doAssert(aSerKey == "asdf")
const cSerKey = getCustomPragmaVal(s.field.c, serializationKey) const cSerKey = getCustomPragmaVal(s.field.c, serializationKey)
static: assert(cSerKey == "cc") static: doAssert(cSerKey == "cc")
const procSerKey = getCustomPragmaVal(myproc, serializationKey) const procSerKey = getCustomPragmaVal(myproc, serializationKey)
static: assert(procSerKey == "myprocSS") static: doAssert(procSerKey == "myprocSS")
static: assert(hasCustomPragma(myproc, alternativeKey)) static: doAssert(hasCustomPragma(myproc, alternativeKey))
const hasFieldCustomPragma = s.field.hasCustomPragma(defaultValue) const hasFieldCustomPragma = s.field.hasCustomPragma(defaultValue)
static: assert(hasFieldCustomPragma == false) static: doAssert(hasFieldCustomPragma == false)
# pragma on an object # pragma on an object
static: static:
assert Subfield.hasCustomPragma(defaultValue) doAssert Subfield.hasCustomPragma(defaultValue)
assert(Subfield.getCustomPragmaVal(defaultValue) == "catman") doAssert(Subfield.getCustomPragmaVal(defaultValue) == "catman")
assert hasCustomPragma(type(s.field), defaultValue) doAssert hasCustomPragma(type(s.field), defaultValue)
proc foo(s: var MySerializable) = proc foo(s: var MySerializable) =
static: assert(s.a.getCustomPragmaVal(defaultValue) == 5) static: doAssert(s.a.getCustomPragmaVal(defaultValue) == 5)
foo(s) foo(s)
@ -91,8 +91,8 @@ block: # ref types
leftSerKey = getCustomPragmaVal(s.left, serializationKey) leftSerKey = getCustomPragmaVal(s.left, serializationKey)
rightSerKey = getCustomPragmaVal(s.right, serializationKey) rightSerKey = getCustomPragmaVal(s.right, serializationKey)
static: static:
assert leftSerKey == "l" doAssert leftSerKey == "l"
assert rightSerKey == "r" doAssert rightSerKey == "r"
var specS = SpecialNodeRef() var specS = SpecialNodeRef()
@ -100,25 +100,25 @@ block: # ref types
dataDefVal = hasCustomPragma(specS.data, defaultValue) dataDefVal = hasCustomPragma(specS.data, defaultValue)
specLeftSerKey = hasCustomPragma(specS.left, serializationKey) specLeftSerKey = hasCustomPragma(specS.left, serializationKey)
static: static:
assert dataDefVal == true doAssert dataDefVal == true
assert specLeftSerKey == true doAssert specLeftSerKey == true
var ptrS = NodePtr(nil) var ptrS = NodePtr(nil)
const const
ptrRightSerKey = getCustomPragmaVal(ptrS.right, serializationKey) ptrRightSerKey = getCustomPragmaVal(ptrS.right, serializationKey)
static: static:
assert ptrRightSerKey == "r" doAssert ptrRightSerKey == "r"
var f = MyFile() var f = MyFile()
const const
fileDefVal = f.getCustomPragmaVal(defaultValue) fileDefVal = f.getCustomPragmaVal(defaultValue)
filePathDefVal = f.path.getCustomPragmaVal(defaultValue) filePathDefVal = f.path.getCustomPragmaVal(defaultValue)
static: static:
assert fileDefVal == "closed" doAssert fileDefVal == "closed"
assert filePathDefVal == "invalid" doAssert filePathDefVal == "invalid"
static: static:
assert TypeWithoutPragma.hasCustomPragma(defaultValue) == false doAssert TypeWithoutPragma.hasCustomPragma(defaultValue) == false
block: block:
type type
@ -144,9 +144,9 @@ block:
nestedItemDefVal = vari.nestedItem.getCustomPragmaVal(defaultValue) nestedItemDefVal = vari.nestedItem.getCustomPragmaVal(defaultValue)
static: static:
assert hasIntSerKey doAssert hasIntSerKey
assert strSerKey == "string" doAssert strSerKey == "string"
assert nestedItemDefVal == "Nimmers of the world, unite!" doAssert nestedItemDefVal == "Nimmers of the world, unite!"
block: block:
template simpleAttr {.pragma.} template simpleAttr {.pragma.}
@ -154,7 +154,7 @@ block:
type Annotated {.simpleAttr.} = object type Annotated {.simpleAttr.} = object
proc generic_proc[T]() = proc generic_proc[T]() =
assert Annotated.hasCustomPragma(simpleAttr) doAssert Annotated.hasCustomPragma(simpleAttr)
#-------------------------------------------------------------------------- #--------------------------------------------------------------------------
@ -252,7 +252,7 @@ block:
block: block:
macro expectedAst(expectedRepr: static[string], input: untyped): untyped = macro expectedAst(expectedRepr: static[string], input: untyped): untyped =
assert input.treeRepr & "\n" == expectedRepr doAssert input.treeRepr & "\n" == expectedRepr
return input return input
const procTypeAst = """ const procTypeAst = """
@ -270,7 +270,7 @@ ProcTy
type type
Foo = proc (x: int) {.expectedAst(procTypeAst), async.} Foo = proc (x: int) {.expectedAst(procTypeAst), async.}
static: assert Foo is proc(x: int): Future[void] static: doAssert Foo is proc(x: int): Future[void]
const asyncProcTypeAst = """ const asyncProcTypeAst = """
ProcTy ProcTy
@ -288,7 +288,7 @@ ProcTy
type type
Bar = proc (s: string) {.async, expectedAst(asyncProcTypeAst).} Bar = proc (s: string) {.async, expectedAst(asyncProcTypeAst).}
static: assert Bar is proc(x: string): Future[void] static: doAssert Bar is proc(x: string): Future[void]
const typeAst = """ const typeAst = """
TypeDef TypeDef
@ -310,7 +310,7 @@ TypeDef
Baz {.expectedAst(typeAst).} = object Baz {.expectedAst(typeAst).} = object
x: string x: string
static: assert Baz.x is string static: doAssert Baz.x is string
const procAst = """ const procAst = """
ProcDef ProcDef
@ -333,7 +333,7 @@ ProcDef
proc bar(s: string): string {.expectedAst(procAst).} = proc bar(s: string): string {.expectedAst(procAst).} =
return s return s
static: assert bar("x") == "x" static: doAssert bar("x") == "x"
#------------------------------------------------------ #------------------------------------------------------
# bug #13909 # bug #13909

View file

@ -58,13 +58,13 @@ block tsets2:
var t = initHashSet[tuple[x, y: int]]() var t = initHashSet[tuple[x, y: int]]()
t.incl((0,0)) t.incl((0,0))
t.incl((1,0)) t.incl((1,0))
assert(not t.containsOrIncl((0,1))) doAssert(not t.containsOrIncl((0,1)))
t.incl((1,1)) t.incl((1,1))
for x in 0..1: for x in 0..1:
for y in 0..1: for y in 0..1:
assert((x,y) in t) doAssert((x,y) in t)
#assert($t == #doAssert($t ==
# "{(x: 0, y: 0), (x: 0, y: 1), (x: 1, y: 0), (x: 1, y: 1)}") # "{(x: 0, y: 0), (x: 0, y: 1), (x: 1, y: 0), (x: 1, y: 1)}")
block setTest2: block setTest2:
@ -76,31 +76,31 @@ block tsets2:
t.incl("012") t.incl("012")
t.incl("123") # test duplicates t.incl("123") # test duplicates
assert "123" in t doAssert "123" in t
assert "111" notin t # deleted doAssert "111" notin t # deleted
assert t.missingOrExcl("000") doAssert t.missingOrExcl("000")
assert "000" notin t doAssert "000" notin t
assert t.missingOrExcl("012") == false doAssert t.missingOrExcl("012") == false
assert "012" notin t doAssert "012" notin t
assert t.containsOrIncl("012") == false doAssert t.containsOrIncl("012") == false
assert t.containsOrIncl("012") doAssert t.containsOrIncl("012")
assert "012" in t # added back doAssert "012" in t # added back
for key in items(data): t.incl(key) for key in items(data): t.incl(key)
for key in items(data): assert key in t for key in items(data): doAssert key in t
for key in items(data): t.excl(key) for key in items(data): t.excl(key)
for key in items(data): assert key notin t for key in items(data): doAssert key notin t
block orderedSetTest1: block orderedSetTest1:
var t = data.toOrderedSet var t = data.toOrderedSet
for key in items(data): assert key in t for key in items(data): doAssert key in t
var i = 0 var i = 0
# `items` needs to yield in insertion order: # `items` needs to yield in insertion order:
for key in items(t): for key in items(t):
assert key == data[i] doAssert key == data[i]
inc(i) inc(i)
@ -117,22 +117,22 @@ block tsets3:
s1_s3 = s1 + s3 s1_s3 = s1 + s3
s2_s3 = s2 + s3 s2_s3 = s2 + s3
assert s1_s2.len == 7 doAssert s1_s2.len == 7
assert s1_s3.len == 8 doAssert s1_s3.len == 8
assert s2_s3.len == 6 doAssert s2_s3.len == 6
for i in s1: for i in s1:
assert i in s1_s2 doAssert i in s1_s2
assert i in s1_s3 doAssert i in s1_s3
for i in s2: for i in s2:
assert i in s1_s2 doAssert i in s1_s2
assert i in s2_s3 doAssert i in s2_s3
for i in s3: for i in s3:
assert i in s1_s3 doAssert i in s1_s3
assert i in s2_s3 doAssert i in s2_s3
assert((s1 + s1) == s1) doAssert((s1 + s1) == s1)
assert((s2 + s1) == s1_s2) doAssert((s2 + s1) == s1_s2)
block intersection: block intersection:
let let
@ -140,22 +140,22 @@ block tsets3:
s1_s3 = intersection(s1, s3) s1_s3 = intersection(s1, s3)
s2_s3 = s2 * s3 s2_s3 = s2 * s3
assert s1_s2.len == 3 doAssert s1_s2.len == 3
assert s1_s3.len == 0 doAssert s1_s3.len == 0
assert s2_s3.len == 2 doAssert s2_s3.len == 2
for i in s1_s2: for i in s1_s2:
assert i in s1 doAssert i in s1
assert i in s2 doAssert i in s2
for i in s1_s3: for i in s1_s3:
assert i in s1 doAssert i in s1
assert i in s3 doAssert i in s3
for i in s2_s3: for i in s2_s3:
assert i in s2 doAssert i in s2
assert i in s3 doAssert i in s3
assert((s2 * s2) == s2) doAssert((s2 * s2) == s2)
assert((s3 * s2) == s2_s3) doAssert((s3 * s2) == s2_s3)
block symmetricDifference: block symmetricDifference:
let let
@ -163,22 +163,22 @@ block tsets3:
s1_s3 = s1 -+- s3 s1_s3 = s1 -+- s3
s2_s3 = s2 -+- s3 s2_s3 = s2 -+- s3
assert s1_s2.len == 4 doAssert s1_s2.len == 4
assert s1_s3.len == 8 doAssert s1_s3.len == 8
assert s2_s3.len == 4 doAssert s2_s3.len == 4
for i in s1: for i in s1:
assert i in s1_s2 xor i in s2 doAssert i in s1_s2 xor i in s2
assert i in s1_s3 xor i in s3 doAssert i in s1_s3 xor i in s3
for i in s2: for i in s2:
assert i in s1_s2 xor i in s1 doAssert i in s1_s2 xor i in s1
assert i in s2_s3 xor i in s3 doAssert i in s2_s3 xor i in s3
for i in s3: for i in s3:
assert i in s1_s3 xor i in s1 doAssert i in s1_s3 xor i in s1
assert i in s2_s3 xor i in s2 doAssert i in s2_s3 xor i in s2
assert((s3 -+- s3) == initHashSet[int]()) doAssert((s3 -+- s3) == initHashSet[int]())
assert((s3 -+- s1) == s1_s3) doAssert((s3 -+- s1) == s1_s3)
block difference: block difference:
let let
@ -186,23 +186,23 @@ block tsets3:
s1_s3 = difference(s1, s3) s1_s3 = difference(s1, s3)
s2_s3 = s2 - s3 s2_s3 = s2 - s3
assert s1_s2.len == 2 doAssert s1_s2.len == 2
assert s1_s3.len == 5 doAssert s1_s3.len == 5
assert s2_s3.len == 3 doAssert s2_s3.len == 3
for i in s1: for i in s1:
assert i in s1_s2 xor i in s2 doAssert i in s1_s2 xor i in s2
assert i in s1_s3 xor i in s3 doAssert i in s1_s3 xor i in s3
for i in s2: for i in s2:
assert i in s2_s3 xor i in s3 doAssert i in s2_s3 xor i in s3
assert((s2 - s2) == initHashSet[int]()) doAssert((s2 - s2) == initHashSet[int]())
block disjoint: block disjoint:
assert(not disjoint(s1, s2)) doAssert(not disjoint(s1, s2))
assert disjoint(s1, s3) doAssert disjoint(s1, s3)
assert(not disjoint(s2, s3)) doAssert(not disjoint(s2, s3))
assert(not disjoint(s2, s2)) doAssert(not disjoint(s2, s2))
block: # https://github.com/nim-lang/Nim/issues/13496 block: # https://github.com/nim-lang/Nim/issues/13496
template testDel(body) = template testDel(body) =
@ -217,7 +217,7 @@ block: # https://github.com/nim-lang/Nim/issues/13496
doAssert sortedItems(t) == @[15, 17, 19] doAssert sortedItems(t) == @[15, 17, 19]
var s = newSeq[int]() var s = newSeq[int]()
for v in t: s.add(v) for v in t: s.add(v)
assert s.len == 3 doAssert s.len == 3
doAssert sortedItems(s) == @[15, 17, 19] doAssert sortedItems(s) == @[15, 17, 19]
when t is OrderedSet: when t is OrderedSet:
doAssert sortedPairs(t) == @[(a: 0, b: 15), (a: 1, b: 19), (a: 2, b: 17)] doAssert sortedPairs(t) == @[(a: 0, b: 15), (a: 1, b: 19), (a: 2, b: 17)]

View file

@ -17,14 +17,14 @@ Val1
import macros import macros
template ok(x) = assert(x) template ok(x) = doAssert(x)
template no(x) = assert(not x) template no(x) = doAssert(not x)
template accept(x) = template accept(x) =
static: assert(compiles(x)) static: doAssert(compiles(x))
template reject(x) = template reject(x) =
static: assert(not compiles(x)) static: doAssert(not compiles(x))
proc plus(a, b: int): int = a + b proc plus(a, b: int): int = a + b
@ -54,8 +54,8 @@ when true:
b: static[int], b: static[int],
c: static int) = c: static int) =
static: static:
assert a.isStatic and b.isStatic and c.isStatic doAssert a.isStatic and b.isStatic and c.isStatic
assert isStatic(a + plus(b, c)) doAssert isStatic(a + plus(b, c))
echo "staticAlialProc instantiated with ", a, b, c echo "staticAlialProc instantiated with ", a, b, c
when b mod a == 0: when b mod a == 0:
@ -111,9 +111,9 @@ when true:
var aw3: ArrayWrapper3[(10, "str")] var aw3: ArrayWrapper3[(10, "str")]
static: static:
assert aw1.data.high == 5 doAssert aw1.data.high == 5
assert aw2.data.high == 6 doAssert aw2.data.high == 6
assert aw3.data.high == 9 doAssert aw3.data.high == 9
# #6077 # #6077
block: block:

View file

@ -6,4 +6,4 @@ test_queue.push(7)
test_queue.push(3) test_queue.push(3)
test_queue.push(9) test_queue.push(9)
let i = test_queue.pushpop(10) let i = test_queue.pushpop(10)
assert i == 3 doAssert i == 3

View file

@ -20,31 +20,31 @@ test()
block: block:
# Tests for lowerBound # Tests for lowerBound
var arr = @[1, 2, 3, 5, 6, 7, 8, 9] var arr = @[1, 2, 3, 5, 6, 7, 8, 9]
assert arr.lowerBound(0) == 0 doAssert arr.lowerBound(0) == 0
assert arr.lowerBound(4) == 3 doAssert arr.lowerBound(4) == 3
assert arr.lowerBound(5) == 3 doAssert arr.lowerBound(5) == 3
assert arr.lowerBound(10) == 8 doAssert arr.lowerBound(10) == 8
arr = @[1, 5, 10] arr = @[1, 5, 10]
assert arr.lowerBound(4) == 1 doAssert arr.lowerBound(4) == 1
assert arr.lowerBound(5) == 1 doAssert arr.lowerBound(5) == 1
assert arr.lowerBound(6) == 2 doAssert arr.lowerBound(6) == 2
# Tests for isSorted # Tests for isSorted
var srt1 = [1, 2, 3, 4, 4, 4, 4, 5] var srt1 = [1, 2, 3, 4, 4, 4, 4, 5]
var srt2 = ["iello", "hello"] var srt2 = ["iello", "hello"]
var srt3 = [1.0, 1.0, 1.0] var srt3 = [1.0, 1.0, 1.0]
var srt4: seq[int] var srt4: seq[int]
assert srt1.isSorted(cmp) == true doAssert srt1.isSorted(cmp) == true
assert srt2.isSorted(cmp) == false doAssert srt2.isSorted(cmp) == false
assert srt3.isSorted(cmp) == true doAssert srt3.isSorted(cmp) == true
assert srt4.isSorted(cmp) == true doAssert srt4.isSorted(cmp) == true
var srtseq = newSeq[int]() var srtseq = newSeq[int]()
assert srtseq.isSorted(cmp) == true doAssert srtseq.isSorted(cmp) == true
# Tests for reversed # Tests for reversed
var arr1 = @[0, 1, 2, 3, 4] var arr1 = @[0, 1, 2, 3, 4]
assert arr1.reversed() == @[4, 3, 2, 1, 0] doAssert arr1.reversed() == @[4, 3, 2, 1, 0]
for i in 0 .. high(arr1): for i in 0 .. high(arr1):
assert arr1.reversed(0, i) == arr1.reversed()[high(arr1) - i .. high(arr1)] doAssert arr1.reversed(0, i) == arr1.reversed()[high(arr1) - i .. high(arr1)]
assert arr1.reversed(i, high(arr1)) == arr1.reversed()[0 .. high(arr1) - i] doAssert arr1.reversed(i, high(arr1)) == arr1.reversed()[0 .. high(arr1) - i]
block: block:
var list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

View file

@ -16,48 +16,48 @@ template main =
doAssert r.contains"def" doAssert r.contains"def"
r.excl "def" r.excl "def"
assert r.missingOrExcl("foo") == false doAssert r.missingOrExcl("foo") == false
assert "foo" notin toSeq(r.items) doAssert "foo" notin toSeq(r.items)
assert r.missingOrExcl("foo") == true doAssert r.missingOrExcl("foo") == true
assert toSeq(r.items) == @["abc", "definition", "prefix", "xyz"] doAssert toSeq(r.items) == @["abc", "definition", "prefix", "xyz"]
assert toSeq(r.itemsWithPrefix("de")) == @["definition"] doAssert toSeq(r.itemsWithPrefix("de")) == @["definition"]
var c = CritBitTree[int]() var c = CritBitTree[int]()
c.inc("a") c.inc("a")
assert c["a"] == 1 doAssert c["a"] == 1
c.inc("a", 4) c.inc("a", 4)
assert c["a"] == 5 doAssert c["a"] == 5
c.inc("a", -5) c.inc("a", -5)
assert c["a"] == 0 doAssert c["a"] == 0
c.inc("b", 2) c.inc("b", 2)
assert c["b"] == 2 doAssert c["b"] == 2
c.inc("c", 3) c.inc("c", 3)
assert c["c"] == 3 doAssert c["c"] == 3
c.inc("a", 1) c.inc("a", 1)
assert c["a"] == 1 doAssert c["a"] == 1
var cf = CritBitTree[float]() var cf = CritBitTree[float]()
cf.incl("a", 1.0) cf.incl("a", 1.0)
assert cf["a"] == 1.0 doAssert cf["a"] == 1.0
cf.incl("b", 2.0) cf.incl("b", 2.0)
assert cf["b"] == 2.0 doAssert cf["b"] == 2.0
cf.incl("c", 3.0) cf.incl("c", 3.0)
assert cf["c"] == 3.0 doAssert cf["c"] == 3.0
assert cf.len == 3 doAssert cf.len == 3
cf.excl("c") cf.excl("c")
assert cf.len == 2 doAssert cf.len == 2
var cb: CritBitTree[string] var cb: CritBitTree[string]
cb.incl("help", "help") cb.incl("help", "help")

View file

@ -11,7 +11,7 @@ block:
proc main = proc main =
var testDeque = initDeque[int]() var testDeque = initDeque[int]()
testDeque.addFirst(1) testDeque.addFirst(1)
assert testDeque.index(0) == 1 doAssert testDeque.index(0) == 1
main() main()
@ -35,26 +35,26 @@ block:
deq.addFirst(123) deq.addFirst(123)
var first = deq.popFirst() var first = deq.popFirst()
deq.addLast(56) deq.addLast(56)
assert(deq.peekLast() == 56) doAssert(deq.peekLast() == 56)
deq.addLast(6) deq.addLast(6)
assert(deq.peekLast() == 6) doAssert(deq.peekLast() == 6)
var second = deq.popFirst() var second = deq.popFirst()
deq.addLast(789) deq.addLast(789)
assert(deq.peekLast() == 789) doAssert(deq.peekLast() == 789)
assert first == 123 doAssert first == 123
assert second == 9 doAssert second == 9
assert($deq == "[4, 56, 6, 789]") doAssert($deq == "[4, 56, 6, 789]")
assert deq == [4, 56, 6, 789].toDeque doAssert deq == [4, 56, 6, 789].toDeque
assert deq[0] == deq.peekFirst and deq.peekFirst == 4 doAssert deq[0] == deq.peekFirst and deq.peekFirst == 4
#assert deq[^1] == deq.peekLast and deq.peekLast == 789 #doAssert deq[^1] == deq.peekLast and deq.peekLast == 789
deq[0] = 42 deq[0] = 42
deq[deq.len - 1] = 7 deq[deq.len - 1] = 7
assert 6 in deq and 789 notin deq doAssert 6 in deq and 789 notin deq
assert deq.find(6) >= 0 doAssert deq.find(6) >= 0
assert deq.find(789) < 0 doAssert deq.find(789) < 0
block: block:
var d = initDeque[int](1) var d = initDeque[int](1)
@ -74,21 +74,21 @@ block:
for i in -2 .. 10: for i in -2 .. 10:
if i in deq: if i in deq:
assert deq.contains(i) and deq.find(i) >= 0 doAssert deq.contains(i) and deq.find(i) >= 0
else: else:
assert(not deq.contains(i) and deq.find(i) < 0) doAssert(not deq.contains(i) and deq.find(i) < 0)
when compileOption("boundChecks"): when compileOption("boundChecks"):
try: try:
echo deq[99] echo deq[99]
assert false doAssert false
except IndexDefect: except IndexDefect:
discard discard
try: try:
assert deq.len == 4 doAssert deq.len == 4
for i in 0 ..< 5: deq.popFirst() for i in 0 ..< 5: deq.popFirst()
assert false doAssert false
except IndexDefect: except IndexDefect:
discard discard
@ -98,24 +98,24 @@ block:
deq.popFirst() deq.popFirst()
deq.popLast() deq.popLast()
for i in 5 .. 8: deq.addFirst i for i in 5 .. 8: deq.addFirst i
assert $deq == "[8, 7, 6, 5, 2, 3]" doAssert $deq == "[8, 7, 6, 5, 2, 3]"
# Similar to proc from the documentation example # Similar to proc from the documentation example
proc foo(a, b: Positive) = # assume random positive values for `a` and `b`. proc foo(a, b: Positive) = # assume random positive values for `a` and `b`.
var deq = initDeque[int]() var deq = initDeque[int]()
assert deq.len == 0 doAssert deq.len == 0
for i in 1 .. a: deq.addLast i for i in 1 .. a: deq.addLast i
if b < deq.len: # checking before indexed access. if b < deq.len: # checking before indexed access.
assert deq[b] == b + 1 doAssert deq[b] == b + 1
# The following two lines don't need any checking on access due to the logic # The following two lines don't need any checking on access due to the logic
# of the program, but that would not be the case if `a` could be 0. # of the program, but that would not be the case if `a` could be 0.
assert deq.peekFirst == 1 doAssert deq.peekFirst == 1
assert deq.peekLast == a doAssert deq.peekLast == a
while deq.len > 0: # checking if the deque is empty while deq.len > 0: # checking if the deque is empty
assert deq.popFirst() > 0 doAssert deq.popFirst() > 0
#foo(0,0) #foo(0,0)
foo(8, 5) foo(8, 5)
@ -133,7 +133,7 @@ block t13310:
q.addFirst([1'i16].toHashSet) q.addFirst([1'i16].toHashSet)
q.addFirst([2'i16].toHashSet) q.addFirst([2'i16].toHashSet)
q.addFirst([3'i16].toHashSet) q.addFirst([3'i16].toHashSet)
assert $q == "[{3}, {2}, {1}]" doAssert $q == "[{3}, {2}, {1}]"
static: static:
main() main()

View file

@ -30,11 +30,11 @@ doAssert editDistanceAscii("kitten", "sitting") == 3 # from Wikipedia
doAssert editDistanceAscii("flaw", "lawn") == 2 # from Wikipedia doAssert editDistanceAscii("flaw", "lawn") == 2 # from Wikipedia
assert(editDistance("prefix__hallo_suffix", "prefix__hallo_suffix") == 0) doAssert(editDistance("prefix__hallo_suffix", "prefix__hallo_suffix") == 0)
assert(editDistance("prefix__hallo_suffix", "prefix__hallo_suffi1") == 1) doAssert(editDistance("prefix__hallo_suffix", "prefix__hallo_suffi1") == 1)
assert(editDistance("prefix__hallo_suffix", "prefix__HALLO_suffix") == 5) doAssert(editDistance("prefix__hallo_suffix", "prefix__HALLO_suffix") == 5)
assert(editDistance("prefix__hallo_suffix", "prefix__ha_suffix") == 3) doAssert(editDistance("prefix__hallo_suffix", "prefix__ha_suffix") == 3)
assert(editDistance("prefix__hallo_suffix", "prefix") == 14) doAssert(editDistance("prefix__hallo_suffix", "prefix") == 14)
assert(editDistance("prefix__hallo_suffix", "suffix") == 14) doAssert(editDistance("prefix__hallo_suffix", "suffix") == 14)
assert(editDistance("prefix__hallo_suffix", "prefix__hao_suffix") == 2) doAssert(editDistance("prefix__hallo_suffix", "prefix__hao_suffix") == 2)
assert(editDistance("main", "malign") == 2) doAssert(editDistance("main", "malign") == 2)

View file

@ -6,14 +6,14 @@ block:
var res: seq[(int, int)] var res: seq[(int, int)]
for i, x in enumerate(a): for i, x in enumerate(a):
res.add (i, x) res.add (i, x)
assert res == @[(0, 1), (1, 3), (2, 5), (3, 7)] doAssert res == @[(0, 1), (1, 3), (2, 5), (3, 7)]
block: block:
var res: seq[(int, int)] var res: seq[(int, int)]
for (i, x) in enumerate(a.items): for (i, x) in enumerate(a.items):
res.add (i, x) res.add (i, x)
assert res == @[(0, 1), (1, 3), (2, 5), (3, 7)] doAssert res == @[(0, 1), (1, 3), (2, 5), (3, 7)]
block: block:
var res: seq[(int, int)] var res: seq[(int, int)]
for i, x in enumerate(3, a): for i, x in enumerate(3, a):
res.add (i, x) res.add (i, x)
assert res == @[(3, 1), (4, 3), (5, 5), (6, 7)] doAssert res == @[(3, 1), (4, 3), (5, 5), (6, 7)]

View file

@ -47,7 +47,7 @@ block t2813:
for n in tree.findAll("table"): for n in tree.findAll("table"):
n.findAll("tr", rows) # len = 2 n.findAll("tr", rows) # len = 2
break break
assert tree.findAll("tr").len == rows.len doAssert tree.findAll("tr").len == rows.len
block t2814: block t2814:

View file

@ -2,31 +2,31 @@ import httpcore, strutils
block: block:
block HttpCode: block HttpCode:
assert $Http418 == "418 I'm a teapot" doAssert $Http418 == "418 I'm a teapot"
assert Http418.is4xx() == true doAssert Http418.is4xx() == true
assert Http418.is2xx() == false doAssert Http418.is2xx() == false
block headers: block headers:
var h = newHttpHeaders() var h = newHttpHeaders()
assert h.len == 0 doAssert h.len == 0
h.add("Cookie", "foo") h.add("Cookie", "foo")
assert h.len == 1 doAssert h.len == 1
assert h.hasKey("cooKIE") doAssert h.hasKey("cooKIE")
assert h["Cookie"] == "foo" doAssert h["Cookie"] == "foo"
assert h["cookie"] == "foo" doAssert h["cookie"] == "foo"
h["cookie"] = @["bar", "x"] h["cookie"] = @["bar", "x"]
assert h["Cookie"] == "bar" doAssert h["Cookie"] == "bar"
assert h["Cookie", 1] == "x" doAssert h["Cookie", 1] == "x"
assert h["Cookie"].contains("BaR") == true doAssert h["Cookie"].contains("BaR") == true
assert h["Cookie"].contains("X") == true doAssert h["Cookie"].contains("X") == true
assert "baR" in h["cookiE"] doAssert "baR" in h["cookiE"]
h.del("coOKie") h.del("coOKie")
assert h.len == 0 doAssert h.len == 0
# Test that header constructor works with repeated values # Test that header constructor works with repeated values
let h1 = newHttpHeaders({"a": "1", "a": "2", "A": "3"}) let h1 = newHttpHeaders({"a": "1", "a": "2", "A": "3"})
assert seq[string](h1["a"]).join(",") == "1,2,3" doAssert seq[string](h1["a"]).join(",") == "1,2,3"
block test_cookies_with_comma: block test_cookies_with_comma:
doAssert parseHeader("cookie: foo, bar") == ("cookie", @["foo, bar"]) doAssert parseHeader("cookie: foo, bar") == ("cookie", @["foo, bar"])

View file

@ -11,16 +11,16 @@ block SinglyLinkedListTest1:
var L: SinglyLinkedList[int] var L: SinglyLinkedList[int]
for d in items(data): L.prepend(d) for d in items(data): L.prepend(d)
for d in items(data): L.append(d) for d in items(data): L.append(d)
assert($L == "[6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6]") doAssert($L == "[6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6]")
assert(4 in L) doAssert(4 in L)
block SinglyLinkedListTest2: block SinglyLinkedListTest2:
var L: SinglyLinkedList[string] var L: SinglyLinkedList[string]
for d in items(data): L.prepend($d) for d in items(data): L.prepend($d)
assert($L == """["6", "5", "4", "3", "2", "1"]""") doAssert($L == """["6", "5", "4", "3", "2", "1"]""")
assert("4" in L) doAssert("4" in L)
block DoublyLinkedListTest1: block DoublyLinkedListTest1:
@ -28,39 +28,39 @@ block DoublyLinkedListTest1:
for d in items(data): L.prepend(d) for d in items(data): L.prepend(d)
for d in items(data): L.append(d) for d in items(data): L.append(d)
L.remove(L.find(1)) L.remove(L.find(1))
assert($L == "[6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6]") doAssert($L == "[6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6]")
assert(4 in L) doAssert(4 in L)
block SinglyLinkedRingTest1: block SinglyLinkedRingTest1:
var L: SinglyLinkedRing[int] var L: SinglyLinkedRing[int]
L.prepend(4) L.prepend(4)
assert($L == "[4]") doAssert($L == "[4]")
L.prepend(4) L.prepend(4)
assert($L == "[4, 4]") doAssert($L == "[4, 4]")
assert(4 in L) doAssert(4 in L)
block DoublyLinkedRingTest1: block DoublyLinkedRingTest1:
var L: DoublyLinkedRing[int] var L: DoublyLinkedRing[int]
L.prepend(4) L.prepend(4)
assert($L == "[4]") doAssert($L == "[4]")
L.prepend(4) L.prepend(4)
assert($L == "[4, 4]") doAssert($L == "[4, 4]")
assert(4 in L) doAssert(4 in L)
L.append(3) L.append(3)
L.append(5) L.append(5)
assert($L == "[4, 4, 3, 5]") doAssert($L == "[4, 4, 3, 5]")
L.remove(L.find(3)) L.remove(L.find(3))
L.remove(L.find(5)) L.remove(L.find(5))
L.remove(L.find(4)) L.remove(L.find(4))
L.remove(L.find(4)) L.remove(L.find(4))
assert($L == "[]") doAssert($L == "[]")
assert(4 notin L) doAssert(4 notin L)
block tlistsToString: block tlistsToString:
block: block:
@ -105,8 +105,8 @@ template testCommon(initList, toList) =
doAssert a.toSeq == [f0] doAssert a.toSeq == [f0]
doAssert b.toSeq == [f0, f1] doAssert b.toSeq == [f0, f1]
f0.x = 42 f0.x = 42
assert a.head.value.x == 42 doAssert a.head.value.x == 42
assert b.head.value.x == 42 doAssert b.head.value.x == 42
block: # add, addMoved block: # add, addMoved
block: block:

View file

@ -152,10 +152,10 @@ block:
return sqrt(num) return sqrt(num)
# check gamma function # check gamma function
assert(gamma(5.0) == 24.0) # 4! doAssert(gamma(5.0) == 24.0) # 4!
assert(lgamma(1.0) == 0.0) # ln(1.0) == 0.0 doAssert(lgamma(1.0) == 0.0) # ln(1.0) == 0.0
assert(erf(6.0) > erf(5.0)) doAssert(erf(6.0) > erf(5.0))
assert(erfc(6.0) < erfc(5.0)) doAssert(erfc(6.0) < erfc(5.0))
# Function for approximate comparison of floats # Function for approximate comparison of floats
@ -215,21 +215,21 @@ block:
doAssert(classify(trunc(0.0'f32)) == fcZero) doAssert(classify(trunc(0.0'f32)) == fcZero)
block: # sgn() tests block: # sgn() tests
assert sgn(1'i8) == 1 doAssert sgn(1'i8) == 1
assert sgn(1'i16) == 1 doAssert sgn(1'i16) == 1
assert sgn(1'i32) == 1 doAssert sgn(1'i32) == 1
assert sgn(1'i64) == 1 doAssert sgn(1'i64) == 1
assert sgn(1'u8) == 1 doAssert sgn(1'u8) == 1
assert sgn(1'u16) == 1 doAssert sgn(1'u16) == 1
assert sgn(1'u32) == 1 doAssert sgn(1'u32) == 1
assert sgn(1'u64) == 1 doAssert sgn(1'u64) == 1
assert sgn(-12342.8844'f32) == -1 doAssert sgn(-12342.8844'f32) == -1
assert sgn(123.9834'f64) == 1 doAssert sgn(123.9834'f64) == 1
assert sgn(0'i32) == 0 doAssert sgn(0'i32) == 0
assert sgn(0'f32) == 0 doAssert sgn(0'f32) == 0
assert sgn(NegInf) == -1 doAssert sgn(NegInf) == -1
assert sgn(Inf) == 1 doAssert sgn(Inf) == 1
assert sgn(NaN) == 0 doAssert sgn(NaN) == 0
block: # fac() tests block: # fac() tests
try: try:

View file

@ -1,7 +1,7 @@
import md5 import md5
assert(getMD5("Franz jagt im komplett verwahrlosten Taxi quer durch Bayern") == doAssert(getMD5("Franz jagt im komplett verwahrlosten Taxi quer durch Bayern") ==
"a3cca2b2aa1e3b5b3b5aad99a8529074") "a3cca2b2aa1e3b5b3b5aad99a8529074")
assert(getMD5("Frank jagt im komplett verwahrlosten Taxi quer durch Bayern") == doAssert(getMD5("Frank jagt im komplett verwahrlosten Taxi quer durch Bayern") ==
"7e716d0e702df0505fc72e2b89467910") "7e716d0e702df0505fc72e2b89467910")
assert($toMD5("") == "d41d8cd98f00b204e9800998ecf8427e") doAssert($toMD5("") == "d41d8cd98f00b204e9800998ecf8427e")

View file

@ -468,19 +468,19 @@ block isRelativeTo:
doAssert not isRelativeTo("/foo2", "/foo") doAssert not isRelativeTo("/foo2", "/foo")
block: # quoteShellWindows block: # quoteShellWindows
assert quoteShellWindows("aaa") == "aaa" doAssert quoteShellWindows("aaa") == "aaa"
assert quoteShellWindows("aaa\"") == "aaa\\\"" doAssert quoteShellWindows("aaa\"") == "aaa\\\""
assert quoteShellWindows("") == "\"\"" doAssert quoteShellWindows("") == "\"\""
block: # quoteShellWindows block: # quoteShellWindows
assert quoteShellPosix("aaa") == "aaa" doAssert quoteShellPosix("aaa") == "aaa"
assert quoteShellPosix("aaa a") == "'aaa a'" doAssert quoteShellPosix("aaa a") == "'aaa a'"
assert quoteShellPosix("") == "''" doAssert quoteShellPosix("") == "''"
assert quoteShellPosix("a'a") == "'a'\"'\"'a'" doAssert quoteShellPosix("a'a") == "'a'\"'\"'a'"
block: # quoteShell block: # quoteShell
when defined(posix): when defined(posix):
assert quoteShell("") == "''" doAssert quoteShell("") == "''"
block: # normalizePathEnd block: # normalizePathEnd
# handle edge cases correctly: shouldn't affect whether path is # handle edge cases correctly: shouldn't affect whether path is

View file

@ -24,8 +24,8 @@ when not defined(js):
var config2 = loadConfig(file) var config2 = loadConfig(file)
let bar = config2.getSectionValue("foo", "bar") let bar = config2.getSectionValue("foo", "bar")
let foo = config2.getSectionValue("foo", "foo") let foo = config2.getSectionValue("foo", "foo")
assert(bar == "-1") doAssert(bar == "-1")
assert(foo == "abc") doAssert(foo == "abc")
## Creating a configuration file. ## Creating a configuration file.
var dict1 = newConfig() var dict1 = newConfig()

View file

@ -27,7 +27,7 @@ for kind, key, val in getopt():
of "version", "v": writeVersion() of "version", "v": writeVersion()
else: else:
writeLine(stdout, "Unknown command line option: ", key, ": ", val) writeLine(stdout, "Unknown command line option: ", key, ": ", val)
of cmdEnd: assert(false) # cannot happen of cmdEnd: doAssert(false) # cannot happen
if filename == "": if filename == "":
# no filename has been given, so we show the help: # no filename has been given, so we show the help:
writeHelp() writeHelp()

View file

@ -146,4 +146,4 @@ block:
echo "Event parser output" echo "Event parser output"
echo "-------------------" echo "-------------------"
let pLen = parseArithExpr(txt) let pLen = parseArithExpr(txt)
assert txt.len == pLen doAssert txt.len == pLen

View file

@ -1,5 +1,5 @@
import punycode import punycode
assert(decode(encode("", "bücher")) == "bücher") doAssert(decode(encode("", "bücher")) == "bücher")
assert(decode(encode("münchen")) == "münchen") doAssert(decode(encode("münchen")) == "münchen")
assert encode("xn--", "münchen") == "xn--mnchen-3ya" doAssert encode("xn--", "münchen") == "xn--mnchen-3ya"

View file

@ -9,90 +9,90 @@ var
m1 = -1 // 1 m1 = -1 // 1
tt = 10 // 2 tt = 10 // 2
assert(a == a) doAssert(a == a)
assert( (a-a) == z) doAssert( (a-a) == z)
assert( (a+b) == o) doAssert( (a+b) == o)
assert( (a/b) == o) doAssert( (a/b) == o)
assert( (a*b) == 1 // 4) doAssert( (a*b) == 1 // 4)
assert( (3/a) == 6 // 1) doAssert( (3/a) == 6 // 1)
assert( (a/3) == 1 // 6) doAssert( (a/3) == 1 // 6)
assert(a*b == 1 // 4) doAssert(a*b == 1 // 4)
assert(tt*z == z) doAssert(tt*z == z)
assert(10*a == tt) doAssert(10*a == tt)
assert(a*10 == tt) doAssert(a*10 == tt)
assert(tt/10 == a) doAssert(tt/10 == a)
assert(a-m1 == 3 // 2) doAssert(a-m1 == 3 // 2)
assert(a+m1 == -1 // 2) doAssert(a+m1 == -1 // 2)
assert(m1+tt == 16 // 4) doAssert(m1+tt == 16 // 4)
assert(m1-tt == 6 // -1) doAssert(m1-tt == 6 // -1)
assert(z < o) doAssert(z < o)
assert(z <= o) doAssert(z <= o)
assert(z == z) doAssert(z == z)
assert(cmp(z, o) < 0) doAssert(cmp(z, o) < 0)
assert(cmp(o, z) > 0) doAssert(cmp(o, z) > 0)
assert(o == o) doAssert(o == o)
assert(o >= o) doAssert(o >= o)
assert(not(o > o)) doAssert(not(o > o))
assert(cmp(o, o) == 0) doAssert(cmp(o, o) == 0)
assert(cmp(z, z) == 0) doAssert(cmp(z, z) == 0)
assert(hash(o) == hash(o)) doAssert(hash(o) == hash(o))
assert(a == b) doAssert(a == b)
assert(a >= b) doAssert(a >= b)
assert(not(b > a)) doAssert(not(b > a))
assert(cmp(a, b) == 0) doAssert(cmp(a, b) == 0)
assert(hash(a) == hash(b)) doAssert(hash(a) == hash(b))
var x = 1//3 var x = 1//3
x *= 5//1 x *= 5//1
assert(x == 5//3) doAssert(x == 5//3)
x += 2 // 9 x += 2 // 9
assert(x == 17//9) doAssert(x == 17//9)
x -= 9//18 x -= 9//18
assert(x == 25//18) doAssert(x == 25//18)
x /= 1//2 x /= 1//2
assert(x == 50//18) doAssert(x == 50//18)
var y = 1//3 var y = 1//3
y *= 4 y *= 4
assert(y == 4//3) doAssert(y == 4//3)
y += 5 y += 5
assert(y == 19//3) doAssert(y == 19//3)
y -= 2 y -= 2
assert(y == 13//3) doAssert(y == 13//3)
y /= 9 y /= 9
assert(y == 13//27) doAssert(y == 13//27)
assert toRational(5) == 5//1 doAssert toRational(5) == 5//1
assert abs(toFloat(y) - 0.4814814814814815) < 1.0e-7 doAssert abs(toFloat(y) - 0.4814814814814815) < 1.0e-7
assert toInt(z) == 0 doAssert toInt(z) == 0
when sizeof(int) == 8: when sizeof(int) == 8:
assert toRational(0.98765432) == 2111111029 // 2137499919 doAssert toRational(0.98765432) == 2111111029 // 2137499919
assert toRational(PI) == 817696623 // 260280919 doAssert toRational(PI) == 817696623 // 260280919
when sizeof(int) == 4: when sizeof(int) == 4:
assert toRational(0.98765432) == 80 // 81 doAssert toRational(0.98765432) == 80 // 81
assert toRational(PI) == 355 // 113 doAssert toRational(PI) == 355 // 113
assert toRational(0.1) == 1 // 10 doAssert toRational(0.1) == 1 // 10
assert toRational(0.9) == 9 // 10 doAssert toRational(0.9) == 9 // 10
assert toRational(0.0) == 0 // 1 doAssert toRational(0.0) == 0 // 1
assert toRational(-0.25) == 1 // -4 doAssert toRational(-0.25) == 1 // -4
assert toRational(3.2) == 16 // 5 doAssert toRational(3.2) == 16 // 5
assert toRational(0.33) == 33 // 100 doAssert toRational(0.33) == 33 // 100
assert toRational(0.22) == 11 // 50 doAssert toRational(0.22) == 11 // 50
assert toRational(10.0) == 10 // 1 doAssert toRational(10.0) == 10 // 1
assert (1//1) div (3//10) == 3 doAssert (1//1) div (3//10) == 3
assert (-1//1) div (3//10) == -3 doAssert (-1//1) div (3//10) == -3
assert (3//10) mod (1//1) == 3//10 doAssert (3//10) mod (1//1) == 3//10
assert (-3//10) mod (1//1) == -3//10 doAssert (-3//10) mod (1//1) == -3//10
assert floorDiv(1//1, 3//10) == 3 doAssert floorDiv(1//1, 3//10) == 3
assert floorDiv(-1//1, 3//10) == -4 doAssert floorDiv(-1//1, 3//10) == -4
assert floorMod(3//10, 1//1) == 3//10 doAssert floorMod(3//10, 1//1) == 3//10
assert floorMod(-3//10, 1//1) == 7//10 doAssert floorMod(-3//10, 1//1) == 7//10

View file

@ -16,7 +16,7 @@ suite "RST include directive":
test "Include whole": test "Include whole":
"other.rst".writeFile("**test1**") "other.rst".writeFile("**test1**")
let input = ".. include:: other.rst" let input = ".. include:: other.rst"
assert "<strong>test1</strong>" == rstTohtml(input, {}, defaultConfig()) doAssert "<strong>test1</strong>" == rstTohtml(input, {}, defaultConfig())
removeFile("other.rst") removeFile("other.rst")
test "Include starting from": test "Include starting from":
@ -30,7 +30,7 @@ OtherStart
.. include:: other.rst .. include:: other.rst
:start-after: OtherStart :start-after: OtherStart
""" """
assert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig()) doAssert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig())
removeFile("other.rst") removeFile("other.rst")
test "Include everything before": test "Include everything before":
@ -44,7 +44,7 @@ And this should **NOT** be visible in `docs.html`
.. include:: other.rst .. include:: other.rst
:end-before: OtherEnd :end-before: OtherEnd
""" """
assert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig()) doAssert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig())
removeFile("other.rst") removeFile("other.rst")
@ -62,7 +62,7 @@ And this should **NOT** be visible in `docs.html`
:start-after: OtherStart :start-after: OtherStart
:end-before: OtherEnd :end-before: OtherEnd
""" """
assert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig()) doAssert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig())
removeFile("other.rst") removeFile("other.rst")
@ -82,5 +82,5 @@ And this should **NOT** be visible in `docs.html`
:start-after: OtherStart :start-after: OtherStart
:end-before: OtherEnd :end-before: OtherEnd
""" """
assert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig()) doAssert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig())
removeFile("other.rst") removeFile("other.rst")

View file

@ -22,7 +22,7 @@ suite "YAML syntax highlighting":
: value : value
...""" ..."""
let output = rstTohtml(input, {}, defaultConfig()) let output = rstTohtml(input, {}, defaultConfig())
assert output == """<pre class = "listing"><span class="Directive">%YAML 1.2</span> doAssert output == """<pre class = "listing"><span class="Directive">%YAML 1.2</span>
<span class="Keyword">---</span> <span class="Keyword">---</span>
<span class="StringLit">a string</span><span class="Punctuation">:</span> <span class="StringLit">string</span> <span class="StringLit">a string</span><span class="Punctuation">:</span> <span class="StringLit">string</span>
<span class="StringLit">a list</span><span class="Punctuation">:</span> <span class="StringLit">a list</span><span class="Punctuation">:</span>
@ -48,7 +48,7 @@ suite "YAML syntax highlighting":
|+ # comment after header |+ # comment after header
allowed, since more indented than parent""" allowed, since more indented than parent"""
let output = rstToHtml(input, {}, defaultConfig()) let output = rstToHtml(input, {}, defaultConfig())
assert output == """<pre class = "listing"><span class="StringLit">a literal block scalar</span><span class="Punctuation">:</span> <span class="Command">|</span><span class="Command"></span><span class="LongStringLit"> doAssert output == """<pre class = "listing"><span class="StringLit">a literal block scalar</span><span class="Punctuation">:</span> <span class="Command">|</span><span class="Command"></span><span class="LongStringLit">
some text some text
# not a comment # not a comment
</span><span class="Comment"># a comment, since less indented</span> </span><span class="Comment"># a comment, since less indented</span>
@ -74,7 +74,7 @@ suite "YAML syntax highlighting":
... ...
%TAG ! !foo:""" %TAG ! !foo:"""
let output = rstToHtml(input, {}, defaultConfig()) let output = rstToHtml(input, {}, defaultConfig())
assert output == """<pre class = "listing"><span class="Directive">%YAML 1.2</span> doAssert output == """<pre class = "listing"><span class="Directive">%YAML 1.2</span>
<span class="Keyword">---</span> <span class="Keyword">---</span>
<span class="StringLit">%not a directive</span> <span class="StringLit">%not a directive</span>
<span class="Keyword">...</span> <span class="Keyword">...</span>
@ -95,7 +95,7 @@ suite "YAML syntax highlighting":
not numbers: [ 42e, 0023, +32.37, 8 ball] not numbers: [ 42e, 0023, +32.37, 8 ball]
}""" }"""
let output = rstToHtml(input, {}, defaultConfig()) let output = rstToHtml(input, {}, defaultConfig())
assert output == """<pre class = "listing"><span class="Punctuation">{</span> doAssert output == """<pre class = "listing"><span class="Punctuation">{</span>
<span class="StringLit">&quot;</span><span class="StringLit">quoted string&quot;</span><span class="Punctuation">:</span> <span class="DecNumber">42</span><span class="Punctuation">,</span> <span class="StringLit">&quot;</span><span class="StringLit">quoted string&quot;</span><span class="Punctuation">:</span> <span class="DecNumber">42</span><span class="Punctuation">,</span>
<span class="StringLit">'single quoted string'</span><span class="Punctuation">:</span> <span class="StringLit">false</span><span class="Punctuation">,</span> <span class="StringLit">'single quoted string'</span><span class="Punctuation">:</span> <span class="StringLit">false</span><span class="Punctuation">,</span>
<span class="Punctuation">[</span> <span class="StringLit">list</span><span class="Punctuation">,</span> <span class="StringLit">&quot;</span><span class="StringLit">with&quot;</span><span class="Punctuation">,</span> <span class="StringLit">'entries'</span> <span class="Punctuation">]</span><span class="Punctuation">:</span> <span class="FloatNumber">73.32e-73</span><span class="Punctuation">,</span> <span class="Punctuation">[</span> <span class="StringLit">list</span><span class="Punctuation">,</span> <span class="StringLit">&quot;</span><span class="StringLit">with&quot;</span><span class="Punctuation">,</span> <span class="StringLit">'entries'</span> <span class="Punctuation">]</span><span class="Punctuation">:</span> <span class="FloatNumber">73.32e-73</span><span class="Punctuation">,</span>
@ -112,7 +112,7 @@ suite "YAML syntax highlighting":
alias: *anchor alias: *anchor
""" """
let output = rstToHtml(input, {}, defaultConfig()) let output = rstToHtml(input, {}, defaultConfig())
assert output == """<pre class = "listing"><span class="Keyword">---</span> <span class="TagStart">!!map</span> doAssert output == """<pre class = "listing"><span class="Keyword">---</span> <span class="TagStart">!!map</span>
<span class="TagStart">!!str</span> <span class="StringLit">string</span><span class="Punctuation">:</span> <span class="TagStart">!&lt;tag:yaml.org,2002:int&gt;</span> <span class="DecNumber">42</span> <span class="TagStart">!!str</span> <span class="StringLit">string</span><span class="Punctuation">:</span> <span class="TagStart">!&lt;tag:yaml.org,2002:int&gt;</span> <span class="DecNumber">42</span>
<span class="Punctuation">?</span> <span class="Label">&amp;anchor</span> <span class="TagStart">!!seq</span> <span class="Punctuation">[</span><span class="Punctuation">]</span><span class="Punctuation">:</span> <span class="Punctuation">?</span> <span class="Label">&amp;anchor</span> <span class="TagStart">!!seq</span> <span class="Punctuation">[</span><span class="Punctuation">]</span><span class="Punctuation">:</span>
<span class="Punctuation">:</span> <span class="TagStart">!localtag</span> <span class="StringLit">foo</span> <span class="Punctuation">:</span> <span class="TagStart">!localtag</span> <span class="StringLit">foo</span>
@ -132,7 +132,7 @@ suite "YAML syntax highlighting":
?not a map key ?not a map key
""" """
let output = rstToHtml(input, {}, defaultConfig()) let output = rstToHtml(input, {}, defaultConfig())
assert output == """<pre class = "listing"><span class="Keyword">...</span> doAssert output == """<pre class = "listing"><span class="Keyword">...</span>
<span class="StringLit">%a string</span><span class="Punctuation">:</span> <span class="StringLit">%a string</span><span class="Punctuation">:</span>
<span class="StringLit">a:string:not:a:map</span> <span class="StringLit">a:string:not:a:map</span>
<span class="Keyword">...</span> <span class="Keyword">...</span>
@ -146,7 +146,7 @@ suite "YAML syntax highlighting":
suite "RST/Markdown general": suite "RST/Markdown general":
test "RST emphasis": test "RST emphasis":
assert rstToHtml("*Hello* **world**!", {}, doAssert rstToHtml("*Hello* **world**!", {},
newStringTable(modeStyleInsensitive)) == newStringTable(modeStyleInsensitive)) ==
"<em>Hello</em> <strong>world</strong>!" "<em>Hello</em> <strong>world</strong>!"
@ -156,9 +156,9 @@ suite "RST/Markdown general":
b = rstToHtml("(([Nim](https://nim-lang.org/)))", {roSupportMarkdown}, defaultConfig()) b = rstToHtml("(([Nim](https://nim-lang.org/)))", {roSupportMarkdown}, defaultConfig())
c = rstToHtml("[[Nim](https://nim-lang.org/)]", {roSupportMarkdown}, defaultConfig()) c = rstToHtml("[[Nim](https://nim-lang.org/)]", {roSupportMarkdown}, defaultConfig())
assert a == """(( <a class="reference external" href="https://nim-lang.org/">Nim</a> ))""" doAssert a == """(( <a class="reference external" href="https://nim-lang.org/">Nim</a> ))"""
assert b == """((<a class="reference external" href="https://nim-lang.org/">Nim</a>))""" doAssert b == """((<a class="reference external" href="https://nim-lang.org/">Nim</a>))"""
assert c == """[<a class="reference external" href="https://nim-lang.org/">Nim</a>]""" doAssert c == """[<a class="reference external" href="https://nim-lang.org/">Nim</a>]"""
test "Markdown tables": test "Markdown tables":
let input1 = """ let input1 = """
@ -170,7 +170,7 @@ suite "RST/Markdown general":
| | F2 without pipe | | F2 without pipe
not in table""" not in table"""
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
assert output1 == """<table border="1" class="docutils"><tr><th>A1 header</th><th>A2 | not fooled</th></tr> doAssert output1 == """<table border="1" class="docutils"><tr><th>A1 header</th><th>A2 | not fooled</th></tr>
<tr><td>C1</td><td>C2 <strong>bold</strong></td></tr> <tr><td>C1</td><td>C2 <strong>bold</strong></td></tr>
<tr><td>D1 <tt class="docutils literal"><span class="pre">code |</span></tt></td><td>D2</td></tr> <tr><td>D1 <tt class="docutils literal"><span class="pre">code |</span></tt></td><td>D2</td></tr>
<tr><td>E1 | text</td><td></td></tr> <tr><td>E1 | text</td><td></td></tr>
@ -181,7 +181,7 @@ not in table"""
| A1 header | A2 | | A1 header | A2 |
| --- | --- |""" | --- | --- |"""
let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig()) let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig())
assert output2 == """<table border="1" class="docutils"><tr><th>A1 header</th><th>A2</th></tr> doAssert output2 == """<table border="1" class="docutils"><tr><th>A1 header</th><th>A2</th></tr>
</table>""" </table>"""
test "RST tables": test "RST tables":
@ -197,10 +197,10 @@ A2 A3
A4 A5 A4 A5
==== === """ ==== === """
let output1 = rstToLatex(input1, {}) let output1 = rstToLatex(input1, {})
assert "{|X|X|}" in output1 # 2 columns doAssert "{|X|X|}" in output1 # 2 columns
assert count(output1, "\\\\") == 4 # 4 rows doAssert count(output1, "\\\\") == 4 # 4 rows
for cell in ["H0", "H1", "A0", "A1", "A2", "A3", "A4", "A5"]: for cell in ["H0", "H1", "A0", "A1", "A2", "A3", "A4", "A5"]:
assert cell in output1 doAssert cell in output1
let input2 = """ let input2 = """
Now test 3 columns / 2 rows, and also borders containing 4 =, 3 =, 1 = signs: Now test 3 columns / 2 rows, and also borders containing 4 =, 3 =, 1 = signs:
@ -212,10 +212,10 @@ A0 A1 X
Ax Y Ax Y
==== === = """ ==== === = """
let output2 = rstToLatex(input2, {}) let output2 = rstToLatex(input2, {})
assert "{|X|X|X|}" in output2 # 3 columns doAssert "{|X|X|X|}" in output2 # 3 columns
assert count(output2, "\\\\") == 2 # 2 rows doAssert count(output2, "\\\\") == 2 # 2 rows
for cell in ["H0", "H1", "H", "A0", "A1", "X", "Ax", "Y"]: for cell in ["H0", "H1", "H", "A0", "A1", "X", "Ax", "Y"]:
assert cell in output2 doAssert cell in output2
test "RST adornments": test "RST adornments":
@ -231,7 +231,7 @@ Long chapter name
''''''''''''''''''' '''''''''''''''''''
""" """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
assert "Long chapter name" in output1 and "<h1" in output1 doAssert "Long chapter name" in output1 and "<h1" in output1
let input2 = """ let input2 = """
Short chapter name: Short chapter name:
@ -240,7 +240,7 @@ ChA
=== ===
""" """
let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig()) let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig())
assert "ChA" in output2 and "<h1" in output2 doAssert "ChA" in output2 and "<h1" in output2
let input3 = """ let input3 = """
Very short chapter name: Very short chapter name:
@ -249,7 +249,7 @@ X
~ ~
""" """
let output3 = rstToHtml(input3, {roSupportMarkdown}, defaultConfig()) let output3 = rstToHtml(input3, {roSupportMarkdown}, defaultConfig())
assert "X" in output3 and "<h1" in output3 doAssert "X" in output3 and "<h1" in output3
let input4 = """ let input4 = """
Check that short underline is not enough to make section: Check that short underline is not enough to make section:
@ -259,7 +259,7 @@ Wrong chapter
""" """
let output4 = rstToHtml(input4, {roSupportMarkdown}, defaultConfig()) let output4 = rstToHtml(input4, {roSupportMarkdown}, defaultConfig())
assert "Wrong chapter" in output4 and "<h1" notin output4 doAssert "Wrong chapter" in output4 and "<h1" notin output4
let input5 = """ let input5 = """
Check that punctuation after adornment and indent are not detected as adornment. Check that punctuation after adornment and indent are not detected as adornment.
@ -269,7 +269,7 @@ Some chapter
"punctuation symbols" """ "punctuation symbols" """
let output5 = rstToHtml(input5, {roSupportMarkdown}, defaultConfig()) let output5 = rstToHtml(input5, {roSupportMarkdown}, defaultConfig())
assert "&quot;punctuation symbols&quot;" in output5 and "<h1" in output5 doAssert "&quot;punctuation symbols&quot;" in output5 and "<h1" in output5
test "RST links": test "RST links":
@ -278,7 +278,7 @@ Want to learn about `my favorite programming language`_?
.. _my favorite programming language: https://nim-lang.org""" .. _my favorite programming language: https://nim-lang.org"""
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
assert "<a" in output1 and "href=\"https://nim-lang.org\"" in output1 doAssert "<a" in output1 and "href=\"https://nim-lang.org\"" in output1
test "RST transitions": test "RST transitions":
let input1 = """ let input1 = """
@ -289,7 +289,7 @@ context1
context2 context2
""" """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
assert "<hr" in output1 doAssert "<hr" in output1
let input2 = """ let input2 = """
This is too short to be a transition: This is too short to be a transition:
@ -299,7 +299,7 @@ This is too short to be a transition:
context2 context2
""" """
let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig()) let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig())
assert "<hr" notin output2 doAssert "<hr" notin output2
test "RST literal block": test "RST literal block":
let input1 = """ let input1 = """
@ -309,7 +309,7 @@ Test literal block
check """ check """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
assert "<pre>" in output1 doAssert "<pre>" in output1
test "Markdown code block": test "Markdown code block":
let input1 = """ let input1 = """
@ -317,7 +317,7 @@ Test literal block
let x = 1 let x = 1
``` """ ``` """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
assert "<pre" in output1 and "class=\"Keyword\"" notin output1 doAssert "<pre" in output1 and "class=\"Keyword\"" notin output1
let input2 = """ let input2 = """
Parse the block with language specifier: Parse the block with language specifier:
@ -325,7 +325,7 @@ Parse the block with language specifier:
let x = 1 let x = 1
``` """ ``` """
let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig()) let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig())
assert "<pre" in output2 and "class=\"Keyword\"" in output2 doAssert "<pre" in output2 and "class=\"Keyword\"" in output2
test "RST comments": test "RST comments":
let input1 = """ let input1 = """
@ -334,7 +334,7 @@ Check that comment disappears:
.. ..
some comment """ some comment """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
assert output1 == "Check that comment disappears:" doAssert output1 == "Check that comment disappears:"
test "RST line blocks": test "RST line blocks":
let input1 = """ let input1 = """
@ -353,13 +353,13 @@ Test1
var output1: string var output1: string
rstGenera.initRstGenerator(outHtml, defaultConfig(), "input", {}) rstGenera.initRstGenerator(outHtml, defaultConfig(), "input", {})
rstGenera.renderRstToOut(rstParse(input1, "", 1, 1, option, {}), output1) rstGenera.renderRstToOut(rstParse(input1, "", 1, 1, option, {}), output1)
assert rstGenera.meta[metaTitle] == "Test1" doAssert rstGenera.meta[metaTitle] == "Test1"
# check that title was not overwritten to '|' # check that title was not overwritten to '|'
assert "line block<br />" in output1 doAssert "line block<br />" in output1
assert "other line<br />" in output1 doAssert "other line<br />" in output1
let output1l = rstToLatex(input1, {}) let output1l = rstToLatex(input1, {})
assert "line block\\\\" in output1l doAssert "line block\\\\" in output1l
assert "other line\\\\" in output1l doAssert "other line\\\\" in output1l
test "RST enumerated lists": test "RST enumerated lists":
let input1 = dedent """ let input1 = dedent """
@ -382,8 +382,8 @@ Test1
""" """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
for i in 1..5: for i in 1..5:
assert ($i & ". line" & $i) notin output1 doAssert ($i & ". line" & $i) notin output1
assert ("<li>line" & $i & " " & $i & "</li>") in output1 doAssert ("<li>line" & $i & " " & $i & "</li>") in output1
let input2 = dedent """ let input2 = dedent """
3. line3 3. line3
@ -404,8 +404,8 @@ Test1
""" """
let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig()) let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig())
for i in [3, 4, 5, 7, 8]: for i in [3, 4, 5, 7, 8]:
assert ($i & ". line" & $i) notin output2 doAssert ($i & ". line" & $i) notin output2
assert ("<li>line" & $i & "</li>") in output2 doAssert ("<li>line" & $i & "</li>") in output2
# check that nested enumerated lists work # check that nested enumerated lists work
let input3 = dedent """ let input3 = dedent """
@ -413,9 +413,9 @@ Test1
2. string2 2. string2
""" """
let output3 = rstToHtml(input3, {roSupportMarkdown}, defaultConfig()) let output3 = rstToHtml(input3, {roSupportMarkdown}, defaultConfig())
assert count(output3, "<ol ") == 2 doAssert count(output3, "<ol ") == 2
assert count(output3, "</ol>") == 2 doAssert count(output3, "</ol>") == 2
assert "<li>string1</li>" in output3 and "<li>string2</li>" in output3 doAssert "<li>string1</li>" in output3 and "<li>string2</li>" in output3
let input4 = dedent """ let input4 = dedent """
Check that enumeration specifiers are respected Check that enumeration specifiers are respected
@ -429,12 +429,12 @@ Test1
e) string6 e) string6
""" """
let output4 = rstToHtml(input4, {roSupportMarkdown}, defaultConfig()) let output4 = rstToHtml(input4, {roSupportMarkdown}, defaultConfig())
assert count(output4, "<ol ") == 4 doAssert count(output4, "<ol ") == 4
assert count(output4, "</ol>") == 4 doAssert count(output4, "</ol>") == 4
for enumerator in [9, 12]: for enumerator in [9, 12]:
assert "start=\"$1\"" % [$enumerator] in output4 doAssert "start=\"$1\"" % [$enumerator] in output4
for enumerator in [2, 5]: # 2=b, 5=e for enumerator in [2, 5]: # 2=b, 5=e
assert "start=\"$1\"" % [$enumerator] in output4 doAssert "start=\"$1\"" % [$enumerator] in output4
let input5 = dedent """ let input5 = dedent """
Check that auto-numbered enumeration lists work. Check that auto-numbered enumeration lists work.
@ -449,9 +449,9 @@ Test1
#) string6 #) string6
""" """
let output5 = rstToHtml(input5, {roSupportMarkdown}, defaultConfig()) let output5 = rstToHtml(input5, {roSupportMarkdown}, defaultConfig())
assert count(output5, "<ol ") == 2 doAssert count(output5, "<ol ") == 2
assert count(output5, "</ol>") == 2 doAssert count(output5, "</ol>") == 2
assert count(output5, "<li>") == 5 doAssert count(output5, "<li>") == 5
let input5a = dedent """ let input5a = dedent """
Auto-numbered RST list can start with 1 even when Markdown support is on. Auto-numbered RST list can start with 1 even when Markdown support is on.
@ -461,9 +461,9 @@ Test1
#. string3 #. string3
""" """
let output5a = rstToHtml(input5a, {roSupportMarkdown}, defaultConfig()) let output5a = rstToHtml(input5a, {roSupportMarkdown}, defaultConfig())
assert count(output5a, "<ol ") == 1 doAssert count(output5a, "<ol ") == 1
assert count(output5a, "</ol>") == 1 doAssert count(output5a, "</ol>") == 1
assert count(output5a, "<li>") == 3 doAssert count(output5a, "<li>") == 3
let input6 = dedent """ let input6 = dedent """
... And for alphabetic enumerators too! ... And for alphabetic enumerators too!
@ -473,10 +473,10 @@ Test1
#. string3 #. string3
""" """
let output6 = rstToHtml(input6, {roSupportMarkdown}, defaultConfig()) let output6 = rstToHtml(input6, {roSupportMarkdown}, defaultConfig())
assert count(output6, "<ol ") == 1 doAssert count(output6, "<ol ") == 1
assert count(output6, "</ol>") == 1 doAssert count(output6, "</ol>") == 1
assert count(output6, "<li>") == 3 doAssert count(output6, "<li>") == 3
assert "start=\"2\"" in output6 and "class=\"loweralpha simple\"" in output6 doAssert "start=\"2\"" in output6 and "class=\"loweralpha simple\"" in output6
let input7 = dedent """ let input7 = dedent """
... And for uppercase alphabetic enumerators. ... And for uppercase alphabetic enumerators.
@ -486,10 +486,10 @@ Test1
#. string3 #. string3
""" """
let output7 = rstToHtml(input7, {roSupportMarkdown}, defaultConfig()) let output7 = rstToHtml(input7, {roSupportMarkdown}, defaultConfig())
assert count(output7, "<ol ") == 1 doAssert count(output7, "<ol ") == 1
assert count(output7, "</ol>") == 1 doAssert count(output7, "</ol>") == 1
assert count(output7, "<li>") == 3 doAssert count(output7, "<li>") == 3
assert "start=\"3\"" in output7 and "class=\"upperalpha simple\"" in output7 doAssert "start=\"3\"" in output7 and "class=\"upperalpha simple\"" in output7
test "Markdown enumerated lists": test "Markdown enumerated lists":
let input1 = dedent """ let input1 = dedent """
@ -505,10 +505,10 @@ Test1
""" """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
for i in 1..5: for i in 1..5:
assert ($i & ". line" & $i) notin output1 doAssert ($i & ". line" & $i) notin output1
assert ("<li>line" & $i & "</li>") in output1 doAssert ("<li>line" & $i & "</li>") in output1
assert count(output1, "<ol ") == 2 doAssert count(output1, "<ol ") == 2
assert count(output1, "</ol>") == 2 doAssert count(output1, "</ol>") == 2
test "RST bullet lists": test "RST bullet lists":
let input1 = dedent """ let input1 = dedent """
@ -531,9 +531,9 @@ Test1
""" """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
for i in 1..5: for i in 1..5:
assert ("<li>line" & $i & " " & $i & "</li>") in output1 doAssert ("<li>line" & $i & " " & $i & "</li>") in output1
assert count(output1, "<ul ") == 1 doAssert count(output1, "<ul ") == 1
assert count(output1, "</ul>") == 1 doAssert count(output1, "</ul>") == 1
test "RST admonitions": test "RST admonitions":
# check that all admonitions are implemented # check that all admonitions are implemented
@ -552,7 +552,7 @@ Test1
let output0 = rstToHtml(input0, {roSupportMarkdown}, defaultConfig()) let output0 = rstToHtml(input0, {roSupportMarkdown}, defaultConfig())
for a in ["admonition", "attention", "caution", "danger", "error", "hint", for a in ["admonition", "attention", "caution", "danger", "error", "hint",
"important", "note", "tip", "warning" ]: "important", "note", "tip", "warning" ]:
assert "endOf " & a & "</div>" in output0 doAssert "endOf " & a & "</div>" in output0
# Test that admonition does not swallow up the next paragraph. # Test that admonition does not swallow up the next paragraph.
let input1 = dedent """ let input1 = dedent """
@ -561,9 +561,9 @@ Test1
Test paragraph. Test paragraph.
""" """
let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig()) let output1 = rstToHtml(input1, {roSupportMarkdown}, defaultConfig())
assert "endOfError</div>" in output1 doAssert "endOfError</div>" in output1
assert "<p>Test paragraph. </p>" in output1 doAssert "<p>Test paragraph. </p>" in output1
assert "class=\"admonition admonition-error\"" in output1 doAssert "class=\"admonition admonition-error\"" in output1
# Test that second line is parsed as continuation of the first line. # Test that second line is parsed as continuation of the first line.
let input2 = dedent """ let input2 = dedent """
@ -573,16 +573,16 @@ Test1
Test paragraph. Test paragraph.
""" """
let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig()) let output2 = rstToHtml(input2, {roSupportMarkdown}, defaultConfig())
assert "endOfError Test2p.</div>" in output2 doAssert "endOfError Test2p.</div>" in output2
assert "<p>Test paragraph. </p>" in output2 doAssert "<p>Test paragraph. </p>" in output2
assert "class=\"admonition admonition-error\"" in output2 doAssert "class=\"admonition admonition-error\"" in output2
let input3 = dedent """ let input3 = dedent """
.. note:: endOfNote .. note:: endOfNote
""" """
let output3 = rstToHtml(input3, {roSupportMarkdown}, defaultConfig()) let output3 = rstToHtml(input3, {roSupportMarkdown}, defaultConfig())
assert "endOfNote</div>" in output3 doAssert "endOfNote</div>" in output3
assert "class=\"admonition admonition-info\"" in output3 doAssert "class=\"admonition admonition-info\"" in output3
suite "RST/Code highlight": suite "RST/Code highlight":
test "Basic Python code highlight": test "Basic Python code highlight":

View file

@ -15,7 +15,7 @@ block: # concat test
s2 = @[4, 5] s2 = @[4, 5]
s3 = @[6, 7] s3 = @[6, 7]
total = concat(s1, s2, s3) total = concat(s1, s2, s3)
assert total == @[1, 2, 3, 4, 5, 6, 7] doAssert total == @[1, 2, 3, 4, 5, 6, 7]
block: # count test block: # count test
let let
@ -35,18 +35,18 @@ block: # count test
ar3 = count(a2, 'y') ar3 = count(a2, 'y')
ar4 = count(a2, 'x') ar4 = count(a2, 'x')
ar5 = count(a2, 'a') ar5 = count(a2, 'a')
assert r0 == 0 doAssert r0 == 0
assert r1 == 1 doAssert r1 == 1
assert r2 == 2 doAssert r2 == 2
assert r3 == 0 doAssert r3 == 0
assert r4 == 1 doAssert r4 == 1
assert r5 == 2 doAssert r5 == 2
assert ar0 == 0 doAssert ar0 == 0
assert ar1 == 1 doAssert ar1 == 1
assert ar2 == 2 doAssert ar2 == 2
assert ar3 == 0 doAssert ar3 == 0
assert ar4 == 1 doAssert ar4 == 1
assert ar5 == 2 doAssert ar5 == 2
block: # cycle tests block: # cycle tests
let let
@ -62,9 +62,9 @@ block: # cycle tests
doAssert c.cycle(0) == @[] doAssert c.cycle(0) == @[]
block: # repeat tests block: # repeat tests
assert repeat(10, 5) == @[10, 10, 10, 10, 10] doAssert repeat(10, 5) == @[10, 10, 10, 10, 10]
assert repeat(@[1, 2, 3], 2) == @[@[1, 2, 3], @[1, 2, 3]] doAssert repeat(@[1, 2, 3], 2) == @[@[1, 2, 3], @[1, 2, 3]]
assert repeat([1, 2, 3], 2) == @[[1, 2, 3], [1, 2, 3]] doAssert repeat([1, 2, 3], 2) == @[[1, 2, 3], [1, 2, 3]]
block: # deduplicates test block: # deduplicates test
let let
@ -80,14 +80,14 @@ block: # deduplicates test
unique6 = deduplicate(dup2, true) unique6 = deduplicate(dup2, true)
unique7 = deduplicate(dup3.sorted, true) unique7 = deduplicate(dup3.sorted, true)
unique8 = deduplicate(dup4, true) unique8 = deduplicate(dup4, true)
assert unique1 == @[1, 3, 4, 2, 8] doAssert unique1 == @[1, 3, 4, 2, 8]
assert unique2 == @["a", "c", "d"] doAssert unique2 == @["a", "c", "d"]
assert unique3 == @[1, 3, 4, 2, 8] doAssert unique3 == @[1, 3, 4, 2, 8]
assert unique4 == @["a", "c", "d"] doAssert unique4 == @["a", "c", "d"]
assert unique5 == @[1, 2, 3, 4, 8] doAssert unique5 == @[1, 2, 3, 4, 8]
assert unique6 == @["a", "c", "d"] doAssert unique6 == @["a", "c", "d"]
assert unique7 == @[1, 2, 3, 4, 8] doAssert unique7 == @[1, 2, 3, 4, 8]
assert unique8 == @["a", "c", "d"] doAssert unique8 == @["a", "c", "d"]
block: # zip test block: # zip test
let let
@ -100,29 +100,29 @@ block: # zip test
zip1 = zip(short, long) zip1 = zip(short, long)
zip2 = zip(short, words) zip2 = zip(short, words)
zip3 = zip(ashort, along) zip3 = zip(ashort, along)
assert zip1 == @[(1, 6), (2, 5), (3, 4)] doAssert zip1 == @[(1, 6), (2, 5), (3, 4)]
assert zip2 == @[(1, "one"), (2, "two"), (3, "three")] doAssert zip2 == @[(1, "one"), (2, "two"), (3, "three")]
assert zip3 == @[(1, 6), (2, 5), (3, 4)] doAssert zip3 == @[(1, 6), (2, 5), (3, 4)]
assert zip1[2][1] == 4 doAssert zip1[2][1] == 4
assert zip2[2][1] == "three" doAssert zip2[2][1] == "three"
assert zip3[2][1] == 4 doAssert zip3[2][1] == 4
when (NimMajor, NimMinor) <= (1, 0): when (NimMajor, NimMinor) <= (1, 0):
let let
# In Nim 1.0.x and older, zip returned a seq of tuple strictly # In Nim 1.0.x and older, zip returned a seq of tuple strictly
# with fields named "a" and "b". # with fields named "a" and "b".
zipAb = zip(ashort, awords) zipAb = zip(ashort, awords)
assert zipAb == @[(a: 1, b: "one"), (2, "two"), (3, "three")] doAssert zipAb == @[(a: 1, b: "one"), (2, "two"), (3, "three")]
assert zipAb[2].b == "three" doAssert zipAb[2].b == "three"
else: else:
let let
# As zip returns seq of anonymous tuples, they can be assigned # As zip returns seq of anonymous tuples, they can be assigned
# to any variable that's a sequence of named tuples too. # to any variable that's a sequence of named tuples too.
zipXy: seq[tuple[x: int, y: string]] = zip(ashort, awords) zipXy: seq[tuple[x: int, y: string]] = zip(ashort, awords)
zipMn: seq[tuple[m: int, n: string]] = zip(ashort, words) zipMn: seq[tuple[m: int, n: string]] = zip(ashort, words)
assert zipXy == @[(x: 1, y: "one"), (2, "two"), (3, "three")] doAssert zipXy == @[(x: 1, y: "one"), (2, "two"), (3, "three")]
assert zipMn == @[(m: 1, n: "one"), (2, "two"), (3, "three")] doAssert zipMn == @[(m: 1, n: "one"), (2, "two"), (3, "three")]
assert zipXy[2].y == "three" doAssert zipXy[2].y == "three"
assert zipMn[2].n == "three" doAssert zipMn[2].n == "three"
block: # distribute tests block: # distribute tests
let numbers = @[1, 2, 3, 4, 5, 6, 7] let numbers = @[1, 2, 3, 4, 5, 6, 7]
@ -156,13 +156,13 @@ block: # map test
anumbers = [1, 4, 5, 8, 9, 7, 4] anumbers = [1, 4, 5, 8, 9, 7, 4]
m1 = map(numbers, proc(x: int): int = 2*x) m1 = map(numbers, proc(x: int): int = 2*x)
m2 = map(anumbers, proc(x: int): int = 2*x) m2 = map(anumbers, proc(x: int): int = 2*x)
assert m1 == @[2, 8, 10, 16, 18, 14, 8] doAssert m1 == @[2, 8, 10, 16, 18, 14, 8]
assert m2 == @[2, 8, 10, 16, 18, 14, 8] doAssert m2 == @[2, 8, 10, 16, 18, 14, 8]
block: # apply test block: # apply test
var a = @["1", "2", "3", "4"] var a = @["1", "2", "3", "4"]
apply(a, proc(x: var string) = x &= "42") apply(a, proc(x: var string) = x &= "42")
assert a == @["142", "242", "342", "442"] doAssert a == @["142", "242", "342", "442"]
block: # filter proc test block: # filter proc test
let let
@ -172,34 +172,34 @@ block: # filter proc test
f2 = filter(colors) do (x: string) -> bool: x.len > 5 f2 = filter(colors) do (x: string) -> bool: x.len > 5
f3 = filter(acolors, proc(x: string): bool = x.len < 6) f3 = filter(acolors, proc(x: string): bool = x.len < 6)
f4 = filter(acolors) do (x: string) -> bool: x.len > 5 f4 = filter(acolors) do (x: string) -> bool: x.len > 5
assert f1 == @["red", "black"] doAssert f1 == @["red", "black"]
assert f2 == @["yellow"] doAssert f2 == @["yellow"]
assert f3 == @["red", "black"] doAssert f3 == @["red", "black"]
assert f4 == @["yellow"] doAssert f4 == @["yellow"]
block: # filter iterator test block: # filter iterator test
let numbers = @[1, 4, 5, 8, 9, 7, 4] let numbers = @[1, 4, 5, 8, 9, 7, 4]
let anumbers = [1, 4, 5, 8, 9, 7, 4] let anumbers = [1, 4, 5, 8, 9, 7, 4]
assert toSeq(filter(numbers, proc (x: int): bool = x mod 2 == 0)) == doAssert toSeq(filter(numbers, proc (x: int): bool = x mod 2 == 0)) ==
@[4, 8, 4] @[4, 8, 4]
assert toSeq(filter(anumbers, proc (x: int): bool = x mod 2 == 0)) == doAssert toSeq(filter(anumbers, proc (x: int): bool = x mod 2 == 0)) ==
@[4, 8, 4] @[4, 8, 4]
block: # keepIf test block: # keepIf test
var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1] var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1]
keepIf(floats, proc(x: float): bool = x > 10) keepIf(floats, proc(x: float): bool = x > 10)
assert floats == @[13.0, 12.5, 10.1] doAssert floats == @[13.0, 12.5, 10.1]
block: # delete tests block: # delete tests
let outcome = @[1, 1, 1, 1, 1, 1, 1, 1] let outcome = @[1, 1, 1, 1, 1, 1, 1, 1]
var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1] var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
dest.delete(3, 8) dest.delete(3, 8)
assert outcome == dest, """\ doAssert outcome == dest, """\
Deleting range 3-9 from [1,1,1,2,2,2,2,2,2,1,1,1,1,1] Deleting range 3-9 from [1,1,1,2,2,2,2,2,2,1,1,1,1,1]
is [1,1,1,1,1,1,1,1]""" is [1,1,1,1,1,1,1,1]"""
var x = @[1, 2, 3] var x = @[1, 2, 3]
x.delete(100, 100) x.delete(100, 100)
assert x == @[1, 2, 3] doAssert x == @[1, 2, 3]
block: # insert tests block: # insert tests
var dest = @[1, 1, 1, 1, 1, 1, 1, 1] var dest = @[1, 1, 1, 1, 1, 1, 1, 1]
@ -207,7 +207,7 @@ block: # insert tests
src = @[2, 2, 2, 2, 2, 2] src = @[2, 2, 2, 2, 2, 2]
outcome = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1] outcome = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
dest.insert(src, 3) dest.insert(src, 3)
assert dest == outcome, """\ doAssert dest == outcome, """\
Inserting [2,2,2,2,2,2] into [1,1,1,1,1,1,1,1] Inserting [2,2,2,2,2,2] into [1,1,1,1,1,1,1,1]
at 3 is [1,1,1,2,2,2,2,2,2,1,1,1,1,1]""" at 3 is [1,1,1,2,2,2,2,2,2,1,1,1,1,1]"""
@ -216,57 +216,57 @@ block: # filterIt test
temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44] temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44]
acceptable = filterIt(temperatures, it < 50 and it > -10) acceptable = filterIt(temperatures, it < 50 and it > -10)
notAcceptable = filterIt(temperatures, it > 50 or it < -10) notAcceptable = filterIt(temperatures, it > 50 or it < -10)
assert acceptable == @[-2.0, 24.5, 44.31] doAssert acceptable == @[-2.0, 24.5, 44.31]
assert notAcceptable == @[-272.15, 99.9, -113.44] doAssert notAcceptable == @[-272.15, 99.9, -113.44]
block: # keepItIf test block: # keepItIf test
var candidates = @["foo", "bar", "baz", "foobar"] var candidates = @["foo", "bar", "baz", "foobar"]
keepItIf(candidates, it.len == 3 and it[0] == 'b') keepItIf(candidates, it.len == 3 and it[0] == 'b')
assert candidates == @["bar", "baz"] doAssert candidates == @["bar", "baz"]
block: # all block: # all
let let
numbers = @[1, 4, 5, 8, 9, 7, 4] numbers = @[1, 4, 5, 8, 9, 7, 4]
anumbers = [1, 4, 5, 8, 9, 7, 4] anumbers = [1, 4, 5, 8, 9, 7, 4]
len0seq: seq[int] = @[] len0seq: seq[int] = @[]
assert all(numbers, proc (x: int): bool = return x < 10) == true doAssert all(numbers, proc (x: int): bool = return x < 10) == true
assert all(numbers, proc (x: int): bool = return x < 9) == false doAssert all(numbers, proc (x: int): bool = return x < 9) == false
assert all(len0seq, proc (x: int): bool = return false) == true doAssert all(len0seq, proc (x: int): bool = return false) == true
assert all(anumbers, proc (x: int): bool = return x < 10) == true doAssert all(anumbers, proc (x: int): bool = return x < 10) == true
assert all(anumbers, proc (x: int): bool = return x < 9) == false doAssert all(anumbers, proc (x: int): bool = return x < 9) == false
block: # allIt block: # allIt
let let
numbers = @[1, 4, 5, 8, 9, 7, 4] numbers = @[1, 4, 5, 8, 9, 7, 4]
anumbers = [1, 4, 5, 8, 9, 7, 4] anumbers = [1, 4, 5, 8, 9, 7, 4]
len0seq: seq[int] = @[] len0seq: seq[int] = @[]
assert allIt(numbers, it < 10) == true doAssert allIt(numbers, it < 10) == true
assert allIt(numbers, it < 9) == false doAssert allIt(numbers, it < 9) == false
assert allIt(len0seq, false) == true doAssert allIt(len0seq, false) == true
assert allIt(anumbers, it < 10) == true doAssert allIt(anumbers, it < 10) == true
assert allIt(anumbers, it < 9) == false doAssert allIt(anumbers, it < 9) == false
block: # any block: # any
let let
numbers = @[1, 4, 5, 8, 9, 7, 4] numbers = @[1, 4, 5, 8, 9, 7, 4]
anumbers = [1, 4, 5, 8, 9, 7, 4] anumbers = [1, 4, 5, 8, 9, 7, 4]
len0seq: seq[int] = @[] len0seq: seq[int] = @[]
assert any(numbers, proc (x: int): bool = return x > 8) == true doAssert any(numbers, proc (x: int): bool = return x > 8) == true
assert any(numbers, proc (x: int): bool = return x > 9) == false doAssert any(numbers, proc (x: int): bool = return x > 9) == false
assert any(len0seq, proc (x: int): bool = return true) == false doAssert any(len0seq, proc (x: int): bool = return true) == false
assert any(anumbers, proc (x: int): bool = return x > 8) == true doAssert any(anumbers, proc (x: int): bool = return x > 8) == true
assert any(anumbers, proc (x: int): bool = return x > 9) == false doAssert any(anumbers, proc (x: int): bool = return x > 9) == false
block: # anyIt block: # anyIt
let let
numbers = @[1, 4, 5, 8, 9, 7, 4] numbers = @[1, 4, 5, 8, 9, 7, 4]
anumbers = [1, 4, 5, 8, 9, 7, 4] anumbers = [1, 4, 5, 8, 9, 7, 4]
len0seq: seq[int] = @[] len0seq: seq[int] = @[]
assert anyIt(numbers, it > 8) == true doAssert anyIt(numbers, it > 8) == true
assert anyIt(numbers, it > 9) == false doAssert anyIt(numbers, it > 9) == false
assert anyIt(len0seq, true) == false doAssert anyIt(len0seq, true) == false
assert anyIt(anumbers, it > 8) == true doAssert anyIt(anumbers, it > 8) == true
assert anyIt(anumbers, it > 9) == false doAssert anyIt(anumbers, it > 9) == false
block: # toSeq test block: # toSeq test
block: block:
@ -275,7 +275,7 @@ block: # toSeq test
oddNumbers = toSeq(filter(numeric) do (x: int) -> bool: oddNumbers = toSeq(filter(numeric) do (x: int) -> bool:
if x mod 2 == 1: if x mod 2 == 1:
result = true) result = true)
assert oddNumbers == @[1, 3, 5, 7, 9] doAssert oddNumbers == @[1, 3, 5, 7, 9]
block: block:
doAssert [1, 2].toSeq == @[1, 2] doAssert [1, 2].toSeq == @[1, 2]
@ -350,10 +350,10 @@ block: # foldl tests
multiplication = foldl(numbers, a * b) multiplication = foldl(numbers, a * b)
words = @["nim", "is", "cool"] words = @["nim", "is", "cool"]
concatenation = foldl(words, a & b) concatenation = foldl(words, a & b)
assert addition == 25, "Addition is (((5)+9)+11)" doAssert addition == 25, "Addition is (((5)+9)+11)"
assert subtraction == -15, "Subtraction is (((5)-9)-11)" doAssert subtraction == -15, "Subtraction is (((5)-9)-11)"
assert multiplication == 495, "Multiplication is (((5)*9)*11)" doAssert multiplication == 495, "Multiplication is (((5)*9)*11)"
assert concatenation == "nimiscool" doAssert concatenation == "nimiscool"
block: # foldr tests block: # foldr tests
let let
@ -363,10 +363,10 @@ block: # foldr tests
multiplication = foldr(numbers, a * b) multiplication = foldr(numbers, a * b)
words = @["nim", "is", "cool"] words = @["nim", "is", "cool"]
concatenation = foldr(words, a & b) concatenation = foldr(words, a & b)
assert addition == 25, "Addition is (5+(9+(11)))" doAssert addition == 25, "Addition is (5+(9+(11)))"
assert subtraction == 7, "Subtraction is (5-(9-(11)))" doAssert subtraction == 7, "Subtraction is (5-(9-(11)))"
assert multiplication == 495, "Multiplication is (5*(9*(11)))" doAssert multiplication == 495, "Multiplication is (5*(9*(11)))"
assert concatenation == "nimiscool" doAssert concatenation == "nimiscool"
doAssert toSeq(1..3).foldr(a + b) == 6 # issue #14404 doAssert toSeq(1..3).foldr(a + b) == 6 # issue #14404
block: # mapIt + applyIt test block: # mapIt + applyIt test
@ -376,8 +376,8 @@ block: # mapIt + applyIt test
strings = nums.identity.mapIt($(4 * it)) strings = nums.identity.mapIt($(4 * it))
doAssert counter == 1 doAssert counter == 1
nums.applyIt(it * 3) nums.applyIt(it * 3)
assert nums[0] + nums[3] == 15 doAssert nums[0] + nums[3] == 15
assert strings[2] == "12" doAssert strings[2] == "12"
block: # newSeqWith tests block: # newSeqWith tests
var seq2D = newSeqWith(4, newSeq[bool](2)) var seq2D = newSeqWith(4, newSeq[bool](2))

View file

@ -11,9 +11,9 @@ block:
init(table) init(table)
table[1] = 10 table[1] = 10
assert table.mget(1) == 10 doAssert table.mget(1) == 10
assert table.mgetOrPut(3, 7) == 7 doAssert table.mgetOrPut(3, 7) == 7
assert table.mgetOrPut(3, 99) == 7 doAssert table.mgetOrPut(3, 99) == 7
deinitSharedTable(table) deinitSharedTable(table)
import sequtils, algorithm import sequtils, algorithm

View file

@ -202,10 +202,10 @@ doAssert fmt"{nat=:3X}" == "nat= 40"
proc my_proc = proc my_proc =
const value = "value" const value = "value"
const a = &"{value}" const a = &"{value}"
assert a == value doAssert a == value
const b = &"{value=}" const b = &"{value=}"
assert b == "value=" & value doAssert b == "value=" & value
my_proc() my_proc()

View file

@ -105,12 +105,12 @@ writeLine(stdout, "length of table ", $tab.len)
block: block:
var x = {"k": "v", "11": "22", "565": "67"}.newStringTable var x = {"k": "v", "11": "22", "565": "67"}.newStringTable
assert x["k"] == "v" doAssert x["k"] == "v"
assert x["11"] == "22" doAssert x["11"] == "22"
assert x["565"] == "67" doAssert x["565"] == "67"
x["11"] = "23" x["11"] = "23"
assert x["11"] == "23" doAssert x["11"] == "23"
x.clear(modeCaseInsensitive) x.clear(modeCaseInsensitive)
x["11"] = "22" x["11"] = "22"
assert x["11"] == "22" doAssert x["11"] == "22"

View file

@ -58,9 +58,9 @@ template main() =
block: # splitLines block: # splitLines
let fixture = "a\nb\rc\r\nd" let fixture = "a\nb\rc\r\nd"
assert len(fixture.splitLines) == 4 doAssert len(fixture.splitLines) == 4
assert splitLines(fixture) == @["a", "b", "c", "d"] doAssert splitLines(fixture) == @["a", "b", "c", "d"]
assert splitLines(fixture, keepEol=true) == @["a\n", "b\r", "c\r\n", "d"] doAssert splitLines(fixture, keepEol=true) == @["a\n", "b\r", "c\r\n", "d"]
block: # rsplit block: # rsplit
doAssert rsplit("foo bar", seps = Whitespace) == @["foo", "bar"] doAssert rsplit("foo bar", seps = Whitespace) == @["foo", "bar"]
@ -83,207 +83,207 @@ template main() =
block: # removeSuffix block: # removeSuffix
var s = "hello\n\r" var s = "hello\n\r"
s.removeSuffix s.removeSuffix
assert s == "hello" doAssert s == "hello"
s.removeSuffix s.removeSuffix
assert s == "hello" doAssert s == "hello"
s = "hello\n\n" s = "hello\n\n"
s.removeSuffix s.removeSuffix
assert s == "hello" doAssert s == "hello"
s = "hello\r" s = "hello\r"
s.removeSuffix s.removeSuffix
assert s == "hello" doAssert s == "hello"
s = "hello \n there" s = "hello \n there"
s.removeSuffix s.removeSuffix
assert s == "hello \n there" doAssert s == "hello \n there"
s = "hello" s = "hello"
s.removeSuffix("llo") s.removeSuffix("llo")
assert s == "he" doAssert s == "he"
s.removeSuffix('e') s.removeSuffix('e')
assert s == "h" doAssert s == "h"
s = "hellos" s = "hellos"
s.removeSuffix({'s','z'}) s.removeSuffix({'s','z'})
assert s == "hello" doAssert s == "hello"
s.removeSuffix({'l','o'}) s.removeSuffix({'l','o'})
assert s == "he" doAssert s == "he"
s = "aeiou" s = "aeiou"
s.removeSuffix("") s.removeSuffix("")
assert s == "aeiou" doAssert s == "aeiou"
s = "" s = ""
s.removeSuffix("") s.removeSuffix("")
assert s == "" doAssert s == ""
s = " " s = " "
s.removeSuffix s.removeSuffix
assert s == " " doAssert s == " "
s = " " s = " "
s.removeSuffix("") s.removeSuffix("")
assert s == " " doAssert s == " "
s = " " s = " "
s.removeSuffix(" ") s.removeSuffix(" ")
assert s == " " doAssert s == " "
s = " " s = " "
s.removeSuffix(' ') s.removeSuffix(' ')
assert s == "" doAssert s == ""
# Contrary to Chomp in other languages # Contrary to Chomp in other languages
# empty string does not change behaviour # empty string does not change behaviour
s = "hello\r\n\r\n" s = "hello\r\n\r\n"
s.removeSuffix("") s.removeSuffix("")
assert s == "hello\r\n\r\n" doAssert s == "hello\r\n\r\n"
block: # removePrefix block: # removePrefix
var s = "\n\rhello" var s = "\n\rhello"
s.removePrefix s.removePrefix
assert s == "hello" doAssert s == "hello"
s.removePrefix s.removePrefix
assert s == "hello" doAssert s == "hello"
s = "\n\nhello" s = "\n\nhello"
s.removePrefix s.removePrefix
assert s == "hello" doAssert s == "hello"
s = "\rhello" s = "\rhello"
s.removePrefix s.removePrefix
assert s == "hello" doAssert s == "hello"
s = "hello \n there" s = "hello \n there"
s.removePrefix s.removePrefix
assert s == "hello \n there" doAssert s == "hello \n there"
s = "hello" s = "hello"
s.removePrefix("hel") s.removePrefix("hel")
assert s == "lo" doAssert s == "lo"
s.removePrefix('l') s.removePrefix('l')
assert s == "o" doAssert s == "o"
s = "hellos" s = "hellos"
s.removePrefix({'h','e'}) s.removePrefix({'h','e'})
assert s == "llos" doAssert s == "llos"
s.removePrefix({'l','o'}) s.removePrefix({'l','o'})
assert s == "s" doAssert s == "s"
s = "aeiou" s = "aeiou"
s.removePrefix("") s.removePrefix("")
assert s == "aeiou" doAssert s == "aeiou"
s = "" s = ""
s.removePrefix("") s.removePrefix("")
assert s == "" doAssert s == ""
s = " " s = " "
s.removePrefix s.removePrefix
assert s == " " doAssert s == " "
s = " " s = " "
s.removePrefix("") s.removePrefix("")
assert s == " " doAssert s == " "
s = " " s = " "
s.removePrefix(" ") s.removePrefix(" ")
assert s == " " doAssert s == " "
s = " " s = " "
s.removePrefix(' ') s.removePrefix(' ')
assert s == "" doAssert s == ""
# Contrary to Chomp in other languages # Contrary to Chomp in other languages
# empty string does not change behaviour # empty string does not change behaviour
s = "\r\n\r\nhello" s = "\r\n\r\nhello"
s.removePrefix("") s.removePrefix("")
assert s == "\r\n\r\nhello" doAssert s == "\r\n\r\nhello"
block: # delete block: # delete
var s = "0123456789ABCDEFGH" var s = "0123456789ABCDEFGH"
delete(s, 4, 5) delete(s, 4, 5)
assert s == "01236789ABCDEFGH" doAssert s == "01236789ABCDEFGH"
delete(s, s.len-1, s.len-1) delete(s, s.len-1, s.len-1)
assert s == "01236789ABCDEFG" doAssert s == "01236789ABCDEFG"
delete(s, 0, 0) delete(s, 0, 0)
assert s == "1236789ABCDEFG" doAssert s == "1236789ABCDEFG"
block: # find block: # find
assert "0123456789ABCDEFGH".find('A') == 10 doAssert "0123456789ABCDEFGH".find('A') == 10
assert "0123456789ABCDEFGH".find('A', 5) == 10 doAssert "0123456789ABCDEFGH".find('A', 5) == 10
assert "0123456789ABCDEFGH".find('A', 5, 10) == 10 doAssert "0123456789ABCDEFGH".find('A', 5, 10) == 10
assert "0123456789ABCDEFGH".find('A', 5, 9) == -1 doAssert "0123456789ABCDEFGH".find('A', 5, 9) == -1
assert "0123456789ABCDEFGH".find("A") == 10 doAssert "0123456789ABCDEFGH".find("A") == 10
assert "0123456789ABCDEFGH".find("A", 5) == 10 doAssert "0123456789ABCDEFGH".find("A", 5) == 10
assert "0123456789ABCDEFGH".find("A", 5, 10) == 10 doAssert "0123456789ABCDEFGH".find("A", 5, 10) == 10
assert "0123456789ABCDEFGH".find("A", 5, 9) == -1 doAssert "0123456789ABCDEFGH".find("A", 5, 9) == -1
assert "0123456789ABCDEFGH".find({'A'..'C'}) == 10 doAssert "0123456789ABCDEFGH".find({'A'..'C'}) == 10
assert "0123456789ABCDEFGH".find({'A'..'C'}, 5) == 10 doAssert "0123456789ABCDEFGH".find({'A'..'C'}, 5) == 10
assert "0123456789ABCDEFGH".find({'A'..'C'}, 5, 10) == 10 doAssert "0123456789ABCDEFGH".find({'A'..'C'}, 5, 10) == 10
assert "0123456789ABCDEFGH".find({'A'..'C'}, 5, 9) == -1 doAssert "0123456789ABCDEFGH".find({'A'..'C'}, 5, 9) == -1
block: # rfind block: # rfind
assert "0123456789ABCDEFGAH".rfind('A') == 17 doAssert "0123456789ABCDEFGAH".rfind('A') == 17
assert "0123456789ABCDEFGAH".rfind('A', last=13) == 10 doAssert "0123456789ABCDEFGAH".rfind('A', last=13) == 10
assert "0123456789ABCDEFGAH".rfind('H', last=13) == -1 doAssert "0123456789ABCDEFGAH".rfind('H', last=13) == -1
assert "0123456789ABCDEFGAH".rfind("A") == 17 doAssert "0123456789ABCDEFGAH".rfind("A") == 17
assert "0123456789ABCDEFGAH".rfind("A", last=13) == 10 doAssert "0123456789ABCDEFGAH".rfind("A", last=13) == 10
assert "0123456789ABCDEFGAH".rfind("H", last=13) == -1 doAssert "0123456789ABCDEFGAH".rfind("H", last=13) == -1
assert "0123456789ABCDEFGAH".rfind({'A'..'C'}) == 17 doAssert "0123456789ABCDEFGAH".rfind({'A'..'C'}) == 17
assert "0123456789ABCDEFGAH".rfind({'A'..'C'}, last=13) == 12 doAssert "0123456789ABCDEFGAH".rfind({'A'..'C'}, last=13) == 12
assert "0123456789ABCDEFGAH".rfind({'G'..'H'}, last=13) == -1 doAssert "0123456789ABCDEFGAH".rfind({'G'..'H'}, last=13) == -1
assert "0123456789ABCDEFGAH".rfind('A', start=18) == -1 doAssert "0123456789ABCDEFGAH".rfind('A', start=18) == -1
assert "0123456789ABCDEFGAH".rfind('A', start=11, last=17) == 17 doAssert "0123456789ABCDEFGAH".rfind('A', start=11, last=17) == 17
assert "0123456789ABCDEFGAH".rfind("0", start=0) == 0 doAssert "0123456789ABCDEFGAH".rfind("0", start=0) == 0
assert "0123456789ABCDEFGAH".rfind("0", start=1) == -1 doAssert "0123456789ABCDEFGAH".rfind("0", start=1) == -1
assert "0123456789ABCDEFGAH".rfind("H", start=11) == 18 doAssert "0123456789ABCDEFGAH".rfind("H", start=11) == 18
assert "0123456789ABCDEFGAH".rfind({'0'..'9'}, start=5) == 9 doAssert "0123456789ABCDEFGAH".rfind({'0'..'9'}, start=5) == 9
assert "0123456789ABCDEFGAH".rfind({'0'..'9'}, start=10) == -1 doAssert "0123456789ABCDEFGAH".rfind({'0'..'9'}, start=10) == -1
assert "/1/2/3".rfind('/') == 4 doAssert "/1/2/3".rfind('/') == 4
assert "/1/2/3".rfind('/', last=1) == 0 doAssert "/1/2/3".rfind('/', last=1) == 0
assert "/1/2/3".rfind('0') == -1 doAssert "/1/2/3".rfind('0') == -1
block: # trimZeros block: # trimZeros
var x = "1200" var x = "1200"
x.trimZeros() x.trimZeros()
assert x == "1200" doAssert x == "1200"
x = "120.0" x = "120.0"
x.trimZeros() x.trimZeros()
assert x == "120" doAssert x == "120"
x = "0." x = "0."
x.trimZeros() x.trimZeros()
assert x == "0" doAssert x == "0"
x = "1.0e2" x = "1.0e2"
x.trimZeros() x.trimZeros()
assert x == "1e2" doAssert x == "1e2"
x = "78.90" x = "78.90"
x.trimZeros() x.trimZeros()
assert x == "78.9" doAssert x == "78.9"
x = "1.23e4" x = "1.23e4"
x.trimZeros() x.trimZeros()
assert x == "1.23e4" doAssert x == "1.23e4"
x = "1.01" x = "1.01"
x.trimZeros() x.trimZeros()
assert x == "1.01" doAssert x == "1.01"
x = "1.1001" x = "1.1001"
x.trimZeros() x.trimZeros()
assert x == "1.1001" doAssert x == "1.1001"
x = "0.0" x = "0.0"
x.trimZeros() x.trimZeros()
assert x == "0" doAssert x == "0"
x = "0.01" x = "0.01"
x.trimZeros() x.trimZeros()
assert x == "0.01" doAssert x == "0.01"
x = "1e0" x = "1e0"
x.trimZeros() x.trimZeros()
assert x == "1e0" doAssert x == "1e0"
block: # countLines block: # countLines
proc assertCountLines(s: string) = assert s.countLines == s.splitLines.len proc assertCountLines(s: string) = doAssert s.countLines == s.splitLines.len
assertCountLines("") assertCountLines("")
assertCountLines("\n") assertCountLines("\n")
assertCountLines("\n\n") assertCountLines("\n\n")
@ -295,36 +295,36 @@ template main() =
block: # parseBinInt, parseHexInt, parseOctInt block: # parseBinInt, parseHexInt, parseOctInt
# binary # binary
assert "0b1111".parseBinInt == 15 doAssert "0b1111".parseBinInt == 15
assert "0B1111".parseBinInt == 15 doAssert "0B1111".parseBinInt == 15
assert "1111".parseBinInt == 15 doAssert "1111".parseBinInt == 15
assert "1110".parseBinInt == 14 doAssert "1110".parseBinInt == 14
assert "1_1_1_1".parseBinInt == 15 doAssert "1_1_1_1".parseBinInt == 15
assert "0b1_1_1_1".parseBinInt == 15 doAssert "0b1_1_1_1".parseBinInt == 15
rejectParse "".parseBinInt rejectParse "".parseBinInt
rejectParse "_".parseBinInt rejectParse "_".parseBinInt
rejectParse "0b".parseBinInt rejectParse "0b".parseBinInt
rejectParse "0b1234".parseBinInt rejectParse "0b1234".parseBinInt
# hex # hex
assert "0x72".parseHexInt == 114 doAssert "0x72".parseHexInt == 114
assert "0X72".parseHexInt == 114 doAssert "0X72".parseHexInt == 114
assert "#72".parseHexInt == 114 doAssert "#72".parseHexInt == 114
assert "72".parseHexInt == 114 doAssert "72".parseHexInt == 114
assert "FF".parseHexInt == 255 doAssert "FF".parseHexInt == 255
assert "ff".parseHexInt == 255 doAssert "ff".parseHexInt == 255
assert "fF".parseHexInt == 255 doAssert "fF".parseHexInt == 255
assert "0x7_2".parseHexInt == 114 doAssert "0x7_2".parseHexInt == 114
rejectParse "".parseHexInt rejectParse "".parseHexInt
rejectParse "_".parseHexInt rejectParse "_".parseHexInt
rejectParse "0x".parseHexInt rejectParse "0x".parseHexInt
rejectParse "0xFFG".parseHexInt rejectParse "0xFFG".parseHexInt
rejectParse "reject".parseHexInt rejectParse "reject".parseHexInt
# octal # octal
assert "0o17".parseOctInt == 15 doAssert "0o17".parseOctInt == 15
assert "0O17".parseOctInt == 15 doAssert "0O17".parseOctInt == 15
assert "17".parseOctInt == 15 doAssert "17".parseOctInt == 15
assert "10".parseOctInt == 8 doAssert "10".parseOctInt == 8
assert "0o1_0_0".parseOctInt == 64 doAssert "0o1_0_0".parseOctInt == 64
rejectParse "".parseOctInt rejectParse "".parseOctInt
rejectParse "_".parseOctInt rejectParse "_".parseOctInt
rejectParse "0o".parseOctInt rejectParse "0o".parseOctInt
@ -333,53 +333,53 @@ template main() =
rejectParse "reject".parseOctInt rejectParse "reject".parseOctInt
block: # parseHexStr block: # parseHexStr
assert "".parseHexStr == "" doAssert "".parseHexStr == ""
assert "00Ff80".parseHexStr == "\0\xFF\x80" doAssert "00Ff80".parseHexStr == "\0\xFF\x80"
try: try:
discard "00Ff8".parseHexStr discard "00Ff8".parseHexStr
assert false, "Should raise ValueError" doAssert false, "Should raise ValueError"
except ValueError: except ValueError:
discard discard
try: try:
discard "0k".parseHexStr discard "0k".parseHexStr
assert false, "Should raise ValueError" doAssert false, "Should raise ValueError"
except ValueError: except ValueError:
discard discard
assert "".toHex == "" doAssert "".toHex == ""
assert "\x00\xFF\x80".toHex == "00FF80" doAssert "\x00\xFF\x80".toHex == "00FF80"
assert "0123456789abcdef".parseHexStr.toHex == "0123456789ABCDEF" doAssert "0123456789abcdef".parseHexStr.toHex == "0123456789ABCDEF"
block: # toHex block: # toHex
assert(toHex(100i16, 32) == "00000000000000000000000000000064") doAssert(toHex(100i16, 32) == "00000000000000000000000000000064")
assert(toHex(-100i16, 32) == "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9C") doAssert(toHex(-100i16, 32) == "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9C")
when not defined js: when not defined js:
assert(toHex(high(uint64)) == "FFFFFFFFFFFFFFFF") doAssert(toHex(high(uint64)) == "FFFFFFFFFFFFFFFF")
assert(toHex(high(uint64), 16) == "FFFFFFFFFFFFFFFF") doAssert(toHex(high(uint64), 16) == "FFFFFFFFFFFFFFFF")
assert(toHex(high(uint64), 32) == "0000000000000000FFFFFFFFFFFFFFFF") doAssert(toHex(high(uint64), 32) == "0000000000000000FFFFFFFFFFFFFFFF")
block: # insertSep block: # insertSep
assert(insertSep($1000_000) == "1_000_000") doAssert(insertSep($1000_000) == "1_000_000")
assert(insertSep($232) == "232") doAssert(insertSep($232) == "232")
assert(insertSep($12345, ',') == "12,345") doAssert(insertSep($12345, ',') == "12,345")
assert(insertSep($0) == "0") doAssert(insertSep($0) == "0")
block: # repeat, spaces block: # repeat, spaces
assert(' '.repeat(8) == " ") doAssert(' '.repeat(8) == " ")
assert(" ".repeat(8) == " ") doAssert(" ".repeat(8) == " ")
assert(spaces(8) == " ") doAssert(spaces(8) == " ")
assert(' '.repeat(0) == "") doAssert(' '.repeat(0) == "")
assert(" ".repeat(0) == "") doAssert(" ".repeat(0) == "")
assert(spaces(0) == "") doAssert(spaces(0) == "")
block: # toBin, toOct block: # toBin, toOct
block:# bug #11369 block:# bug #11369
var num: int64 = -1 var num: int64 = -1
when not defined js: when not defined js:
assert num.toBin(64) == "1111111111111111111111111111111111111111111111111111111111111111" doAssert num.toBin(64) == "1111111111111111111111111111111111111111111111111111111111111111"
assert num.toOct(24) == "001777777777777777777777" doAssert num.toOct(24) == "001777777777777777777777"
block: # replace block: # replace
doAssert "oo".replace("", "abc") == "oo" doAssert "oo".replace("", "abc") == "oo"
@ -499,26 +499,26 @@ template main() =
doAssert parseEnum("invalid enum value", enC) == enC doAssert parseEnum("invalid enum value", enC) == enC
block: # indentation block: # indentation
assert 0 == indentation """ doAssert 0 == indentation """
hey hey
low low
there there
""" """
assert 2 == indentation """ doAssert 2 == indentation """
hey hey
low low
there there
""" """
assert 2 == indentation """ hey doAssert 2 == indentation """ hey
low low
there there
""" """
assert 2 == indentation """ hey doAssert 2 == indentation """ hey
low low
there""" there"""
assert 0 == indentation "" doAssert 0 == indentation ""
assert 0 == indentation " \n \n" doAssert 0 == indentation " \n \n"
assert 0 == indentation " " doAssert 0 == indentation " "
block: # indent block: # indent
doAssert " foo\n bar".indent(4, "Q") == "QQQQ foo\nQQQQ bar" doAssert " foo\n bar".indent(4, "Q") == "QQQQ foo\nQQQQ bar"

View file

@ -47,15 +47,15 @@ doAssert b[1] == 1
import sets, tables import sets, tables
let data = @["bird", "word"] # if this gets stuck in your head, its not my fault let data = @["bird", "word"] # if this gets stuck in your head, its not my fault
assert collect(newSeq, for (i, d) in data.pairs: (if i mod 2 == 0: d)) == @["bird"] doAssert collect(newSeq, for (i, d) in data.pairs: (if i mod 2 == 0: d)) == @["bird"]
assert collect(initTable(2), for (i, d) in data.pairs: {i: d}) == {0: "bird", doAssert collect(initTable(2), for (i, d) in data.pairs: {i: d}) == {0: "bird",
1: "word"}.toTable 1: "word"}.toTable
assert initHashSet.collect(for d in data.items: {d}) == data.toHashSet doAssert initHashSet.collect(for d in data.items: {d}) == data.toHashSet
let x = collect(newSeqOfCap(4)): let x = collect(newSeqOfCap(4)):
for (i, d) in data.pairs: for (i, d) in data.pairs:
if i mod 2 == 0: d if i mod 2 == 0: d
assert x == @["bird"] doAssert x == @["bird"]
# bug #12874 # bug #12874
@ -69,20 +69,20 @@ let bug1 = collect(
d & d d & d
) )
) )
assert bug1 == @["bird", "wordword"] doAssert bug1 == @["bird", "wordword"]
import strutils import strutils
let y = collect(newSeq): let y = collect(newSeq):
for (i, d) in data.pairs: for (i, d) in data.pairs:
try: parseInt(d) except: 0 try: parseInt(d) except: 0
assert y == @[0, 0] doAssert y == @[0, 0]
let z = collect(newSeq): let z = collect(newSeq):
for (i, d) in data.pairs: for (i, d) in data.pairs:
case d case d
of "bird": "word" of "bird": "word"
else: d else: d
assert z == @["word", "word"] doAssert z == @["word", "word"]
proc tforum = proc tforum =
let ans = collect(newSeq): let ans = collect(newSeq):
@ -97,12 +97,12 @@ block:
for d in data.items: for d in data.items:
when d is int: "word" when d is int: "word"
else: d else: d
assert x == @["bird", "word"] doAssert x == @["bird", "word"]
assert collect(for (i, d) in pairs(data): (i, d)) == @[(0, "bird"), (1, "word")] doAssert collect(for (i, d) in pairs(data): (i, d)) == @[(0, "bird"), (1, "word")]
assert collect(for d in data.items: (try: parseInt(d) except: 0)) == @[0, 0] doAssert collect(for d in data.items: (try: parseInt(d) except: 0)) == @[0, 0]
assert collect(for (i, d) in pairs(data): {i: d}) == {1: "word", doAssert collect(for (i, d) in pairs(data): {i: d}) == {1: "word",
0: "bird"}.toTable 0: "bird"}.toTable
assert collect(for d in data.items: {d}) == data.toHashSet doAssert collect(for d in data.items: {d}) == data.toHashSet
# bug #14332 # bug #14332
template foo = template foo =

View file

@ -5,18 +5,18 @@ var epsilon = 1.0
while 1.0 + epsilon != 1.0: while 1.0 + epsilon != 1.0:
epsilon /= 2.0 epsilon /= 2.0
let data = @[1.0, epsilon, -epsilon] let data = @[1.0, epsilon, -epsilon]
assert sumKbn(data) == 1.0 doAssert sumKbn(data) == 1.0
# assert sumPairs(data) != 1.0 # known to fail in 64 bits # doAssert sumPairs(data) != 1.0 # known to fail in 64 bits
assert (1.0 + epsilon) - epsilon != 1.0 doAssert (1.0 + epsilon) - epsilon != 1.0
var tc1: seq[float] var tc1: seq[float]
for n in 1 .. 1000: for n in 1 .. 1000:
tc1.add 1.0 / n.float tc1.add 1.0 / n.float
assert sumKbn(tc1) == 7.485470860550345 doAssert sumKbn(tc1) == 7.485470860550345
assert sumPairs(tc1) == 7.485470860550345 doAssert sumPairs(tc1) == 7.485470860550345
var tc2: seq[float] var tc2: seq[float]
for n in 1 .. 1000: for n in 1 .. 1000:
tc2.add pow(-1.0, n.float) / n.float tc2.add pow(-1.0, n.float) / n.float
assert sumKbn(tc2) == -0.6926474305598203 doAssert sumKbn(tc2) == -0.6926474305598203
assert sumPairs(tc2) == -0.6926474305598204 doAssert sumPairs(tc2) == -0.6926474305598204

View file

@ -59,8 +59,8 @@ block: # Deletion from OrderedTable should account for collision groups. See iss
}.toOrderedTable() }.toOrderedTable()
t.del(key1) t.del(key1)
assert(t.len == 1) doAssert(t.len == 1)
assert(key2 in t) doAssert(key2 in t)
var var
t1 = initCountTable[string]() t1 = initCountTable[string]()
@ -72,9 +72,9 @@ t2.inc("foo", 4)
t2.inc("bar") t2.inc("bar")
t2.inc("baz", 11) t2.inc("baz", 11)
merge(t1, t2) merge(t1, t2)
assert(t1["foo"] == 5) doAssert(t1["foo"] == 5)
assert(t1["bar"] == 3) doAssert(t1["bar"] == 3)
assert(t1["baz"] == 14) doAssert(t1["baz"] == 14)
let let
t1r = newCountTable[string]() t1r = newCountTable[string]()
@ -86,9 +86,9 @@ t2r.inc("foo", 4)
t2r.inc("bar") t2r.inc("bar")
t2r.inc("baz", 11) t2r.inc("baz", 11)
merge(t1r, t2r) merge(t1r, t2r)
assert(t1r["foo"] == 5) doAssert(t1r["foo"] == 5)
assert(t1r["bar"] == 3) doAssert(t1r["bar"] == 3)
assert(t1r["baz"] == 14) doAssert(t1r["baz"] == 14)
var var
t1l = initCountTable[string]() t1l = initCountTable[string]()
@ -127,28 +127,28 @@ block: #5482
var b = newOrderedTable[string, string](initialSize = 2) var b = newOrderedTable[string, string](initialSize = 2)
b["wrong?"] = "foo" b["wrong?"] = "foo"
b["wrong?"] = "foo2" b["wrong?"] = "foo2"
assert a == b doAssert a == b
block: #5482 block: #5482
var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable() var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
var b = newOrderedTable[string, string](initialSize = 2) var b = newOrderedTable[string, string](initialSize = 2)
b["wrong?"] = "foo" b["wrong?"] = "foo"
b["wrong?"] = "foo2" b["wrong?"] = "foo2"
assert a == b doAssert a == b
block: #5487 block: #5487
var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable() var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
var b = newOrderedTable[string, string]() # notice, default size! var b = newOrderedTable[string, string]() # notice, default size!
b["wrong?"] = "foo" b["wrong?"] = "foo"
b["wrong?"] = "foo2" b["wrong?"] = "foo2"
assert a == b doAssert a == b
block: #5487 block: #5487
var a = [("wrong?", "foo"), ("wrong?", "foo2")].newOrderedTable() var a = [("wrong?", "foo"), ("wrong?", "foo2")].newOrderedTable()
var b = newOrderedTable[string, string]() # notice, default size! var b = newOrderedTable[string, string]() # notice, default size!
b["wrong?"] = "foo" b["wrong?"] = "foo"
b["wrong?"] = "foo2" b["wrong?"] = "foo2"
assert a == b doAssert a == b
block: block:
var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable() var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
@ -156,22 +156,22 @@ block:
var c = newOrderedTable[string, string]() # notice, default size! var c = newOrderedTable[string, string]() # notice, default size!
c["wrong?"] = "foo" c["wrong?"] = "foo"
c["wrong?"] = "foo2" c["wrong?"] = "foo2"
assert a == b doAssert a == b
assert a == c doAssert a == c
block: #6250 block: #6250
let let
a = {3: 1}.toOrderedTable a = {3: 1}.toOrderedTable
b = {3: 2}.toOrderedTable b = {3: 2}.toOrderedTable
assert((a == b) == false) doAssert((a == b) == false)
assert((b == a) == false) doAssert((b == a) == false)
block: #6250 block: #6250
let let
a = {3: 2}.toOrderedTable a = {3: 2}.toOrderedTable
b = {3: 2}.toOrderedTable b = {3: 2}.toOrderedTable
assert((a == b) == true) doAssert((a == b) == true)
assert((b == a) == true) doAssert((b == a) == true)
block: # CountTable.smallest block: # CountTable.smallest
let t = toCountTable([0, 0, 5, 5, 5]) let t = toCountTable([0, 0, 5, 5, 5])

View file

@ -17,16 +17,16 @@ var test = @[0,1,2,3,4]
var x = toAny(test) var x = toAny(test)
var y = 78 var y = 78
x[4] = toAny(y) x[4] = toAny(y)
assert x[2].getInt == 2 doAssert x[2].getInt == 2
var test2: tuple[name: string, s: int] = ("test", 56) var test2: tuple[name: string, s: int] = ("test", 56)
var x2 = toAny(test2) var x2 = toAny(test2)
var i = 0 var i = 0
for n, a in fields(x2): for n, a in fields(x2):
case i case i
of 0: assert n == "Field0" and $a.kind == "akString" of 0: doAssert n == "Field0" and $a.kind == "akString"
of 1: assert n == "Field1" and $a.kind == "akInt" of 1: doAssert n == "Field1" and $a.kind == "akInt"
else: assert false else: doAssert false
inc i inc i
var test3: TestObj var test3: TestObj
@ -36,17 +36,17 @@ var x3 = toAny(test3)
i = 0 i = 0
for n, a in fields(x3): for n, a in fields(x3):
case i case i
of 0: assert n == "test" and $a.kind == "akInt" of 0: doAssert n == "test" and $a.kind == "akInt"
of 1: assert n == "asd" and $a.kind == "akInt" of 1: doAssert n == "asd" and $a.kind == "akInt"
of 2: assert n == "test2" and $a.kind == "akEnum" of 2: doAssert n == "test2" and $a.kind == "akEnum"
else: assert false else: doAssert false
inc i inc i
var test4: ref string var test4: ref string
new(test4) new(test4)
test4[] = "test" test4[] = "test"
var x4 = toAny(test4) var x4 = toAny(test4)
assert($x4[].kind() == "akString") doAssert($x4[].kind() == "akString")
block: block:
# gimme a new scope dammit # gimme a new scope dammit

View file

@ -56,7 +56,7 @@ proc defectiveRobot() =
of 1: raise newException(OSError, "CANNOT COMPUTE!") of 1: raise newException(OSError, "CANNOT COMPUTE!")
of 2: discard parseInt("Hello World!") of 2: discard parseInt("Hello World!")
of 3: raise newException(IOError, "I can't do that Dave.") of 3: raise newException(IOError, "I can't do that Dave.")
else: assert 2 + 2 == 5 else: doAssert 2 + 2 == 5
test "unittest expect": test "unittest expect":
expect IOError, OSError, ValueError, AssertionDefect: expect IOError, OSError, ValueError, AssertionDefect:
defectiveRobot() defectiveRobot()

View file

@ -6,15 +6,15 @@ block:
x: XmlNode x: XmlNode
x = <>a(href = "http://nim-lang.org", newText("Nim rules.")) x = <>a(href = "http://nim-lang.org", newText("Nim rules."))
assert $x == """<a href="http://nim-lang.org">Nim rules.</a>""" doAssert $x == """<a href="http://nim-lang.org">Nim rules.</a>"""
x = <>outer(<>inner()) x = <>outer(<>inner())
assert $x == """<outer> doAssert $x == """<outer>
<inner /> <inner />
</outer>""" </outer>"""
x = <>outer(<>middle(<>inner1(), <>inner2(), <>inner3(), <>inner4())) x = <>outer(<>middle(<>inner1(), <>inner2(), <>inner3(), <>inner4()))
assert $x == """<outer> doAssert $x == """<outer>
<middle> <middle>
<inner1 /> <inner1 />
<inner2 /> <inner2 />
@ -24,7 +24,7 @@ block:
</outer>""" </outer>"""
x = <>l0(<>l1(<>l2(<>l3(<>l4())))) x = <>l0(<>l1(<>l2(<>l3(<>l4()))))
assert $x == """<l0> doAssert $x == """<l0>
<l1> <l1>
<l2> <l2>
<l3> <l3>
@ -35,14 +35,14 @@ block:
</l0>""" </l0>"""
x = <>l0(<>l1p1(), <>l1p2(), <>l1p3()) x = <>l0(<>l1p1(), <>l1p2(), <>l1p3())
assert $x == """<l0> doAssert $x == """<l0>
<l1p1 /> <l1p1 />
<l1p2 /> <l1p2 />
<l1p3 /> <l1p3 />
</l0>""" </l0>"""
x = <>l0(<>l1(<>l2p1(), <>l2p2())) x = <>l0(<>l1(<>l2p1(), <>l2p2()))
assert $x == """<l0> doAssert $x == """<l0>
<l1> <l1>
<l2p1 /> <l2p1 />
<l2p2 /> <l2p2 />
@ -50,7 +50,7 @@ block:
</l0>""" </l0>"""
x = <>l0(<>l1(<>l2_1(), <>l2_2(<>l3_1(), <>l3_2(), <>l3_3(<>l4_1(), <>l4_2(), <>l4_3())), <>l2_3(), <>l2_4())) x = <>l0(<>l1(<>l2_1(), <>l2_2(<>l3_1(), <>l3_2(), <>l3_3(<>l4_1(), <>l4_2(), <>l4_3())), <>l2_3(), <>l2_4()))
assert $x == """<l0> doAssert $x == """<l0>
<l1> <l1>
<l2_1 /> <l2_1 />
<l2_2> <l2_2>
@ -72,7 +72,7 @@ block:
middle = newXmlTree("middle", [innermost]) middle = newXmlTree("middle", [innermost])
innermost.add newText("innermost text") innermost.add newText("innermost text")
x = newXmlTree("outer", [middle]) x = newXmlTree("outer", [middle])
assert $x == """<outer> doAssert $x == """<outer>
<middle> <middle>
<innermost>innermost text</innermost> <innermost>innermost text</innermost>
</middle> </middle>
@ -82,4 +82,4 @@ block:
x.add newText("my text") x.add newText("my text")
x.add newElement("sonTag") x.add newElement("sonTag")
x.add newEntity("my entity") x.add newEntity("my entity")
assert $x == "<myTag>my text<sonTag />&my entity;</myTag>" doAssert $x == "<myTag>my text<sonTag />&my entity;</myTag>"

View file

@ -27,22 +27,22 @@ macro m(t: typedesc): typedesc =
result = int result = int
var f: TFoo[int, int] var f: TFoo[int, int]
static: assert(f.y.type.name == "string") static: doAssert(f.y.type.name == "string")
when compiles(f.z): when compiles(f.z):
{.error: "Foo should not have a `z` field".} {.error: "Foo should not have a `z` field".}
proc p(a, b: auto) = proc p(a, b: auto) =
when a.type is int: when a.type is int:
static: assert false static: doAssert false
var f: TFoo[m(a.type), b.type] var f: TFoo[m(a.type), b.type]
static: static:
assert f.x.type.name == "int" doAssert f.x.type.name == "int"
echo f.y.type.name echo f.y.type.name
assert f.y.type.name == "float" doAssert f.y.type.name == "float"
echo f.z.type.name echo f.z.type.name
assert f.z.type.name == "float" doAssert f.z.type.name == "float"
p(A, f) p(A, f)

View file

@ -35,4 +35,4 @@ static:
otherTable["hallo"] = "123" otherTable["hallo"] = "123"
otherTable["welt"] = "456" otherTable["welt"] = "456"
assert otherTable == {"hallo": "123", "welt": "456"}.newTable doAssert otherTable == {"hallo": "123", "welt": "456"}.newTable

View file

@ -25,4 +25,4 @@ block t4952:
static: static:
let tree = newTree(nnkExprColonExpr) let tree = newTree(nnkExprColonExpr)
let t = (n: tree) let t = (n: tree)
assert: t.n.kind == tree.kind doAssert: t.n.kind == tree.kind

View file

@ -7,5 +7,5 @@ static:
var var
x = int64.high x = int64.high
discard x + 1 discard x + 1
assert false doAssert false
p() p()

View file

@ -8,5 +8,5 @@ static:
x = int64.high x = int64.high
y = 1 y = 1
discard x + y discard x + y
assert false doAssert false
p() p()

View file

@ -7,5 +7,5 @@ static:
var var
x = 1'i64 shl 62 x = 1'i64 shl 62
discard x * 2 discard x * 2
assert false doAssert false
p() p()

View file

@ -6,5 +6,5 @@ static:
proc p = proc p =
var x = int64.low var x = int64.low
discard x - 1 discard x - 1
assert false doAssert false
p() p()

View file

@ -8,5 +8,5 @@ static:
x = int64.low x = int64.low
y = 1 y = 1
discard x - y discard x - y
assert false doAssert false
p() p()

View file

@ -47,4 +47,4 @@ macro suite(suiteName, suiteDesc, suiteBloc: untyped): typed =
# Test above # Test above
suite basics, "Description of such": suite basics, "Description of such":
test(t5, ""): test(t5, ""):
assert false doAssert false

View file

@ -9,7 +9,7 @@ var
d = "abc" d = "abc"
static: static:
assert a == 2 doAssert a == 2
assert c == 3 doAssert c == 3
echo b, d echo b, d

View file

@ -22,11 +22,11 @@ import algorithm
static: static:
var numArray = [1, 2, 3, 4, -1] var numArray = [1, 2, 3, 4, -1]
numArray.sort(cmp) numArray.sort(cmp)
assert numArray == [-1, 1, 2, 3, 4] doAssert numArray == [-1, 1, 2, 3, 4]
var str = "cba" var str = "cba"
str.sort(cmp) str.sort(cmp)
assert str == "abc" doAssert str == "abc"
# #6086 # #6086
import math, sequtils, sugar import math, sequtils, sugar
@ -42,7 +42,7 @@ block:
var a = f() var a = f()
const b = f() const b = f()
assert a == b doAssert a == b
block: block:
proc f(): seq[char] = proc f(): seq[char] =
@ -50,7 +50,7 @@ block:
var runTime = f() var runTime = f()
const compTime = f() const compTime = f()
assert runTime == compTime doAssert runTime == compTime
# #6083 # #6083
block: block:
@ -64,24 +64,24 @@ block:
result[i] = tmp result[i] = tmp
const fact1000 = abc() const fact1000 = abc()
assert fact1000 == @[1, 2] doAssert fact1000 == @[1, 2]
# Tests for VM ops # Tests for VM ops
block: block:
static: static:
# for joint test, the project path is different, so I disabled it: # for joint test, the project path is different, so I disabled it:
when false: when false:
assert "vm" in getProjectPath() doAssert "vm" in getProjectPath()
let b = getEnv("UNSETENVVAR") let b = getEnv("UNSETENVVAR")
assert b == "" doAssert b == ""
assert existsEnv("UNSERENVVAR") == false doAssert existsEnv("UNSERENVVAR") == false
putEnv("UNSETENVVAR", "VALUE") putEnv("UNSETENVVAR", "VALUE")
assert getEnv("UNSETENVVAR") == "VALUE" doAssert getEnv("UNSETENVVAR") == "VALUE"
assert existsEnv("UNSETENVVAR") == true doAssert existsEnv("UNSETENVVAR") == true
assert fileExists("MISSINGFILE") == false doAssert fileExists("MISSINGFILE") == false
assert dirExists("MISSINGDIR") == false doAssert dirExists("MISSINGDIR") == false
# #7210 # #7210
block: block:

View file

@ -23,6 +23,6 @@ static:
sameBug(objs) sameBug(objs)
# sameBug(objs) # sameBug(objs)
echo objs[0].field echo objs[0].field
assert(objs[0].field == "hello") # fails, because (objs[0].field == "hello bug") - mutated! doAssert(objs[0].field == "hello") # fails, because (objs[0].field == "hello bug") - mutated!
echo "success" echo "success"

View file

@ -14,4 +14,4 @@ when false:
proc two(dummy: int, size: int) = proc two(dummy: int, size: int) =
var x: array[size * 1, int] # compiles, but shouldn't? var x: array[size * 1, int] # compiles, but shouldn't?
#assert(x.len == size) # just for fun # doAssert(x.len == size) # just for fun