Don't run non-test code when defined(testing)

This commit is contained in:
Oleh Prypin
2015-04-21 14:37:29 +03:00
parent d203d6fad4
commit 32109a7867
46 changed files with 104 additions and 82 deletions

View File

@@ -205,7 +205,7 @@ proc setEncoding*(connection: TDbConn, encoding: string): bool {.
exec(connection, sql"PRAGMA encoding = ?", [encoding])
result = connection.getValue(sql"PRAGMA encoding") == encoding
when isMainModule:
when not defined(testing) and isMainModule:
var db = open("db.sql", "", "", "")
exec(db, sql"create table tbl1(one varchar(10), two smallint)", [])
exec(db, sql"insert into tbl1 values('hello!',10)", [])

View File

@@ -499,7 +499,7 @@ template withEvents*(surf: PSurface, event: expr, actions: stmt): stmt {.
if sdl.init(sdl.INIT_VIDEO) < 0: raiseEGraphics()
if sdl_ttf.init() < 0: raiseEGraphics()
when isMainModule:
when not defined(testing) and isMainModule:
var surf = newScreenSurface(800, 600)
surf.fillSurface(colWhite)

View File

@@ -82,7 +82,7 @@ proc close*(sock: TSecureSocket) =
ERR_print_errors_fp(stderr)
raiseOSError(osLastError())
when isMainModule:
when not defined(testing) and isMainModule:
var s: TSecureSocket
echo connect(s, "smtp.gmail.com", 465)

View File

@@ -1250,6 +1250,6 @@ proc rstToHtml*(s: string, options: TRstParseOptions,
renderRstToOut(d, rst, result)
when isMainModule:
when not defined(testing) and isMainModule:
echo rstToHtml("*Hello* **world**!", {},
newStringTable(modeStyleInsensitive))

View File

@@ -221,7 +221,7 @@ proc spawn*[TIn](p: var TActorPool[TIn, void], input: TIn,
setupTask()
schedule()
when isMainModule:
when not defined(testing) and isMainModule:
var
a: TActorPool[int, void]
createActorPool(a)

View File

@@ -300,7 +300,7 @@ proc newAsyncFtpClient*(address: string, port = Port(21),
result.dsockConnected = false
result.csock = newAsyncSocket()
when isMainModule:
when not defined(testing) and isMainModule:
var ftp = newAsyncFtpClient("example.com", user = "test", pass = "test")
proc main(ftp: AsyncFtpClient) {.async.} =
await ftp.connect()

View File

@@ -260,7 +260,7 @@ proc close*(server: AsyncHttpServer) =
## Terminates the async http server instance.
server.socket.close()
when isMainModule:
when not defined(testing) and isMainModule:
proc main =
var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =

View File

@@ -660,7 +660,7 @@ proc len*(disp: Dispatcher): int =
## Retrieves the amount of delegates in ``disp``.
return disp.delegates.len
when isMainModule:
when not defined(testing) and isMainModule:
proc testConnect(s: AsyncSocket, no: int) =
echo("Connected! " & $no)

View File

@@ -458,7 +458,7 @@ proc isClosed*(socket: AsyncSocket): bool =
## Determines whether the socket has been closed.
return socket.closed
when isMainModule:
when not defined(testing) and isMainModule:
type
TestCases = enum
HighClient, LowClient, LowServer

View File

@@ -525,7 +525,7 @@ proc get*[K,V](table: var PConcTable[K,V], key: var K): V =
#Tests ----------------------------
when isMainModule:
when not defined(testing) and isMainModule:
import locks, times, mersenne
const

View File

@@ -292,12 +292,15 @@ when isMainModule:
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
when not defined(testing):
#r.del "def"
for w in r.items:
echo w
for w in r.itemsWithPrefix("de"):
echo w

View File

@@ -197,7 +197,7 @@ proc empty*(s: IntSet): bool {.inline, deprecated.} =
## worked reliably and so is deprecated.
result = s.counter == 0
when isMainModule:
when not defined(testing) and isMainModule:
var x = initIntSet()
x.incl(1)
x.incl(2)

View File

@@ -493,7 +493,8 @@ when isMainModule:
block: # filter iterator test
let numbers = @[1, 4, 5, 8, 9, 7, 4]
for n in filter(numbers, proc (x: int): bool = x mod 2 == 0):
echo($n)
when not defined(testing):
echo($n)
# echoes 4, 8, 4 in separate lines
block: # keepIf test
@@ -616,4 +617,5 @@ when isMainModule:
#doAssert a.repeat(-1) == @[] # will not compile!
doAssert b.repeat(3) == @[]
echo "Finished doc tests"
when not defined(testing):
echo "Finished doc tests"

View File

@@ -970,6 +970,7 @@ when isMainModule and not defined(release):
if s <= i or mustRehash(s, i):
echo "performance issue: rightSize() will not elide enlarge() at ", i
echo "Micro tests run successfully."
when not defined(testing):
echo "Micro tests run successfully."
testModule()

View File

@@ -78,7 +78,7 @@ proc advice*(s: var ThreadPoolState): ThreadPoolAdvice =
result = doNothing
inc s.calls
when isMainModule:
when not defined(testing) and isMainModule:
proc busyLoop() =
while true:
discard random(80)

View File

@@ -53,7 +53,7 @@ proc setCookie*(key, value: string, expires: TimeInfo,
format(expires, "ddd',' dd MMM yyyy HH:mm:ss 'UTC'"),
noname, secure, httpOnly)
when isMainModule:
when not defined(testing) and isMainModule:
var tim = Time(int(getTime()) + 76 * (60 * 60 * 24))
echo(setCookie("test", "value", tim.getGMTime()))

View File

@@ -451,7 +451,7 @@ proc convert*(s: string, destEncoding = "UTF-8",
finally:
close(c)
when isMainModule:
when not defined(testing) and isMainModule:
let
orig = "öäüß"
cp1252 = convert(orig, "CP1252", "UTF-8")

View File

@@ -198,7 +198,7 @@ proc register*(d: Dispatcher, monitor: FSMonitor,
var deleg = toDelegate(monitor)
d.register(deleg)
when isMainModule:
when not defined(testing) and isMainModule:
proc main =
var disp = newDispatcher()
var monitor = newMonitor()

View File

@@ -629,7 +629,7 @@ when isMainModule:
if not d.poll(): break
main()
when isMainModule and false:
when not defined(testing) and isMainModule:
var ftp = ftpClient("example.com", user = "foo", pass = "bar")
ftp.connect()
echo ftp.pwd()

View File

@@ -186,8 +186,9 @@ when isMainModule:
assert( z["first"]["one"] == 1) # retrieve from first inner table
assert( z["second"]["red"] == 10) # retrieve from second inner table
for k,v in pairs(z):
echo( "$# ($#) ->" % [k,$len(v)] )
#for k2,v2 in pairs(v):
# echo( " $# <-> $#" % [k2,$v2] )
echo()
when not defined(testing) :
for k,v in pairs(z):
echo( "$# ($#) ->" % [k,$len(v)] )
#for k2,v2 in pairs(v):
# echo( " $# <-> $#" % [k2,$v2] )
echo()

View File

@@ -482,7 +482,7 @@ macro `var`*(e: expr): expr {.immediate.} =
let e = callsite()
result = xmlCheckedTag(e, "var", commonAttr)
when isMainModule:
when not defined(testing) and isMainModule:
var nim = "Nim"
echo h1(a(href="http://nim-lang.org", nim))
echo form(action="test", `accept-charset` = "Content-Type")

View File

@@ -593,7 +593,7 @@ proc loadHtml*(path: string): XmlNode =
var errors: seq[string] = @[]
result = loadHtml(path, errors)
when isMainModule:
when not defined(testing) and isMainModule:
import os
var errors: seq[string] = @[]

View File

@@ -819,7 +819,7 @@ proc get*(client: AsyncHttpClient, url: string): Future[Response] {.async.} =
result = await client.request(redirectTo, httpGET)
lastUrl = redirectTo
when isMainModule:
when not defined(testing) and isMainModule:
when true:
# Async
proc main() {.async.} =

View File

@@ -514,7 +514,7 @@ proc close*(h: PAsyncHTTPServer) =
## Closes the ``PAsyncHTTPServer``.
h.asyncSocket.close()
when isMainModule:
when not defined(testing) and isMainModule:
var counter = 0
var s: TServer

View File

@@ -1153,19 +1153,22 @@ when false:
when isMainModule:
#var node = parse("{ \"test\": null }")
#echo(node.existsKey("test56"))
var parsed = parseFile("tests/testdata/jsontest.json")
var parsed2 = parseFile("tests/testdata/jsontest2.json")
echo(parsed)
echo()
echo(pretty(parsed, 2))
echo()
echo(parsed["keyÄÖöoßß"])
echo()
echo(pretty(parsed2))
try:
echo(parsed["key2"][12123])
raise newException(ValueError, "That line was expected to fail")
except IndexError: echo()
when not defined(testing):
echo(parsed)
echo()
echo(pretty(parsed, 2))
echo()
echo(parsed["keyÄÖöoßß"])
echo()
echo(pretty(parsed2))
try:
echo(parsed["key2"][12123])
raise newException(ValueError, "That line was expected to fail")
except IndexError: echo()
let testJson = parseJson"""{ "a": [1, 2, 3, 4], "b": "asd" }"""
# nil passthrough
@@ -1228,11 +1231,12 @@ when isMainModule:
]
assert j3 == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}]
discard """
while true:
var json = stdin.readLine()
var node = parse(json)
echo(node)
echo()
echo()
"""
when not defined(testing):
discard """
while true:
var json = stdin.readLine()
var node = parse(json)
echo(node)
echo()
echo()
"""

View File

@@ -278,7 +278,7 @@ proc getLogFilter*(): Level =
# --------------
when isMainModule:
when not defined(testing) and isMainModule:
var L = newConsoleLogger()
var fL = newFileLogger("test.log", fmtStr = verboseFmtStr)
var rL = newRollingFileLogger("rolling.log", fmtStr = verboseFmtStr)

View File

@@ -244,7 +244,7 @@ proc to*[T](data: string): T =
var tab = initTable[BiggestInt, pointer]()
loadAny(newStringStream(data), toAny(result), tab)
when isMainModule:
when not defined(testing) and isMainModule:
template testit(x: expr) = echo($$to[type(x)]($$x))
var x: array[0..4, array[0..4, string]] = [

View File

@@ -372,7 +372,9 @@ when isMainModule and not defined(JS):
randomize(seed)
for i in 0..SIZE-1:
assert buf[i] == random(high(int)), "non deterministic random seeding"
echo "random values equal after reseeding"
when not defined(testing):
echo "random values equal after reseeding"
# Check for no side effect annotation
proc mySqrt(num: float): float {.noSideEffect.} =

View File

@@ -32,7 +32,7 @@ proc getNum*(m: var MersenneTwister): int =
return int(y)
# Test
when isMainModule:
when not defined(testing) and isMainModule:
var mt = newMersenneTwister(2525)
for i in 0..99:

View File

@@ -516,7 +516,7 @@ proc register*(mimedb: var MimeDB, ext: string, mimetype: string) =
## Adds ``mimetype`` to the ``mimedb``.
mimedb.mimes[ext] = mimetype
when isMainModule:
when not defined(testing) and isMainModule:
var m = newMimetypes()
echo m.getMimetype("mp4")
echo m.getExt("text/html")

View File

@@ -88,6 +88,6 @@ proc generatedTime*(oid: Oid): Time =
bigEndian32(addr(tmp), addr(dummy))
result = Time(tmp)
when isMainModule:
when not defined(testing) and isMainModule:
let xo = genOid()
echo xo.generatedTime

View File

@@ -166,7 +166,7 @@ proc close*(my: var CsvParser) {.inline.} =
## closes the parser `my` and its associated input stream.
lexbase.close(my)
when isMainModule:
when not defined(testing) and isMainModule:
import os
var s = newFileStream(paramStr(1), fmRead)
if s == nil: quit("cannot open the file" & paramStr(1))

View File

@@ -1330,7 +1330,7 @@ proc renderSQL*(n: SqlNode): string =
result = ""
ra(n, result, 0)
when isMainModule:
when not defined(testing) and isMainModule:
echo(renderSQL(parseSQL(newStringStream("""
CREATE TYPE happiness AS ENUM ('happy', 'very happy', 'ecstatic');
CREATE TABLE holidays (

View File

@@ -324,7 +324,9 @@ iterator interpolatedFragments*(s: string): tuple[kind: InterpolatedKind,
when isMainModule:
for k, v in interpolatedFragments("$test{} $this is ${an{ example}} "):
echo "(", k, ", \"", v, "\")"
when not defined(testing):
echo "(", k, ", \"", v, "\")"
var value = 0
discard parseHex("0x38", value)
assert value == 56

View File

@@ -628,7 +628,7 @@ proc next*(my: var XmlParser) =
my.kind = xmlError
my.state = stateNormal
when isMainModule:
when not defined(testing) and isMainModule:
import os
var s = newFileStream(paramStr(1), fmRead)
if s == nil: quit("cannot open the file" & paramStr(1))

View File

@@ -1080,7 +1080,7 @@ proc assertListsIdentical(listA, listB: seq[string]) =
assert(item == listB[i])
i = i + 1
when isMainModule:
when not defined(testing) and isMainModule:
when false:
var r = open()

View File

@@ -296,7 +296,7 @@ proc contains*(s: Selector, key: SelectorKey): bool =
TReadyInfo: ReadyInfo, PSelector: Selector].}
when isMainModule and not defined(nimdoc):
when not defined(testing) and isMainModule and not defined(nimdoc):
# Select()
import sockets
type

View File

@@ -253,7 +253,7 @@ proc close*(smtp: AsyncSmtp) {.async.} =
await smtp.sock.send("QUIT\c\L")
smtp.sock.close()
when isMainModule:
when not defined(testing) and isMainModule:
#var msg = createMessage("Test subject!",
# "Hello, my name is dom96.\n What\'s yours?", @["dominik@localhost"])
#echo(msg)

View File

@@ -1402,14 +1402,16 @@ when isMainModule:
doAssert align("a", 0) == "a"
doAssert align("1232", 6) == " 1232"
doAssert align("1232", 6, '#') == "##1232"
echo wordWrap(""" this is a long text -- muchlongerthan10chars and here
it goes""", 10, false)
when not defined(testing):
echo wordWrap(""" this is a long text -- muchlongerthan10chars and here
it goes""", 10, false)
doAssert formatBiggestFloat(0.00000000001, ffDecimal, 11) == "0.00000000001"
doAssert formatBiggestFloat(0.00000000001, ffScientific, 1) == "1.0e-11"
doAssert "$# $3 $# $#" % ["a", "b", "c"] == "a c b c"
echo formatSize(1'i64 shl 31 + 300'i64) # == "4,GB"
echo formatSize(1'i64 shl 31)
when not defined(testing):
echo formatSize(1'i64 shl 31 + 300'i64) # == "4,GB"
echo formatSize(1'i64 shl 31)
doAssert "$animal eats $food." % ["animal", "The cat", "food", "fish"] ==
"The cat eats fish."

View File

@@ -386,8 +386,9 @@ when isMainModule:
longishA,
longish)"""
echo "type TMyEnum* = enum\n $', '2i'\n '{..}" % ["fieldA",
"fieldB", "FiledClkad", "fieldD", "fieldE", "longishFieldName"]
when not defined(testing):
echo "type TMyEnum* = enum\n $', '2i'\n '{..}" % ["fieldA",
"fieldB", "FiledClkad", "fieldD", "fieldE", "longishFieldName"]
doAssert subex"$1($', '{2..})" % ["f", "a", "b", "c"] == "f(a, b, c)"
@@ -395,7 +396,8 @@ when isMainModule:
doAssert subex"$['''|'|''''|']']#" % "0" == "'|"
echo subex("type\n TEnum = enum\n $', '40c'\n '{..}") % [
"fieldNameA", "fieldNameB", "fieldNameC", "fieldNameD"]
when not defined(testing):
echo subex("type\n TEnum = enum\n $', '40c'\n '{..}") % [
"fieldNameA", "fieldNameB", "fieldNameC", "fieldNameD"]

View File

@@ -375,7 +375,7 @@ when not defined(windows):
result = stdin.readChar()
discard fd.tcsetattr(TCSADRAIN, addr oldMode)
when isMainModule:
when not defined(testing) and isMainModule:
system.addQuitProc(resetAttributes)
write(stdout, "never mind")
eraseLine()

View File

@@ -1036,8 +1036,9 @@ when isMainModule:
# Tue 19 Jan 03:14:07 GMT 2038
var t = getGMTime(fromSeconds(2147483647))
echo t.format("ddd dd MMM hh:mm:ss ZZZ yyyy")
echo t.format("ddd ddMMMhhmmssZZZyyyy")
when not defined(testing):
echo t.format("ddd dd MMM hh:mm:ss ZZZ yyyy")
echo t.format("ddd ddMMMhhmmssZZZyyyy")
assert t.format("ddd dd MMM hh:mm:ss ZZZ yyyy") == "Tue 19 Jan 03:14:07 UTC 2038"
assert t.format("ddd ddMMMhh:mm:ssZZZyyyy") == "Tue 19Jan03:14:07UTC2038"
@@ -1112,4 +1113,5 @@ when isMainModule:
# Kitchen = "3:04PM"
s = "3:04PM"
f = "h:mmtt"
echo "Kitchen: " & $s.parse(f)
when not defined(testing):
echo "Kitchen: " & $s.parse(f)

View File

@@ -70,5 +70,6 @@ proc unidecode*(s: string): string =
when isMainModule:
loadUnidecodeTable("lib/pure/unidecode/unidecode.dat")
echo unidecode("Äußerst")
when not defined(testing):
echo unidecode("Äußerst")

View File

@@ -155,7 +155,7 @@ proc loadXMLFile*(path: string): PDocument =
return loadXMLStream(s)
when isMainModule:
when not defined(testing) and isMainModule:
var xml = loadXMLFile("nim/xmldom/test.xml")
#echo(xml.getElementsByTagName("m:test2")[0].namespaceURI)
#echo(xml.getElementsByTagName("bla:test")[0].namespaceURI)

View File

@@ -143,7 +143,7 @@ proc loadXml*(path: string): XmlNode =
result = loadXml(path, errors)
if errors.len > 0: raiseInvalidXml(errors)
when isMainModule:
when not defined(testing) and isMainModule:
import os
var errors: seq[string] = @[]

View File

@@ -2710,7 +2710,7 @@ proc workspace_window_set_icon*(w: ptr TWorkspaceWindow, icon: ptr TImage){.
claro_base_init()
claro_graphics_init()
when isMainModule:
when not defined(testing) and isMainModule:
var w = newWindow(nil, newBounds(100, 100, 230, 230), 0)
window_set_title(w, "Hello, World!")