test-timeout.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var server = require('./server')
  2. , events = require('events')
  3. , stream = require('stream')
  4. , assert = require('assert')
  5. , request = require('../main.js')
  6. ;
  7. var s = server.createServer();
  8. var expectedBody = "waited";
  9. var remainingTests = 5;
  10. // Request that waits for 200ms
  11. s.on('/timeout', function (req, resp) {
  12. setTimeout(function(){
  13. resp.writeHead(200, {'content-type':'text/plain'})
  14. resp.write(expectedBody)
  15. resp.end()
  16. }, 200);
  17. });
  18. // Scenario that should timeout
  19. var shouldTimeout = {
  20. url: s.url + "/timeout",
  21. timeout:100
  22. }
  23. request(shouldTimeout, function (err, resp, body) {
  24. assert.ok(err == "ETIMEDOUT");
  25. checkDone();
  26. })
  27. // Scenario that shouldn't timeout
  28. var shouldntTimeout = {
  29. url: s.url + "/timeout",
  30. timeout:300
  31. }
  32. request(shouldntTimeout, function (err, resp, body) {
  33. assert.ok(!err);
  34. assert.ok(expectedBody === body)
  35. checkDone();
  36. })
  37. // Scenario with no timeout set, so shouldn't timeout
  38. var noTimeout = {
  39. url: s.url + "/timeout"
  40. }
  41. request(noTimeout, function (err, resp, body) {
  42. assert.ok(!err);
  43. assert.ok(expectedBody === body)
  44. checkDone();
  45. })
  46. // Scenario with a negative timeout value, should be treated a zero or the minimum delay
  47. var negativeTimeout = {
  48. url: s.url + "/timeout",
  49. timeout:-1000
  50. }
  51. request(negativeTimeout, function (err, resp, body) {
  52. assert.ok(err == "ETIMEDOUT");
  53. checkDone();
  54. })
  55. // Scenario with a float timeout value, should be rounded by setTimeout anyway
  56. var floatTimeout = {
  57. url: s.url + "/timeout",
  58. timeout: 100.76
  59. }
  60. request(floatTimeout, function (err, resp, body) {
  61. assert.ok(err == "ETIMEDOUT");
  62. checkDone();
  63. })
  64. function checkDone() {
  65. if(--remainingTests == 0) {
  66. s.close();
  67. console.log("All tests passed.");
  68. }
  69. }