TestServer.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. }
  60. start(port) {
  61. return new Promise((resolve, reject) => {
  62. this.server = this.app.listen(port, err => {
  63. if (err) {
  64. reject(err)
  65. } else {
  66. resolve()
  67. }
  68. })
  69. })
  70. }
  71. stop() {
  72. return new Promise((resolve, reject) => {
  73. this.server.close(err => {
  74. if (err) {
  75. reject(err)
  76. } else {
  77. resolve()
  78. }
  79. })
  80. })
  81. }
  82. }
  83. module.exports = { TestServer }