TestServer.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 = 'Basic ' + Buffer.from('user:pass').toString('base64')
  47. if (req.headers.authorization === expectedAuth) {
  48. res.json({ key: 'verysecret' })
  49. } else {
  50. res.status(401).json({ error: 'unauthorized' })
  51. }
  52. })
  53. this.app.post('/json/ignore-request', (req, res) => {
  54. res.json({ msg: 'hello' })
  55. })
  56. // Never returns
  57. this.app.post('/hang', (req, res) => {})
  58. }
  59. start(port) {
  60. return new Promise((resolve, reject) => {
  61. this.server = this.app.listen(port, err => {
  62. if (err) {
  63. reject(err)
  64. } else {
  65. resolve()
  66. }
  67. })
  68. })
  69. }
  70. stop() {
  71. return new Promise((resolve, reject) => {
  72. this.server.close(err => {
  73. if (err) {
  74. reject(err)
  75. } else {
  76. resolve()
  77. }
  78. })
  79. })
  80. }
  81. }
  82. module.exports = { TestServer }