albaHttpServer/tests/test.nim
2024-12-02 16:35:12 -05:00

69 lines
1.8 KiB
Nim

import ../src/albaHttpServer
import httpclient
import tables
import net
import os
import std/options
import std/monoTimes
import asyncdispatch
import sugar
import sequtils
import times
import strformat
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[string]]
let client = collect(for x in 0 .. numOfRequests-1: newAsyncHttpClient())
for x in 0 .. numOfRequests-1:
waiting.add client[x].getContent("http://localhost:" & $port & "/")
let t1 = getMonoTime()
discard await waiting.all()
let totalTimeMs = float64((getMonoTime()-t1).inMilliseconds())
echo totalTimeMs
doAssert(totalTimeMs >= aproxTime and aproxTime+250 >= totalTimeMs, "The dispatcher is not performing within the expected guidelines...")
echo &"{totalTimeMs}ms total time"
proc testWrapper() =
waitfor test()
type MyObject = object
foo : string
bar : string
proc doThing(a : Request, b : MyObject) =
if a.verb != HttpGet:
a.respond(405, "")
sleep sleepTime
a.respond(200, b.foo)
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)
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)