new tester; all tests categorized

This commit is contained in:
Araq 2014-01-13 02:10:03 +01:00
commit 20b5f31c03
481 changed files with 794 additions and 2506 deletions

13
tests/stdlib/tcputime.nim Normal file
View file

@ -0,0 +1,13 @@
import times, os
var e = epochTime()
var c = cpuTime()
os.sleep(1500)
e = epochTime() - e
c = cpuTime() - c
echo "epochTime: ", e, " cpuTime: ", c

View file

@ -0,0 +1,28 @@
discard """
output: '''abc
def
definition
prefix
xyz
def
definition'''
"""
import critbits
when isMainModule:
var r: TCritBitTree[void]
r.incl "abc"
r.incl "xyz"
r.incl "def"
r.incl "definition"
r.incl "prefix"
doAssert r.contains"def"
#r.del "def"
for w in r.items:
echo w
for w in r.itemsWithPrefix("de"):
echo w

17
tests/stdlib/tdialogs.nim Normal file
View file

@ -0,0 +1,17 @@
# Test the dialogs module
import dialogs, gtk2
gtk2.nimrod_init()
var x = ChooseFilesToOpen(nil)
for a in items(x):
writeln(stdout, a)
info(nil, "start with an info box")
warning(nil, "now a warning ...")
error(nil, "... and an error!")
writeln(stdout, ChooseFileToOpen(nil))
writeln(stdout, ChooseFileToSave(nil))
writeln(stdout, ChooseDir(nil))

3
tests/stdlib/techo.nim Normal file
View file

@ -0,0 +1,3 @@
# Simplest Nimrod program
echo "Hello, World!"

12
tests/stdlib/tformat.nim Normal file
View file

@ -0,0 +1,12 @@
discard """
file: "tformat.nim"
output: "Hi Andreas! How do you feel, Rumpf?"
"""
# Tests the new format proc (including the & and &= operators)
import strutils
echo("Hi $1! How do you feel, $2?\n" % ["Andreas", "Rumpf"])
#OUT Hi Andreas! How do you feel, Rumpf?

8
tests/stdlib/thashes.nim Normal file
View file

@ -0,0 +1,8 @@
import unittest
import hashes
suite "hashes":
suite "hashing":
test "0.0 and -0.0 should have the same hash value":
var dummy = 0.0
check hash(dummy) == hash(-dummy)

7
tests/stdlib/tio.nim Normal file
View file

@ -0,0 +1,7 @@
# test the file-IO
proc main() =
for line in lines("thello.nim"):
writeln(stdout, line)
main()

452
tests/stdlib/tircbot.nim Normal file
View file

