diff options
Diffstat (limited to 'tests/stdlib')
-rw-r--r-- | tests/stdlib/tcount.nim | 29 | ||||
-rw-r--r-- | tests/stdlib/tdialogs.nim | 17 | ||||
-rw-r--r-- | tests/stdlib/tgetfileinfo.nim | 17 | ||||
-rw-r--r-- | tests/stdlib/tircbot.nim | 452 | ||||
-rw-r--r-- | tests/stdlib/tmarshal.nim | 12 | ||||
-rw-r--r-- | tests/stdlib/tmitems.nim | 136 | ||||
-rw-r--r-- | tests/stdlib/tnet.nim | 47 | ||||
-rw-r--r-- | tests/stdlib/tpegs.nim | 28 | ||||
-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/tstrutil.nim | 57 |
12 files changed, 332 insertions, 520 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 deleted file mode 100644 index d161a976d..000000000 --- a/tests/stdlib/tdialogs.nim +++ /dev/null @@ -1,17 +0,0 @@ -# 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)) 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 1b83aab53..a778d2f77 100644 --- a/tests/stdlib/tmarshal.nim +++ b/tests/stdlib/tmarshal.nim @@ -6,11 +6,11 @@ import marshal 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 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/tpegs.nim b/tests/stdlib/tpegs.nim index 1bc2669c3..cceea1693 100644 --- a/tests/stdlib/tpegs.nim +++ b/tests/stdlib/tpegs.nim @@ -533,7 +533,7 @@ proc bounds*(c: TCaptures, 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 @@ -865,7 +865,7 @@ template `=~`*(s: string, pattern: TPeg): expr = ## else: ## echo("syntax error") ## - when not definedInScope(matches): + when not declaredInScope(matches): var matches {.inject.}: array[0..MaxSubpatterns-1, string] match(s, pattern, matches) @@ -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) @@ -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/tstrutil.nim b/tests/stdlib/tstrutil.nim index da65d1f89..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,25 +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) + +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 - -main() -#OUT ha/home/a1xyz/usr/bin +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 |