Skip to content

Instantly share code, notes, and snippets.

@naithar
Last active March 7, 2017 13:29
Show Gist options
  • Save naithar/7f26c24dd08c312858d13d4f5e97f728 to your computer and use it in GitHub Desktop.
Save naithar/7f26c24dd08c312858d13d4f5e97f728 to your computer and use it in GitHub Desktop.
Foundation HTTP testing
private func runServer(with condition: ServerSemaphore, delay: TimeInterval? = nil) throws {
let start = 21961
for port in start...(start+100) { //we must find at least one port to bind
do {
serverPort = port
let test = try TestURLSessionServer(port: UInt16(port), delay: delay)
try test.start(started: condition)
try test.readAndRespond() {
test.stop()
}
} catch let e as ServerError {
if e.operation != "bind" { continue }
throw e
}
}
}
public class TestURLSessionServer {
let capitals: [String:String] = ["Nepal":"Kathmandu",
"Peru":"Lima",
"Italy":"Rome",
"USA":"Washington, D.C.",
"country.txt": "A country is a region that is identified as a distinct national entity in political geography"]
let httpServer: _HTTPServer
let delay: TimeInterval?
public init (port: UInt16, delay: TimeInterval? = nil) throws {
httpServer = try _HTTPServer.create(port: port)
self.delay = delay
}
public func start(started: ServerSemaphore) throws {
started.signal()
try httpServer.listen(notify: started)
}
public func readAndRespond(callback: @escaping (Void) -> Void) throws {
if let delay = self.delay {
DispatchQueue.global().asyncAfter(deadline: .now() + delay) {
try? self.httpServer.respond(with: self.process(request: self.httpServer.request()))
callback()
}
} else {
try httpServer.respond(with: process(request: httpServer.request()))
callback()
}
}
func process(request: _HTTPRequest) -> _HTTPResponse {
if request.method == .GET {
return getResponse(uri: request.uri)
} else {
fatalError("Unsupported method!")
}
}
func getResponse(uri: String) -> _HTTPResponse {
if uri == "/country.txt" {
let text = capitals[String(uri.characters.dropFirst())]!
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.characters.count)", body: text)
}
return _HTTPResponse(response: .OK, body: capitals[String(uri.characters.dropFirst())]!)
}
func stop() {
httpServer.stop()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment