Last active
October 21, 2020 23:14
-
-
Save dexterous/43c2615c3c2829a9da34815637ab8bf3 to your computer and use it in GitHub Desktop.
Quick and dirty HTTP server for functional tests that presents itself as a Future.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.CompletableFuture | |
import java.util.concurrent.TimeUnit | |
import java.util.concurrent.CancellationException | |
import java.util.concurrent.TimeoutException | |
import java.net.InetSocketAddress | |
import com.sun.net.httpserver.HttpServer | |
import com.sun.net.httpserver.HttpHandler | |
import com.sun.net.httpserver.HttpExchange | |
class CompletableHTTPServer extends CompletableFuture<Boolean> implements HttpHandler { | |
private final HttpServer server | |
private final String targetUri | |
private Closure test | |
CompletableHTTPServer(String uri) { | |
server = HttpServer.create(new InetSocketAddress(60000), 1) | |
targetUri = uri | |
} | |
CompletableHTTPServer should(Closure exchangeVerifier) { | |
test = exchangeVerifier | |
server.with { | |
createContext(targetUri, this) | |
start() | |
} | |
return this | |
} | |
void handle(HttpExchange exchange) { | |
complete(test(exchange) as Boolean) | |
exchange.sendResponseHeaders(200, -1) | |
server.stop(0) | |
} | |
Integer getPort() { | |
server.address.port | |
} | |
void stop() { | |
cancel(true) | |
server.stop(0) | |
} | |
Boolean verify(Integer time, TimeUnit unit) { | |
try { | |
return get(time, unit) | |
} catch (CancellationException x) { | |
return false | |
} catch (TimeoutException x) { | |
return false | |
} | |
} | |
} | |
def server = new CompletableHTTPServer('/foo').should { it.requestMethod == 'GET' } | |
println(""" | |
* run `curl http://localhost:${server.port}/foo` within the next 5 seconds to PASS; or | |
* run `curl -X POST http://localhost:${server.port}/foo` within the next 5 seconds to FAIL; or | |
* wait 5 seconds to FAIL; or | |
""") | |
assert server.verify(5, TimeUnit.SECONDS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment