TestServer.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. const express = require('express')
  2. const bodyParser = require('body-parser')
  3. class TestServer {
  4. constructor(port) {
  5. this.app = express()
  6. this.app.use(bodyParser.json())
  7. this.app.use((req, res, next) => {
  8. this.lastReq = req
  9. next()
  10. })
  11. // Plain text endpoints
  12. this.app.get('/hello', (req, res) => {
  13. res.send('hello')
  14. })
  15. this.largePayload = 'x'.repeat(16 * 1024 * 1024)
  16. this.app.get('/large', (req, res) => {
  17. res.send(this.largePayload)
  18. })
  19. this.app.get('/204', (req, res) => {
  20. res.status(204).end()
  21. })
  22. this.app.get('/empty', (req, res) => {
  23. res.end()
  24. })
  25. this.app.get('/500', (req, res) => {
  26. res.sendStatus(500)
  27. })
  28. this.app.post('/sink', (req, res) => {
  29. req.on('data', () => {})
  30. req.on('end', () => {
  31. res.status(204).end()
  32. })
  33. })
  34. // JSON endpoints
  35. this.app.get('/json/hello', (req, res) => {
  36. res.json({ msg: 'hello' })
  37. })
  38. this.app.post('/json/add', (req, res) => {
  39. const { a, b } = req.body
  40. res.json({ sum: a + b })
  41. })
  42. this.app.get('/json/500', (req, res) => {
  43. res.status(500).json({ error: 'Internal server error' })
  44. })
  45. this.app.get('/json/basic-auth', (req, res) => {
  46. const expectedAuth =
  47. 'Basic ' + Buffer.from('user:pass').toString('base64')
  48. if (req.headers.authorization === expectedAuth) {
  49. res.json({ key: 'verysecret' })
  50. } else {
  51. res.status(401).json({ error: 'unauthorized' })
  52. }
  53. })
  54. this.app.post('/json/ignore-request', (req, res) => {
  55. res.json({ msg: 'hello' })
  56. })
  57. // Never returns
  58. this.app.post('/hang', (req, res) => {})
  59. // Redirect
  60. this.app.get('/redirect/1', (req, res) => {
  61. res.redirect('/redirect/2')
  62. })
  63. this.app.get('/redirect/2', (req, res) => {
  64. res.send('body after redirect')
  65. })
  66. this.app.get('/redirect/empty-location', (req, res) => {
  67. res.sendStatus(302)
  68. })
  69. }
  70. start(port) {
  71. return new Promise((resolve, reject) => {
  72. this.server = this.app.listen(port, err => {
  73. if (err) {
  74. reject(err)
  75. } else {
  76. resolve()
  77. }
  78. })
  79. })
  80. }
  81. stop() {
  82. return new Promise((resolve, reject) => {
  83. this.server.close(err => {
  84. if (err) {
  85. reject(err)
  86. } else {
  87. resolve()
  88. }
  89. })
  90. })
  91. }
  92. }
  93. module.exports = { TestServer }