@ -0,0 +1,452 @@
import irc, sockets, asyncio, json, os, strutils, times, redis
type
TDb* = object
r*: TRedis
lastPing: float
TBuildResult* = enum
bUnknown, bFail, bSuccess
TTestResult* = enum
tUnknown, tFail, tSuccess
TEntry* = tuple[c: TCommit, p: seq[TPlatform]]
TCommit* = object
commitMsg*, username*, hash*: string
date*: TTime
TPlatform* = object
buildResult*: TBuildResult
testResult*: TTestResult
failReason*, platform*: string
total*, passed*, skipped*, failed*: biggestInt
csources*: bool
const
listName = "commits"
failOnExisting = False
proc open*(host = "localhost", port: TPort): TDb =
result.r = redis.open(host, port)
result.lastPing = epochTime()
discard """proc customHSet(database: TDb, name, field, value: string) =
if database.r.hSet(name, field, value).int == 0:
if failOnExisting:
assert(false)
else:
echo("[Warning:REDIS] ", field, " already exists in ", name)"""
proc updateProperty*(database: TDb, commitHash, platform, property,
value: string) =
var name = platform & ":" & commitHash
if database.r.hSet(name, property, value).int == 0:
echo("[INFO:REDIS] '$1' field updated in hash" % [property])
else:
echo("[INFO:REDIS] '$1' new field added to hash" % [property])
proc globalProperty*(database: TDb, commitHash, property, value: string) =
if database.r.hSet(commitHash, property, value).int == 0:
echo("[INFO:REDIS] '$1' field updated in hash" % [property])
else:
echo("[INFO:REDIS] '$1' new field added to hash" % [property])
proc addCommit*(database: TDb, commitHash, commitMsg, user: string) =
# Add the commit hash to the `commits` list.
discard database.r.lPush(listName, commitHash)
# Add the commit message, current date and username as a property
globalProperty(database, commitHash, "commitMsg", commitMsg)
globalProperty(database, commitHash, "date", $int(getTime()))
globalProperty(database, commitHash, "username", user)
proc keepAlive*(database: var TDb) =
## Keep the connection alive. Ping redis in this case. This functions does
## not guarantee that redis will be pinged.
var t = epochTime()
if t - database.lastPing >= 60.0:
echo("PING -> redis")
assert(database.r.ping() == "PONG")
database.lastPing = t
proc getCommits*(database: TDb,
plStr: var seq[string]): seq[TEntry] =
result = @[]
var commitsRaw = database.r.lrange("commits", 0, -1)
for c in items(commitsRaw):
var commit: TCommit
commit.hash = c
for key, value in database.r.hPairs(c):
case normalize(key)
of "commitmsg": commit.commitMsg = value
of "date": commit.date = TTime(parseInt(value))
of "username": commit.username = value
else:
echo(key)
assert(false)
var platformsRaw = database.r.lrange(c & ":platforms", 0, -1)
var platforms: seq[TPlatform] = @[]
for p in items(platformsRaw):
var platform: TPlatform
for key, value in database.r.hPairs(p & ":" & c):
case normalize(key)
of "buildresult":
platform.buildResult = parseInt(value).TBuildResult
of "testresult":
platform.testResult = parseInt(value).TTestResult
of "failreason":
platform.failReason = value
of "total":
platform.total = parseBiggestInt(value)
of "passed":
platform.passed = parseBiggestInt(value)
of "skipped":
platform.skipped = parseBiggestInt(value)
of "failed":
platform.failed = parseBiggestInt(value)
of "csources":
platform.csources = if value == "t": true else: false
else:
echo(normalize(key))
assert(false)
platform.platform = p
platforms.add(platform)
if p notin plStr:
plStr.add(p)
result.add((commit, platforms))
proc commitExists*(database: TDb, commit: string, starts = false): bool =
# TODO: Consider making the 'commits' list a set.
for c in items(database.r.lrange("commits", 0, -1)):
if starts:
if c.startsWith(commit): return true
else:
if c == commit: return true
return false
proc platformExists*(database: TDb, commit: string, platform: string): bool =
for p in items(database.r.lrange(commit & ":" & "platforms", 0, -1)):
if p == platform: return true
proc expandHash*(database: TDb, commit: string): string =
for c in items(database.r.lrange("commits", 0, -1)):
if c.startsWith(commit): return c
assert false
proc isNewest*(database: TDb, commit: string): bool =
return database.r.lIndex("commits", 0) == commit
proc getNewest*(database: TDb): string =
return database.r.lIndex("commits", 0)
proc addPlatform*(database: TDb, commit: string, platform: string) =
assert database.commitExists(commit)
assert (not database.platformExists(commit, platform))
var name = platform & ":" & commit
if database.r.exists(name):
if failOnExisting: quit("[FAIL] " & name & " already exists!", 1)
else: echo("[Warning] " & name & " already exists!")
discard database.r.lPush(commit & ":" & "platforms", platform)
proc `[]`*(p: seq[TPlatform], name: string): TPlatform =
for platform in items(p):
if platform.platform == name:
return platform
raise newException(EInvalidValue, name & " platforms not found in commits.")
proc contains*(p: seq[TPlatform], s: string): bool =
for i in items(p):
if i.platform == s:
return True
type
PState = ref TState
TState = object of TObject
dispatcher: PDispatcher
sock: PAsyncSocket
ircClient: PAsyncIRC
hubPort: TPort
database: TDb
dbConnected: bool
TSeenType = enum
PSeenJoin, PSeenPart, PSeenMsg, PSeenNick, PSeenQuit
TSeen = object
nick: string
channel: string
timestamp: TTime
case kind*: TSeenType
of PSeenJoin: nil
of PSeenPart, PSeenQuit, PSeenMsg:
msg: string
of PSeenNick:
newNick: string
const
ircServer = "irc.freenode.net"
joinChans = @["#nimrod"]
botNickname = "NimBot"
proc setSeen(d: TDb, s: TSeen) =
discard d.r.del("seen:" & s.nick)
var hashToSet = @[("type", $s.kind.int), ("channel", s.channel),
("timestamp", $s.timestamp.int)]
case s.kind
of PSeenJoin: nil
of PSeenPart, PSeenMsg, PSeenQuit:
hashToSet.add(("msg", s.msg))
of PSeenNick:
hashToSet.add(("newnick", s.newNick))
d.r.hMSet("seen:" & s.nick, hashToSet)
proc getSeen(d: TDb, nick: string, s: var TSeen): bool =
if d.r.exists("seen:" & nick):
result = true
s.nick = nick
# Get the type first
s.kind = d.r.hGet("seen:" & nick, "type").parseInt.TSeenType
for key, value in d.r.hPairs("seen:" & nick):
case normalize(key)
of "type":
#s.kind = value.parseInt.TSeenType
of "channel":
s.channel = value
of "timestamp":
s.timestamp = TTime(value.parseInt)
of "msg":
s.msg = value
of "newnick":
s.newNick = value
template createSeen(typ: TSeenType, n, c: string): stmt {.immediate, dirty.} =
var seenNick: TSeen
seenNick.kind = typ
seenNick.nick = n
seenNick.channel = c
seenNick.timestamp = getTime()
proc parseReply(line: string, expect: string): Bool =
var jsonDoc = parseJson(line)
return jsonDoc["reply"].str == expect
proc limitCommitMsg(m: string): string =
## Limits the message to 300 chars and adds ellipsis.
var m1 = m
if NewLines in m1:
m1 = m1.splitLines()[0]
if m1.len >= 300:
m1 = m1[0..300]
if m1.len >= 300 or NewLines in m: m1.add("... ")
if NewLines in m: m1.add($m.splitLines().len & " more lines")
return m1
proc handleWebMessage(state: PState, line: string) =
echo("Got message from hub: " & line)
var json = parseJson(line)
if json.hasKey("payload"):
for i in 0..min(4, json["payload"]["commits"].len-1):
var commit = json["payload"]["commits"][i]
# Create the message
var message = ""
message.add(json["payload"]["repository"]["owner"]["name"].str & "/" &
json["payload"]["repository"]["name"].str & " ")
message.add(commit["id"].str[0..6] & " ")
message.add(commit["author"]["name"].str & " ")
message.add("[+" & $commit["added"].len & " ")
message.add("±" & $commit["modified"].len & " ")
message.add("-" & $commit["removed"].len & "]: ")
message.add(limitCommitMsg(commit["message"].str))
# Send message to #nimrod.
state.ircClient.privmsg(joinChans[0], message)
elif json.hasKey("redisinfo"):
assert json["redisinfo"].hasKey("port")
#let redisPort = json["redisinfo"]["port"].num
state.dbConnected = true
proc hubConnect(state: PState)
proc handleConnect(s: PAsyncSocket, state: PState) =
try:
# Send greeting
var obj = newJObject()
obj["name"] = newJString("irc")
obj["platform"] = newJString("?")
state.sock.send($obj & "\c\L")
# Wait for reply.
var line = ""
sleep(1500)
if state.sock.recvLine(line):
assert(line != "")
doAssert parseReply(line, "OK")
echo("The hub accepted me!")
else:
raise newException(EInvalidValue,
"Hub didn't accept me. Waited 1.5 seconds.")
# ask for the redis info
var riobj = newJObject()
riobj["do"] = newJString("redisinfo")
state.sock.send($riobj & "\c\L")
except EOS:
echo(getCurrentExceptionMsg())
s.close()
echo("Waiting 5 seconds...")
sleep(5000)
state.hubConnect()
proc handleRead(s: PAsyncSocket, state: PState) =
var line = ""
if state.sock.recvLine(line):
if line != "":
# Handle the message
state.handleWebMessage(line)
else:
echo("Disconnected from hub: ", OSErrorMsg())
s.close()
echo("Reconnecting...")
state.hubConnect()
else:
echo(OSErrorMsg())
proc hubConnect(state: PState) =
state.sock = AsyncSocket()
state.sock.connect("127.0.0.1", state.hubPort)
state.sock.handleConnect =
proc (s: PAsyncSocket) =
handleConnect(s, state)
state.sock.handleRead =
proc (s: PAsyncSocket) =
handleRead(s, state)
state.dispatcher.register(state.sock)
proc handleIrc(irc: PAsyncIRC, event: TIRCEvent, state: PState) =
case event.typ
of EvConnected: nil
of EvDisconnected:
while not state.ircClient.isConnected:
try:
state.ircClient.connect()
except:
echo("Error reconnecting: ", getCurrentExceptionMsg())
echo("Waiting 5 seconds...")
sleep(5000)
echo("Reconnected successfully!")
of EvMsg:
echo("< ", event.raw)
case event.cmd
of MPrivMsg:
let msg = event.params[event.params.len-1]
let words = msg.split(' ')
template pm(msg: string): stmt =
state.ircClient.privmsg(event.origin, msg)
case words[0]
of "!ping": pm("pong")
of "!lag":
if state.ircClient.getLag != -1.0:
var lag = state.ircClient.getLag
lag = lag * 1000.0
pm($int(lag) & "ms between me and the server.")
else:
pm("Unknown.")
of "!seen":
if words.len > 1:
let nick = words[1]
if nick == botNickname:
pm("Yes, I see myself.")
echo(nick)
var seenInfo: TSeen
if state.database.getSeen(nick, seenInfo):
#var mSend = ""
case seenInfo.kind
of PSeenMsg:
pm("$1 was last seen on $2 in $3 saying: $4" %
[seenInfo.nick, $seenInfo.timestamp,
seenInfo.channel, seenInfo.msg])
of PSeenJoin:
pm("$1 was last seen on $2 joining $3" %
[seenInfo.nick, $seenInfo.timestamp, seenInfo.channel])
of PSeenPart:
pm("$1 was last seen on $2 leaving $3 with message: $4" %
[seenInfo.nick, $seenInfo.timestamp, seenInfo.channel,
seenInfo.msg])
of PSeenQuit:
pm("$1 was last seen on $2 quitting with message: $3" %
[seenInfo.nick, $seenInfo.timestamp, seenInfo.msg])
of PSeenNick:
pm("$1 was last seen on $2 changing nick to $3" %
[seenInfo.nick, $seenInfo.timestamp, seenInfo.newNick])
else:
pm("I have not seen " & nick)
else:
pm("Syntax: !seen <nick>")
# TODO: ... commands
# -- Seen
# Log this as activity.
createSeen(PSeenMsg, event.nick, event.origin)
seenNick.msg = msg
state.database.setSeen(seenNick)
of MJoin:
createSeen(PSeenJoin, event.nick, event.origin)
state.database.setSeen(seenNick)
of MPart:
createSeen(PSeenPart, event.nick, event.origin)
let msg = event.params[event.params.high]
seenNick.msg = msg
state.database.setSeen(seenNick)
of MQuit:
createSeen(PSeenQuit, event.nick, event.origin)
let msg = event.params[event.params.high]
seenNick.msg = msg
state.database.setSeen(seenNick)
of MNick:
createSeen(PSeenNick, event.nick, "#nimrod")
seenNick.newNick = event.params[0]
state.database.setSeen(seenNick)
else:
nil # TODO: ?
proc open(port: TPort = TPort(5123)): PState =
var res: PState
new(res)
res.dispatcher = newDispatcher()
res.hubPort = port
res.hubConnect()
let hirc =
proc (a: PAsyncIRC, ev: TIRCEvent) =
handleIrc(a, ev, res)
# Connect to the irc server.
res.ircClient = AsyncIrc(ircServer, nick = botNickname, user = botNickname,
joinChans = joinChans, ircEvent = hirc)
res.ircClient.connect()
res.dispatcher.register(res.ircClient)
res.dbConnected = false
result = res
var state = tircbot.open() # Connect to the website and the IRC server.
while state.dispatcher.poll():
if state.dbConnected:
state.database.keepAlive()

