You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.2 KiB

  1. 'use strict'
  2. const test = require('tape')
  3. const request = require('req-then')
  4. const LocalWebServer = require('../../')
  5. const http = require('http')
  6. function checkResponse (t, status, body) {
  7. return function (response) {
  8. if (status) t.strictEqual(response.res.statusCode, status)
  9. if (body) t.ok(body.test(response.data), 'correct data')
  10. }
  11. }
  12. function fail (t) {
  13. return function (err) {
  14. t.fail('failed: ' + err.stack)
  15. }
  16. }
  17. test('rewrite: proxy', function (t) {
  18. t.plan(2)
  19. const ws = new LocalWebServer()
  20. ws.addRewrite([
  21. { from: '/test/*', to: 'http://registry.npmjs.org/$1' }
  22. ])
  23. const server = ws.getServer()
  24. server.listen(8100, () => {
  25. request('http://localhost:8100/test/')
  26. .then(checkResponse(t, 200, /db_name/))
  27. .then(server.close.bind(server))
  28. .catch(fail(t))
  29. })
  30. })
  31. test('rewrite: proxy, POST', function (t) {
  32. t.plan(1)
  33. const ws = new LocalWebServer()
  34. ws.addRewrite([
  35. { from: '/test/*', to: 'http://registry.npmjs.org/' }
  36. ])
  37. const server = ws.getServer()
  38. server.listen(8100, () => {
  39. request('http://localhost:8100/test/', { data: {} })
  40. .then(checkResponse(t, 405))
  41. .then(server.close.bind(server))
  42. .catch(fail(t))
  43. })
  44. })
  45. test('rewrite: proxy, two url tokens', function (t) {
  46. t.plan(2)
  47. const ws = new LocalWebServer()
  48. ws.addRewrite([
  49. { from: '/:package/:version', to: 'http://registry.npmjs.org/:package/:version' }
  50. ])
  51. const server = ws.getServer()
  52. server.listen(8100, () => {
  53. request('http://localhost:8100/command-line-args/1.0.0')
  54. .then(checkResponse(t, 200, /command-line-args/))
  55. .then(server.close.bind(server))
  56. .catch(fail(t))
  57. })
  58. })
  59. test('rewrite: proxy with port', function (t) {
  60. t.plan(2)
  61. const ws1 = new LocalWebServer()
  62. ws1.addStatic(__dirname)
  63. const ws2 = new LocalWebServer()
  64. ws2.addRewrite([
  65. { from: '/test/*', to: 'http://localhost:9000/$1' }
  66. ])
  67. const server1 = ws1.getServer()
  68. const server2 = ws2.getServer()
  69. server1.listen(9000, () => {
  70. server2.listen(8100, () => {
  71. request('http://localhost:8100/test/file.txt')
  72. .then(checkResponse(t, 200, /one/))
  73. .then(server1.close.bind(server1))
  74. .then(server2.close.bind(server2))
  75. })
  76. })
  77. })