diff options
Diffstat (limited to 'tests/stdlib')
-rw-r--r-- | tests/stdlib/tcount.nim | 29 | ||||
-rw-r--r-- | tests/stdlib/tdialogs.nim | 8 | ||||
-rw-r--r-- | tests/stdlib/tgetfileinfo.nim | 17 | ||||
-rw-r--r-- | tests/stdlib/tircbot.nim | 452 | ||||
-rw-r--r-- | tests/stdlib/tmarshal.nim | 28 | ||||
-rw-r--r-- | tests/stdlib/tmath2.nim | 4 | ||||
-rw-r--r-- | tests/stdlib/tmitems.nim | 136 | ||||
-rw-r--r-- | tests/stdlib/tnet.nim | 47 | ||||
-rw-r--r-- | tests/stdlib/tparsefloat.nim | 3 | ||||
-rw-r--r-- | tests/stdlib/tpegs.nim | 92 | ||||
-rw-r--r-- | tests/stdlib/tpermutations.nim | 19 | ||||
-rw-r--r-- | tests/stdlib/treloop.nim | 9 | ||||
-rw-r--r-- | tests/stdlib/tsinglylinkedring.nim | 29 | ||||
-rw-r--r-- | tests/stdlib/tsockets.nim | 12 | ||||
-rw-r--r-- | tests/stdlib/tstrutil.nim | 61 |
15 files changed, 388 insertions, 558 deletions
diff --git a/tests/stdlib/tcount.nim b/tests/stdlib/tcount.nim new file mode 100644 index 000000000..ce1d14b6c --- /dev/null +++ b/tests/stdlib/tcount.nim @@ -0,0 +1,29 @@ +discard """ + output: '''1 +2 +3 +4 +5 +done''' +""" + +# bug #1845, #2224 + +var arr = [3,2,1,5,4] + +# bubble sort +for i in low(arr)..high(arr): + for j in i+1..high(arr): # Error: unhandled exception: value out of range: 5 [RangeError] + if arr[i] > arr[j]: + let tmp = arr[i] + arr[i] = arr[j] + arr[j] = tmp + +for i in low(arr)..high(arr): + echo arr[i] + +# check this terminates: +for x in countdown('\255', '\0'): + discard + +echo "done" diff --git a/tests/stdlib/tdialogs.nim b/tests/stdlib/tdialogs.nim index d161a976d..f0203d319 100644 --- a/tests/stdlib/tdialogs.nim +++ b/tests/stdlib/tdialogs.nim @@ -4,7 +4,7 @@ import dialogs, gtk2 gtk2.nimrod_init() -var x = ChooseFilesToOpen(nil) +var x = chooseFilesToOpen(nil) for a in items(x): writeln(stdout, a) @@ -12,6 +12,6 @@ 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)) +writeln(stdout, chooseFileToOpen(nil)) +writeln(stdout, chooseFileToSave(nil)) +writeln(stdout, chooseDir(nil)) diff --git a/tests/stdlib/tgetfileinfo.nim b/tests/stdlib/tgetfileinfo.nim index 49a019061..8a0538a5f 100644 --- a/tests/stdlib/tgetfileinfo.nim +++ b/tests/stdlib/tgetfileinfo.nim @@ -32,7 +32,7 @@ proc caseOneAndTwo(followLink: bool) = try: discard getFileInfo(getAppFilename(), followLink) #echo("String : Existing File : Symlink $# : Success" % $followLink) - except EOS: + except OSError: echo("String : Existing File : Symlink $# : Failure" % $followLink) proc caseThreeAndFour(followLink: bool) = @@ -40,7 +40,8 @@ proc caseThreeAndFour(followLink: bool) = try: discard getFileInfo(invalidName, true) echo("String : Non-existing File : Symlink $# : Failure" % $followLink) - except EOS: + except OSError: + discard #echo("String : Non-existing File : Symlink $# : Success" % $followLink) proc testGetFileInfo = @@ -64,13 +65,13 @@ proc testGetFileInfo = try: discard getFileInfo(testFile) #echo("Handle : Valid File : Success") - except EIO: + except IOError: echo("Handle : Valid File : Failure") try: discard getFileInfo(testHandle) #echo("Handle : Valid File : Success") - except EIO: + except IOError: echo("Handle : Valid File : Failure") # Case 6 and 8 @@ -81,13 +82,15 @@ proc testGetFileInfo = try: discard getFileInfo(testFile) echo("Handle : Invalid File : Failure") - except EIO, EOS: + except IOError, OSError: + discard #echo("Handle : Invalid File : Success") try: discard getFileInfo(testHandle) echo("Handle : Invalid File : Failure") - except EIO, EOS: + except IOError, OSError: + discard #echo("Handle : Invalid File : Success") -testGetFileInfo() \ No newline at end of file +testGetFileInfo() diff --git a/tests/stdlib/tircbot.nim b/tests/stdlib/tircbot.nim deleted file mode 100644 index b91300762..000000000 --- a/tests/stdlib/tircbot.nim +++ /dev/null @@ -1,452 +0,0 @@ -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 = @["#nim"] - 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: discard - 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 #nim. - 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: discard - 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, "#nim") - seenNick.newNick = event.params[0] - state.database.setSeen(seenNick) - else: - discard # 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() diff --git a/tests/stdlib/tmarshal.nim b/tests/stdlib/tmarshal.nim index 5471d347a..a778d2f77 100644 --- a/tests/stdlib/tmarshal.nim +++ b/tests/stdlib/tmarshal.nim @@ -1,16 +1,16 @@ discard """ - output: "" + output: '''{"age": 12, "name": "Cletus"}''' """ import marshal -template testit(x: expr) = echo($$to[type(x)]($$x)) +template testit(x: expr) = discard $$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 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) @@ -24,7 +24,7 @@ type of blah: help: string else: - nil + discard PNode = ref TNode TNode = object @@ -63,3 +63,15 @@ testit(test7) var test6: set[char] = {'A'..'Z', '_'} testit(test6) + +# bug #1352 + +type + Entity = object of RootObj + name: string + + Person = object of Entity + age: int + +var instance1 = Person(name: "Cletus", age: 12) +echo($$instance1) diff --git a/tests/stdlib/tmath2.nim b/tests/stdlib/tmath2.nim index 935b08634..88d96c80a 100644 --- a/tests/stdlib/tmath2.nim +++ b/tests/stdlib/tmath2.nim @@ -58,7 +58,7 @@ proc TestLoops() = break break - while True: + while true: break @@ -73,7 +73,7 @@ proc main() = res: int s: string #write(stdout, mymax(23, 45)) - write(stdout, "Hallo! Wie heißt du? ") + write(stdout, "Hallo! Wie heisst du? ") s = readLine(stdin) # test the case statement case s diff --git a/tests/stdlib/tmitems.nim b/tests/stdlib/tmitems.nim new file mode 100644 index 000000000..2c0a0392a --- /dev/null +++ b/tests/stdlib/tmitems.nim @@ -0,0 +1,136 @@ +discard """ + output: '''@[11, 12, 13] +@[11, 12, 13] +@[1, 3, 5] +@[1, 3, 5] +gppcbs +gppcbs +fpqeew +fpqeew +[11, 12, 13] +[11, 12, 13] +[11, 12, 13] +[11, 12, 13] +{"key1": 11, "key2": 12, "key3": 13} +[11, 12, 13] +<Students> + <Student Name="Aprilfoo" /> + <Student Name="bar" /> +</Students>''' +""" + +block: + var xs = @[1,2,3] + for x in xs.mitems: + x += 10 + echo xs + +block: + var xs = [1,2,3] + for x in xs.mitems: + x += 10 + echo(@xs) + +block: + var xs = @[1,2,3] + for i, x in xs.mpairs: + x += i + echo xs + +block: + var xs = [1,2,3] + for i, x in xs.mpairs: + x += i + echo(@xs) + +block: + var x = "foobar" + for c in x.mitems: + inc c + echo x + +block: + var x = "foobar" + var y = cast[cstring](addr x[0]) + for c in y.mitems: + inc c + echo x + +block: + var x = "foobar" + for i, c in x.mpairs: + inc c, i + echo x + +block: + var x = "foobar" + var y = cast[cstring](addr x[0]) + for i, c in y.mpairs: + inc c, i + echo x + +import lists + +block: + var sl = initSinglyLinkedList[int]() + sl.prepend(3) + sl.prepend(2) + sl.prepend(1) + for x in sl.mitems: + x += 10 + echo sl + +block: + var sl = initDoublyLinkedList[int]() + sl.append(1) + sl.append(2) + sl.append(3) + for x in sl.mitems: + x += 10 + echo sl + +block: + var sl = initDoublyLinkedRing[int]() + sl.append(1) + sl.append(2) + sl.append(3) + for x in sl.mitems: + x += 10 + echo sl + +import queues + +block: + var q = initQueue[int]() + q.add(1) + q.add(2) + q.add(3) + for x in q.mitems: + x += 10 + echo q + +import json + +block: + var j = parseJson """{"key1": 1, "key2": 2, "key3": 3}""" + for key,val in j.pairs: + val.num += 10 + echo j + +block: + var j = parseJson """[1, 2, 3]""" + for x in j.mitems: + x.num += 10 + echo j + +import xmltree, xmlparser, streams, strtabs + +block: + var d = parseXml(newStringStream """<Students> + <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> + <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> + </Students>""") + for x in d.mitems: + x = <>Student(Name=x.attrs["Name"] & "foo") + d.mget(1).attrs["Name"] = "bar" + echo d diff --git a/tests/stdlib/tnet.nim b/tests/stdlib/tnet.nim new file mode 100644 index 000000000..e8ada05e7 --- /dev/null +++ b/tests/stdlib/tnet.nim @@ -0,0 +1,47 @@ +import net +import unittest + +suite "isIpAddress tests": + test "127.0.0.1 is valid": + check isIpAddress("127.0.0.1") == true + + test "ipv6 localhost is valid": + check isIpAddress("::1") == true + + test "fqdn is not an ip address": + check isIpAddress("example.com") == false + + test "random string is not an ipaddress": + check isIpAddress("foo bar") == false + + test "5127.0.0.1 is invalid": + check isIpAddress("5127.0.0.1") == false + + test "ipv6 is valid": + check isIpAddress("2001:cdba:0000:0000:0000:0000:3257:9652") == true + + test "invalid ipv6": + check isIpAddress("gggg:cdba:0000:0000:0000:0000:3257:9652") == false + + +suite "parseIpAddress tests": + test "127.0.0.1 is valid": + discard parseIpAddress("127.0.0.1") + + test "ipv6 localhost is valid": + discard parseIpAddress("::1") + + test "fqdn is not an ip address": + expect(ValueError): + discard parseIpAddress("example.com") + + test "random string is not an ipaddress": + expect(ValueError): + discard parseIpAddress("foo bar") + + test "ipv6 is valid": + discard parseIpAddress("2001:cdba:0000:0000:0000:0000:3257:9652") + + test "invalid ipv6": + expect(ValueError): + discard parseIpAddress("gggg:cdba:0000:0000:0000:0000:3257:9652") diff --git a/tests/stdlib/tparsefloat.nim b/tests/stdlib/tparsefloat.nim deleted file mode 100644 index 38ed2db6d..000000000 --- a/tests/stdlib/tparsefloat.nim +++ /dev/null @@ -1,3 +0,0 @@ -import strutils - -echo ParseFloat("5000") / ParseFloat("10") diff --git a/tests/stdlib/tpegs.nim b/tests/stdlib/tpegs.nim index e5353e4ff..cceea1693 100644 --- a/tests/stdlib/tpegs.nim +++ b/tests/stdlib/tpegs.nim @@ -397,7 +397,7 @@ proc esc(c: char, reserved = {'\0'..'\255'}): string = elif c in reserved: result = '\\' & c else: result = $c -proc singleQuoteEsc(c: Char): string = return "'" & esc(c, {'\''}) & "'" +proc singleQuoteEsc(c: char): string = return "'" & esc(c, {'\''}) & "'" proc singleQuoteEsc(str: string): string = result = "'" @@ -421,11 +421,11 @@ proc charSetEscAux(cc: set[char]): string = c1 = c2 inc(c1) -proc CharSetEsc(cc: set[char]): string = +proc charSetEsc(cc: set[char]): string = if card(cc) >= 128+64: - result = "[^" & CharSetEscAux({'\1'..'\xFF'} - cc) & ']' + result = "[^" & charSetEscAux({'\1'..'\xFF'} - cc) & ']' else: - result = '[' & CharSetEscAux(cc) & ']' + result = '[' & charSetEscAux(cc) & ']' proc toStrAux(r: TPeg, res: var string) = case r.kind @@ -522,18 +522,18 @@ proc `$` *(r: TPeg): string {.rtl, extern: "npegsToString".} = type TCaptures* {.final.} = object ## contains the captured substrings. - matches: array[0..maxSubpatterns-1, tuple[first, last: int]] + matches: array[0..MaxSubpatterns-1, tuple[first, last: int]] ml: int origStart: int proc bounds*(c: TCaptures, - i: range[0..maxSubpatterns-1]): tuple[first, last: int] = + i: range[0..MaxSubpatterns-1]): tuple[first, last: int] = ## returns the bounds ``[first..last]`` of the `i`'th capture. result = c.matches[i] when not useUnicode: type - TRune = char + Rune = char template fastRuneAt(s, i, ch: expr) = ch = s[i] inc(i) @@ -563,7 +563,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. result = -1 of pkLetter: if s[start] != '\0': - var a: TRune + var a: Rune result = start fastRuneAt(s, result, a) if isAlpha(a): dec(result, start) @@ -572,7 +572,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. result = -1 of pkLower: if s[start] != '\0': - var a: TRune + var a: Rune result = start fastRuneAt(s, result, a) if isLower(a): dec(result, start) @@ -581,7 +581,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. result = -1 of pkUpper: if s[start] != '\0': - var a: TRune + var a: Rune result = start fastRuneAt(s, result, a) if isUpper(a): dec(result, start) @@ -590,7 +590,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. result = -1 of pkTitle: if s[start] != '\0': - var a: TRune + var a: Rune result = start fastRuneAt(s, result, a) if isTitle(a): dec(result, start) @@ -599,7 +599,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. result = -1 of pkWhitespace: if s[start] != '\0': - var a: TRune + var a: Rune result = start fastRuneAt(s, result, a) if isWhitespace(a): dec(result, start) @@ -623,7 +623,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. of pkTerminalIgnoreCase: var i = 0 - a, b: TRune + a, b: Rune result = start while i < len(p.term): fastRuneAt(p.term, i, a) @@ -635,15 +635,15 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. of pkTerminalIgnoreStyle: var i = 0 - a, b: TRune + a, b: Rune result = start while i < len(p.term): while true: fastRuneAt(p.term, i, a) - if a != TRune('_'): break + if a != Rune('_'): break while true: fastRuneAt(s, result, b) - if b != TRune('_'): break + if b != Rune('_'): break if toLower(a) != toLower(b): result = -1 break @@ -695,7 +695,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. while start+result < s.len: var x = rawMatch(s, p.sons[0], start+result, c) if x >= 0: - if idx < maxSubpatterns: + if idx < MaxSubpatterns: c.matches[idx] = (start, start+result-1) #else: silently ignore the capture inc(result, x) @@ -739,7 +739,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. inc(c.ml) result = rawMatch(s, p.sons[0], start, c) if result >= 0: - if idx < maxSubpatterns: + if idx < MaxSubpatterns: c.matches[idx] = (start, start+result-1) #else: silently ignore the capture else: @@ -836,7 +836,7 @@ iterator findAll*(s: string, pattern: TPeg, start = 0): string = while i < s.len: var L = matchLen(s, pattern, matches, i) if L < 0: break - for k in 0..maxSubPatterns-1: + for k in 0..MaxSubPatterns-1: if isNil(matches[k]): break yield matches[k] inc(i, L) @@ -865,8 +865,8 @@ template `=~`*(s: string, pattern: TPeg): expr = ## else: ## echo("syntax error") ## - when not definedInScope(matches): - var matches {.inject.}: array[0..maxSubpatterns-1, string] + when not declaredInScope(matches): + var matches {.inject.}: array[0..MaxSubpatterns-1, string] match(s, pattern, matches) # ------------------------- more string handling ------------------------------ @@ -907,7 +907,7 @@ proc replacef*(s: string, sub: TPeg, by: string): string {. ## "var1<-keykey; val2<-key2key2" result = "" var i = 0 - var caps: array[0..maxSubpatterns-1, string] + var caps: array[0..MaxSubpatterns-1, string] while i < s.len: var x = matchLen(s, sub, caps, i) if x <= 0: @@ -924,7 +924,7 @@ proc replace*(s: string, sub: TPeg, by = ""): string {. ## in `by`. result = "" var i = 0 - var caps: array[0..maxSubpatterns-1, string] + var caps: array[0..MaxSubpatterns-1, string] while i < s.len: var x = matchLen(s, sub, caps, i) if x <= 0: @@ -942,7 +942,7 @@ proc parallelReplace*(s: string, subs: varargs[ ## applied in parallel. result = "" var i = 0 - var caps: array[0..maxSubpatterns-1, string] + var caps: array[0..MaxSubpatterns-1, string] while i < s.len: block searchSubs: for j in 0..high(subs): @@ -964,7 +964,7 @@ proc transformFile*(infile, outfile: string, ## error occurs. This is supposed to be used for quick scripting. var x = readFile(infile) if not isNil(x): - var f: TFile + var f: File if open(f, outfile, fmWrite): write(f, x.parallelReplace(subs)) close(f) @@ -1055,7 +1055,7 @@ type TPegLexer {.inheritable.} = object ## the lexer object. bufpos: int ## the current position within the buffer buf: cstring ## the buffer itself - LineNumber: int ## the current line number + lineNumber: int ## the current line number lineStart: int ## index of last line start in buffer colOffset: int ## column to add filename: string @@ -1118,38 +1118,38 @@ proc getEscapedChar(c: var TPegLexer, tok: var TToken) = case c.buf[c.bufpos] of 'r', 'R', 'c', 'C': add(tok.literal, '\c') - Inc(c.bufpos) + inc(c.bufpos) of 'l', 'L': add(tok.literal, '\L') - Inc(c.bufpos) + inc(c.bufpos) of 'f', 'F': add(tok.literal, '\f') inc(c.bufpos) of 'e', 'E': add(tok.literal, '\e') - Inc(c.bufpos) + inc(c.bufpos) of 'a', 'A': add(tok.literal, '\a') - Inc(c.bufpos) + inc(c.bufpos) of 'b', 'B': add(tok.literal, '\b') - Inc(c.bufpos) + inc(c.bufpos) of 'v', 'V': add(tok.literal, '\v') - Inc(c.bufpos) + inc(c.bufpos) of 't', 'T': add(tok.literal, '\t') - Inc(c.bufpos) + inc(c.bufpos) of 'x', 'X': inc(c.bufpos) var xi = 0 handleHexChar(c, xi) handleHexChar(c, xi) if xi == 0: tok.kind = tkInvalid - else: add(tok.literal, Chr(xi)) + else: add(tok.literal, chr(xi)) of '0'..'9': var val = ord(c.buf[c.bufpos]) - ord('0') - Inc(c.bufpos) + inc(c.bufpos) var i = 1 while (i <= 3) and (c.buf[c.bufpos] in {'0'..'9'}): val = val * 10 + ord(c.buf[c.bufpos]) - ord('0') @@ -1159,11 +1159,11 @@ proc getEscapedChar(c: var TPegLexer, tok: var TToken) = else: tok.kind = tkInvalid of '\0'..'\31': tok.kind = tkInvalid - elif c.buf[c.bufpos] in strutils.letters: + elif c.buf[c.bufpos] in strutils.Letters: tok.kind = tkInvalid else: add(tok.literal, c.buf[c.bufpos]) - Inc(c.bufpos) + inc(c.bufpos) proc skip(c: var TPegLexer) = var pos = c.bufpos @@ -1171,7 +1171,7 @@ proc skip(c: var TPegLexer) = while true: case buf[pos] of ' ', '\t': - Inc(pos) + inc(pos) of '#': while not (buf[pos] in {'\c', '\L', '\0'}): inc(pos) of '\c': @@ -1203,7 +1203,7 @@ proc getString(c: var TPegLexer, tok: var TToken) = break else: add(tok.literal, buf[pos]) - Inc(pos) + inc(pos) c.bufpos = pos proc getDollar(c: var TPegLexer, tok: var TToken) = @@ -1244,7 +1244,7 @@ proc getCharSet(c: var TPegLexer, tok: var TToken) = break else: ch = buf[pos] - Inc(pos) + inc(pos) incl(tok.charset, ch) if buf[pos] == '-': if buf[pos+1] == ']': @@ -1264,7 +1264,7 @@ proc getCharSet(c: var TPegLexer, tok: var TToken) = break else: ch2 = buf[pos] - Inc(pos) + inc(pos) for i in ord(ch)+1 .. ord(ch2): incl(tok.charset, chr(i)) c.bufpos = pos @@ -1275,7 +1275,7 @@ proc getSymbol(c: var TPegLexer, tok: var TToken) = var buf = c.buf while true: add(tok.literal, buf[pos]) - Inc(pos) + inc(pos) if buf[pos] notin strutils.IdentChars: break c.bufpos = pos tok.kind = tkIdentifier @@ -1312,11 +1312,11 @@ proc getTok(c: var TPegLexer, tok: var TToken) = getCharset(c, tok) of '(': tok.kind = tkParLe - Inc(c.bufpos) + inc(c.bufpos) add(tok.literal, '(') of ')': tok.kind = tkParRi - Inc(c.bufpos) + inc(c.bufpos) add(tok.literal, ')') of '.': tok.kind = tkAny @@ -1404,8 +1404,8 @@ proc arrowIsNextTok(c: TPegLexer): bool = # ----------------------------- parser ---------------------------------------- type - EInvalidPeg* = object of EInvalidValue ## raised if an invalid - ## PEG has been detected + EInvalidPeg* = object of ValueError ## raised if an invalid + ## PEG has been detected TPegParser = object of TPegLexer ## the PEG parser object tok: TToken nonterms: seq[PNonTerminal] diff --git a/tests/stdlib/tpermutations.nim b/tests/stdlib/tpermutations.nim new file mode 100644 index 000000000..a6e07ded6 --- /dev/null +++ b/tests/stdlib/tpermutations.nim @@ -0,0 +1,19 @@ +discard """ + output: '''@[0, 2, 1] +@[1, 0, 2] +@[1, 2, 0] +@[2, 0, 1] +@[2, 1, 0] +@[2, 0, 1] +@[1, 2, 0] +@[1, 0, 2] +@[0, 2, 1] +@[0, 1, 2]''' +""" +import algorithm + +var v = @[0, 1, 2] +while v.nextPermutation(): + echo v +while v.prevPermutation(): + echo v diff --git a/tests/stdlib/treloop.nim b/tests/stdlib/treloop.nim new file mode 100644 index 000000000..35236708c --- /dev/null +++ b/tests/stdlib/treloop.nim @@ -0,0 +1,9 @@ +discard """ + output: "@[(, +, 1, 2, )]" +""" + +import re + +let str = "(+ 1 2)" +var tokenRE = re"""[\s,]*(~@|[\[\]{}()'`~^@]|"(?:\\.|[^\\"])*"|;.*|[^\s\[\]{}('"`,;)]*)""" +echo str.findAll(tokenRE) diff --git a/tests/stdlib/tsinglylinkedring.nim b/tests/stdlib/tsinglylinkedring.nim new file mode 100644 index 000000000..93f0c69cd --- /dev/null +++ b/tests/stdlib/tsinglylinkedring.nim @@ -0,0 +1,29 @@ +discard """ + output: '''[5] +[4, 5] +[3, 4, 5] +[2, 3, 4, 5] +[2, 3, 4, 5, 6] +[2, 3, 4, 5, 6, 7] +[2, 3, 4, 5, 6, 7, 8] +[1, 2, 3, 4, 5, 6, 7, 8]''' +""" +import lists + +var r = initSinglyLinkedRing[int]() +r.prepend(5) +echo r +r.prepend(4) +echo r +r.prepend(3) +echo r +r.prepend(2) +echo r +r.append(6) +echo r +r.append(7) +echo r +r.append(8) +echo r +r.prepend(1) +echo r diff --git a/tests/stdlib/tsockets.nim b/tests/stdlib/tsockets.nim deleted file mode 100644 index ff566df74..000000000 --- a/tests/stdlib/tsockets.nim +++ /dev/null @@ -1,12 +0,0 @@ -import sockets, os -var s: TSocket -s = socket() -if s == InvalidSocket: osError(osLastError()) - -s.connect("www.google.com", TPort(80)) - -var data: string = "" -s.readLine(data) -echo(data) - - diff --git a/tests/stdlib/tstrutil.nim b/tests/stdlib/tstrutil.nim index 80c2f3870..3db484faa 100644 --- a/tests/stdlib/tstrutil.nim +++ b/tests/stdlib/tstrutil.nim @@ -2,18 +2,18 @@ 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) +# 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" @@ -25,21 +25,34 @@ proc testDelete = 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 +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) + +assert "/1/2/3".rfind('/') == 4 +assert "/1/2/3".rfind('/', 1) == 0 +assert "/1/2/3".rfind('0') == -1 + +assert(toHex(100i16, 32) == "00000000000000000000000000000064") +assert(toHex(-100i16, 32) == "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9C") + +assert(' '.repeat(8)== " ") +assert(" ".repeat(8) == " ") +assert(spaces(8) == " ") + +assert(' '.repeat(0) == "") +assert(" ".repeat(0) == "") +assert(spaces(0) == "") +main() +#OUT ha/home/a1xyz/usr/bin |