66
tests/stdlib/tlists.nim Normal file
View file

@ -0,0 +1,66 @@
discard """
output: '''true'''
"""
import lists
const
data = [1, 2, 3, 4, 5, 6]
block SinglyLinkedListTest1:
var L: TSinglyLinkedList[int]
for d in items(data): L.prepend(d)
assert($L == "[6, 5, 4, 3, 2, 1]")
assert(4 in L)
block SinglyLinkedListTest2:
var L: TSinglyLinkedList[string]
for d in items(data): L.prepend($d)
assert($L == "[6, 5, 4, 3, 2, 1]")
assert("4" in L)
block DoublyLinkedListTest1:
var L: TDoublyLinkedList[int]
for d in items(data): L.prepend(d)
for d in items(data): L.append(d)
L.remove(L.find(1))
assert($L == "[6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6]")
assert(4 in L)
block SinglyLinkedRingTest1:
var L: TSinglyLinkedRing[int]
L.prepend(4)
assert($L == "[4]")
L.prepend(4)
assert($L == "[4, 4]")
assert(4 in L)
block DoublyLinkedRingTest1:
var L: TDoublyLinkedRing[int]
L.prepend(4)
assert($L == "[4]")
L.prepend(4)
assert($L == "[4, 4]")
assert(4 in L)
L.append(3)
L.append(5)
assert($L == "[4, 4, 3, 5]")
L.remove(L.find(3))
L.remove(L.find(5))
L.remove(L.find(4))
L.remove(L.find(4))
assert($L == "[]")
assert(4 notin L)
echo "true"

65
tests/stdlib/tmarshal.nim Normal file
View file

@ -0,0 +1,65 @@
discard """
output: ""
"""
import marshal
template testit(x: expr) = echo($$to[type(x)]($$x))
var x: array[0..4, array[0..4, string]] = [
["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
["test", "1", "2", "3", "4"]]
testit(x)
var test2: tuple[name: string, s: int] = ("tuple test", 56)
testit(test2)
type
TE = enum
blah, blah2
TestObj = object
test, asd: int
case test2: TE
of blah:
help: string
else:
nil
PNode = ref TNode
TNode = object
next, prev: PNode
data: string
proc buildList(): PNode =
new(result)
new(result.next)
new(result.prev)
result.data = "middle"
result.next.data = "next"
result.prev.data = "prev"
result.next.next = result.prev
result.next.prev = result
result.prev.next = result
result.prev.prev = result.next
var test3: TestObj
test3.test = 42
test3.test2 = blah
testit(test3)
var test4: ref tuple[a, b: string]
new(test4)
test4.a = "ref string test: A"
test4.b = "ref string test: B"
testit(test4)
var test5 = @[(0,1),(2,3),(4,5)]
testit(test5)
var test7 = buildList()
testit(test7)
var test6: set[char] = {'A'..'Z', '_'}
testit(test6)

47
tests/stdlib/tmath.nim Normal file
View file

@ -0,0 +1,47 @@
import math
import unittest
import sets
suite "random int":
test "there might be some randomness":
var set = initSet[int](128)
randomize()
for i in 1..1000:
incl(set, random(high(int)))
check len(set) == 1000
test "single number bounds work":
randomize()
var rand: int
for i in 1..1000:
rand = random(1000)
check rand < 1000
check rand > -1
test "slice bounds work":
randomize()
var rand: int
for i in 1..1000:
rand = random(100..1000)
check rand < 1000
check rand >= 100
suite "random float":
test "there might be some randomness":
var set = initSet[float](128)
randomize()
for i in 1..100:
incl(set, random(1.0))
check len(set) == 100
test "single number bounds work":
randomize()
var rand: float
for i in 1..1000:
rand = random(1000.0)
check rand < 1000.0
check rand > -1.0
test "slice bounds work":
randomize()
var rand: float
for i in 1..1000:
rand = random(100.0..1000.0)
check rand < 1000.0
check rand >= 100.0

85
tests/stdlib/tmath2.nim Normal file
View file

@ -0,0 +1,85 @@
# tests for the interpreter
proc loops(a: var int) =
nil
#var
# b: int
#b = glob
#while b != 0:
# b = b + 1
#a = b
proc mymax(a, b: int): int =
#loops(result)
result = a
if b > a: result = b
proc test(a, b: int) =
var
x, y: int
x = 0
y = 7
if x == a + b * 3 - 7 or
x == 8 or
x == y and y > -56 and y < 699:
y = 0
elif y == 78 and x == 0:
y = 1
elif y == 0 and x == 0:
y = 2
else:
y = 3
type
TTokType = enum
tkNil, tkType, tkConst, tkVar, tkSymbol, tkIf,
tkWhile, tkFor, tkLoop, tkCase, tkLabel, tkGoto
proc testCase(t: TTokType): int =
case t
of tkNil, tkType, tkConst: result = 0
of tkVar: result = 1
of tkSymbol: result = 2
of tkIf..tkFor: result = 3
of tkLoop: result = 56
else: result = -1
test(0, 9) # test the call
proc TestLoops() =
var
i, j: int
while i >= 0:
if i mod 3 == 0:
break
i = i + 1
while j == 13:
j = 13
break
break
while True:
break
var
glob: int
a: array [0..5, int]
proc main() =
#glob = 0
#loops( glob )
var
res: int
s: string
#write(stdout, mymax(23, 45))
write(stdout, "Hallo! Wie heißt du? ")
s = readLine(stdin)
# test the case statement
case s
of "Andreas": write(stdout, "Du bist mein Meister!\n")
of "Rumpf": write(stdout, "Du bist in der Familie meines Meisters!\n")
else: write(stdout, "ich kenne dich nicht!\n")
write(stdout, "Du heisst " & s & "\n")
main()

16
tests/stdlib/tmongo.nim Normal file
View file

@ -0,0 +1,16 @@
import mongo, db_mongo, oids, json
var conn = db_mongo.open()
var data = %{"a": %13, "b": %"my string value",
"inner": %{"i": %71} }
var id = insertID(conn, "test.test", data)
for v in find(conn, "test.test", "this.a == 13"):
print v
delete(conn, "test.test", id)
close(conn)

12
tests/stdlib/tos.nim Normal file
View file

@ -0,0 +1,12 @@
# test some things of the os module
import os
proc walkDirTree(root: string) =
for k, f in walkDir(root):
case k
of pcFile, pcLinkToFile: echo(f)
of pcDir: walkDirTree(f)
of pcLinkToDir: nil
walkDirTree(".")

25
tests/stdlib/tparscfg.nim Normal file
View file

@ -0,0 +1,25 @@
import
os, parsecfg, strutils, streams
var f = newFileStream(paramStr(1), fmRead)
if f != nil:
var p: TCfgParser
open(p, f, paramStr(1))
while true:
var e = next(p)
case e.kind
of cfgEof:
echo("EOF!")
break
of cfgSectionStart: ## a ``[section]`` has been parsed
echo("new section: " & e.section)
of cfgKeyValuePair:
echo("key-value-pair: " & e.key & ": " & e.value)
of cfgOption:
echo("command: " & e.key & ": " & e.value)
of cfgError:
echo(e.msg)
close(p)
else:
echo("cannot open: " & paramStr(1))

View file

@ -0,0 +1,3 @@
import strutils
echo ParseFloat("5000") / ParseFloat("10")

27
tests/stdlib/tparsopt.nim Normal file
View file

@ -0,0 +1,27 @@
# Test the new parseopt module
import
parseopt
proc writeHelp() =
writeln(stdout, "Usage: tparsopt [options] filename [options]")
proc writeVersion() =
writeln(stdout, "Version: 1.0.0")
var
filename = ""
for kind, key, val in getopt():
case kind
of cmdArgument:
filename = key
of cmdLongOption, cmdShortOption:
case key
of "help", "h": writeHelp()
of "version", "v": writeVersion()
else:
writeln(stdout, "Unknown command line option: ", key, ": ", val)
of cmdEnd: assert(false) # cannot happen
if filename == "":
# no filename has been given, so we show the help:
writeHelp()

1770
tests/stdlib/tpegs.nim Normal file

File diff suppressed because it is too large Load diff

16
tests/stdlib/tposix.nim Normal file
View file

@ -0,0 +1,16 @@
# Test Posix interface
when not defined(windows):
import posix
var
u: Tutsname
discard uname(u)
writeln(stdout, u.sysname)
writeln(stdout, u.nodename)
writeln(stdout, u.release)
writeln(stdout, u.machine)

6
tests/stdlib/tquit.nim Normal file
View file

@ -0,0 +1,6 @@
# Test the new beforeQuit variable:
proc myExit() {.noconv.} =
write(stdout, "just exiting...\n")
addQuitProc(myExit)

31
tests/stdlib/tregex.nim Normal file
View file

@ -0,0 +1,31 @@
discard """
file: "tregex.nim"
output: "key: keyAYes!"
"""
# Test the new regular expression module
# which is based on the PCRE library
when defined(powerpc64):
# cheat as our powerpc test machine has no PCRE installed:
echo "key: keyAYes!"
else:
import
re
if "keyA = valueA" =~ re"\s*(\w+)\s*\=\s*(\w+)":
write(stdout, "key: ", matches[0])
elif "# comment!" =~ re.re"\s*(\#.*)":
# test re.re"" syntax
echo("comment: ", matches[0])
else:
echo("Bug!")
if "Username".match(re"[A-Za-z]+"):
echo("Yes!")
else:
echo("Bug!")
#OUT key: keyAYes!

27
tests/stdlib/treguse.nim Normal file
View file

@ -0,0 +1,27 @@
discard """
file: "treguse.nim"
output: "055this should be the casehugh"
"""
# Test the register usage of the virtual machine and
# the blocks in var statements
proc main(a, b: int) =
var x = 0
write(stdout, x)
if x == 0:
var y = 55
write(stdout, y)
write(stdout, "this should be the case")
var input = "<no input>"
if input == "Andreas":
write(stdout, "wow")
else:
write(stdout, "hugh")
else:
var z = 66
write(stdout, z) # "bug!")
main(45, 1000)
#OUT 055this should be the casehugh

29
tests/stdlib/trepr.nim Normal file
View file

@ -0,0 +1,29 @@
discard """
file: "trepr.nim"
output: "{a, b}{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}"
"""
type
TEnum = enum
a, b
var val = {a, b}
stdout.write(repr(val))
stdout.writeln(repr({'a'..'z', 'A'..'Z'}))
type
TObj {.pure, inheritable.} = object
data: int
TFoo = ref object of TObj
d2: float
var foo: TFoo
new(foo)
when false:
# cannot capture this output as it contains a memory address :-/
echo foo.repr
#var testseq: seq[string] = @[
# "a", "b", "c", "d", "e"
#]
#echo(repr(testseq))

32
tests/stdlib/trepr2.nim Normal file
View file

@ -0,0 +1,32 @@
# test the new "repr" built-in proc
type
TEnum = enum
en1, en2, en3, en4, en5, en6
TPoint {.final.} = object
x, y, z: int
s: array [0..1, string]
e: TEnum
var
p: TPoint
q: ref TPoint
s: seq[ref TPoint]
p.x = 0
p.y = 13
p.z = 45
p.s[0] = "abc"
p.s[1] = "xyz"
p.e = en6
new(q)
q[] = p
s = @[q, q, q, q]
writeln(stdout, repr(p))
writeln(stdout, repr(q))
writeln(stdout, repr(s))
writeln(stdout, repr(en4))

11
tests/stdlib/tsockets.nim Normal file
View file

@ -0,0 +1,11 @@
import sockets
var s: TSocket
s = socket()
s.connect("www.google.com", TPort(80))
var data: string = ""
s.readLine(data)
echo(data)

View file

@ -0,0 +1,5 @@
import algorithm
proc foosort(ships: var seq[int]) = sort(ships, system.cmp[int])

20
tests/stdlib/tsplit.nim Normal file
View file

@ -0,0 +1,20 @@
discard """
file: "tsplit.nim"
output: "true"
"""
import strutils
var s = ""
for w in split("|abc|xy|z", {'|'}):
s.add("#")
s.add(w)
if s == "#abc#xy#z":
echo "true"
else:
echo "false"
#OUT true

View file

@ -0,0 +1,7 @@
import streams
var outp = newFileStream(stdout)
var inp = newFileStream(stdin)
write(outp, "Hello! What is your name?")
var line = readLine(inp)
write(outp, "Nice name: " & line)

74
tests/stdlib/tstrset.nim Normal file
View file

@ -0,0 +1,74 @@
# test a simple yet highly efficient set of strings
type
TRadixNodeKind = enum rnLinear, rnFull, rnLeaf
PRadixNode = ref TRadixNode
TRadixNode = object {.inheritable.}
kind: TRadixNodeKind
TRadixNodeLinear = object of TRadixNode
len: int8
keys: array [0..31, char]
vals: array [0..31, PRadixNode]
TRadixNodeFull = object of TRadixNode
b: array [char, PRadixNode]
TRadixNodeLeaf = object of TRadixNode
s: string
PRadixNodeLinear = ref TRadixNodeLinear
PRadixNodeFull = ref TRadixNodeFull
PRadixNodeLeaf = ref TRadixNodeLeaf
proc search(r: PRadixNode, s: string): PRadixNode =
var r = r
var i = 0
while r != nil:
case r.kind
of rnLinear:
var x = PRadixNodeLinear(r)
for j in 0..ze(x.len)-1:
if x.keys[j] == s[i]:
if s[i] == '\0': return r
r = x.vals[j]
inc(i)
break
break # character not found
of rnFull:
var x = PRadixNodeFull(r)
var y = x.b[s[i]]
if s[i] == '\0':
return if y != nil: r else: nil
r = y
inc(i)
of rnLeaf:
var x = PRadixNodeLeaf(r)
var j = 0
while true:
if x.s[j] != s[i]: return nil
if s[i] == '\0': return r
inc(j)
inc(i)
proc contains*(r: PRadixNode, s: string): bool =
return search(r, s) != nil
proc testOrincl*(r: var PRadixNode, s: string): bool =
nil
proc incl*(r: var PRadixNode, s: string) = discard testOrIncl(r, s)
proc excl*(r: var PRadixNode, s: string) =
var x = search(r, s)
if x == nil: return
case x.kind
of rnLeaf: PRadixNodeLeaf(x).s = ""
of rnFull: PRadixNodeFull(x).b['\0'] = nil
of rnLinear:
var x = PRadixNodeLinear(x)
for i in 0..ze(x.len)-1:
if x.keys[i] == '\0':
swap(x.keys[i], x.keys[ze(x.len)-1])
dec(x.len)
break
var
root: PRadixNode

12
tests/stdlib/tstrtabs.nim Normal file
View file

@ -0,0 +1,12 @@
import strtabs
var tab = newStringTable({"key1": "val1", "key2": "val2"},
modeStyleInsensitive)
for i in 0..80:
tab["key_" & $i] = "value" & $i
for key, val in pairs(tab):
writeln(stdout, key, ": ", val)
writeln(stdout, "length of table ", $tab.len)
writeln(stdout, `%`("$key1 = $key2; ${PATH}", tab, {useEnvironment}))

45
tests/stdlib/tstrutil.nim Normal file
View file

@ -0,0 +1,45 @@
discard """
file: "tstrutil.nim"
output: "ha/home/a1xyz/usr/bin"
"""
# test the new strutils module
import
strutils
proc testStrip() =
write(stdout, strip(" ha "))
proc main() =
testStrip()
for p in split("/home/a1:xyz:/usr/bin", {':'}):
write(stdout, p)
proc testDelete =
var s = "0123456789ABCDEFGH"
delete(s, 4, 5)
assert s == "01236789ABCDEFGH"
delete(s, s.len-1, s.len-1)
assert s == "01236789ABCDEFG"
delete(s, 0, 0)
assert s == "1236789ABCDEFG"
testDelete()
assert(insertSep($1000_000) == "1_000_000")
assert(insertSep($232) == "232")
assert(insertSep($12345, ',') == "12,345")
assert(insertSep($0) == "0")
assert(editDistance("prefix__hallo_suffix", "prefix__hallo_suffix") == 0)
assert(editDistance("prefix__hallo_suffix", "prefix__hallo_suffi1") == 1)
assert(editDistance("prefix__hallo_suffix", "prefix__HALLO_suffix") == 5)
assert(editDistance("prefix__hallo_suffix", "prefix__ha_suffix") == 3)
assert(editDistance("prefix__hallo_suffix", "prefix") == 14)
assert(editDistance("prefix__hallo_suffix", "suffix") == 14)
assert(editDistance("prefix__hallo_suffix", "prefix__hao_suffix") == 2)
main()
#OUT ha/home/a1xyz/usr/bin

6
tests/stdlib/ttime.nim Normal file
View file

@ -0,0 +1,6 @@
# test the new time module
import
times
write(stdout, $getTime())

View file

@ -0,0 +1,12 @@
discard """
cmd: "nimrod cc --hints:on -d:embedUnidecodeTable $# $#"
output: "Ausserst"
"""
import unidecode
loadUnidecodeTable("lib/pure/unidecode/unidecode.dat")
#assert unidecode("\x53\x17\x4E\xB0") == "Bei Jing"
echo unidecode("Äußerst")

13
tests/stdlib/twalker.nim Normal file
View file

@ -0,0 +1,13 @@
# iterate over all files with a given filter:
import
"../../lib/pure/os.nim", ../../ lib / pure / times
proc main(filter: string) =
for filename in walkFiles(filter):
writeln(stdout, filename)
for key, val in envPairs():
writeln(stdout, key & '=' & val)
main("*.nim")

12
tests/stdlib/txmlgen.nim Normal file
View file

@ -0,0 +1,12 @@
discard """
file: "txmlgen.nim"
output: "<h1><a href=\"http://force7.de/nimrod\">Nimrod</a></h1>"
"""
import htmlgen
var nim = "Nimrod"
echo h1(a(href="http://force7.de/nimrod", nim))

13
tests/stdlib/txmltree.nim Normal file
View file

@ -0,0 +1,13 @@
discard """
file: "txmltree.nim"
output: "true"
"""
import xmltree, strtabs
var x = <>a(href="nimrod.de", newText("www.nimrod-test.de"))
echo($x == "<a href=\"nimrod.de\">www.nimrod-test.de</a>")