albaHttpServer/tests/testExceptions.nim
2025-01-13 19:08:03 -05:00

74 lines
1.7 KiB
Nim

import ../src/albaHttpServer
import httpclient
import net
import os
import std/monoTimes
import std/options
import asyncdispatch
import sugar
import sequtils
import times
import strformat
import tables
const port = 7050
const sleepTime = 1000
const numOfThreads = 10
const numOfRequests = 30
const aproxTime = sleepTime*(numOfRequests/numOfThreads)
proc test() {.async.} =
sleep 1000
var waiting : seq[Future[AsyncResponse]]
let client = collect(for x in 0 .. numOfRequests-1: newAsyncHttpClient())
for x in 0 .. numOfRequests-1:
waiting.add client[x].request("http://localhost:" & $port & "/")
let t1 = getMonoTime()
let responses = await waiting.all()
doAssert(responses.all(x=> code(x) == HttpCode(500)))
let totalTimeMs = float64((getMonoTime()-t1).inMilliseconds())
echo totalTimeMs
echo &"{totalTimeMs}ms total time"
proc testWrapper() =
waitfor test()
type MyObject = object
foo : string
bar : string
proc doThing(a : Request, b : MyObject) =
raise new CatchableError
proc raiseException(a : Request, b : MyObject) =
echo "OH NO ISSUE LOLE"
a.respond(500, "")
proc init() : MyObject =
result.foo = "hello"
result.bar = "world"
var paths : Table[string, proc(a: Request, b: MyObject){.gcsafe.}]
paths["/"] = doThing
let handler = initHandler[MyObject](init, paths, numOfThreads, raiseException)
let socket = newSocket()
socket.setSockOpt(OptReusePort, true)
socket.bindAddr(Port(port))
socket.listen()
var t : Thread[void]
createThread(t, testWrapper)
for x in 0 .. numOfRequests-1:
var request = getRequest(socket)
#Checks for invalid requests.
if request.isNone():
continue
else:
let req = request.get()
dispatch(req, handler)
echo &"The total time should be about {aproxTime}ms."
joinThread(t)