test-timeout.js 2.2 KB

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