3

Supposed I have some unit tests that test a web server. For reasons I don't want to discuss here (outside scope ;-)), every test needs a newly started server.

As long as I don't send a request to the server, everything is fine. But once I do, a call to the http server's close function does not work as expected, as all made requests result in kept-alive connections, hence the server waits for 120 seconds before actually closing.

Of course this is not acceptable for running the tests.

At the moment, the only solutions I'd see was either

  • setting the keep-alive timeout to 0, so a call to close will actually close the server,
  • or to start each server on a different port, although this becomes hard to handle when you have lots of tests.

Any other ideas of how to deal with this situation?

PS: I had a asked How do I shutdown a Node.js http(s) server immediately? a while ago, and found a viable way to work around it, but as it seems this workaround does not run reliably in every case, as I am getting strange results from time to time.

Community
  • 1
  • 1
Golo Roden
  • 140,679
  • 96
  • 298
  • 425
  • 1
    How do you start the server in the first place? Are you running the node.js server from node or from other script? – jsalonen Jul 26 '13 at 15:00
  • Also I understand you may have strict requirements, but do you really need to restart your server after each test? I mean could you refactor something in a way that would allow you to run several tests on the same server? – jsalonen Jul 26 '13 at 15:03
  • The server is started programmatically using Node.js, using the usual `http.createServer.listen` stuff. And, unfortunately, yes, I *DO* need to have a new instance on each test :-/ – Golo Roden Jul 26 '13 at 15:11

1 Answers1

2
function createOneRequestServer() {
    var server = http.createServer(function (req, res) {
        res.write('write stuff');
        res.end();
        server.close();
    }).listen(8080);
}

You could also consider using process to fork processes and kill them after you have tested on that process.

var child = fork('serverModuleYouWishToTest.js');

function callback(signalCode) {
    child.kill(signalCode);
}

runYourTest(callback);

This method is desirable because it does not require you to write special cases of your servers to service only one request, and keeps your test code and your production code 100% independant.

MobA11y
  • 18,425
  • 3
  • 49
  • 76