暫無描述

middleware-mockserver.js 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /* eslint-env node */
  2. var url = require( "url" );
  3. var fs = require( "fs" );
  4. var getRawBody = require( "raw-body" );
  5. var cspLog = "";
  6. /**
  7. * Keep in sync with /test/mock.php
  8. */
  9. var mocks = {
  10. contentType: function( req, resp ) {
  11. resp.writeHead( 200, {
  12. "content-type": req.query.contentType
  13. } );
  14. resp.end( req.query.response );
  15. },
  16. wait: function( req, resp ) {
  17. var wait = Number( req.query.wait ) * 1000;
  18. setTimeout( function() {
  19. if ( req.query.script ) {
  20. resp.writeHead( 200, { "content-type": "text/javascript" } );
  21. } else {
  22. resp.writeHead( 200, { "content-type": "text/html" } );
  23. resp.end( "ERROR <script>QUnit.assert.ok( true, \"mock executed\" );</script>" );
  24. }
  25. }, wait );
  26. },
  27. name: function( req, resp, next ) {
  28. resp.writeHead( 200 );
  29. if ( req.query.name === "foo" ) {
  30. resp.end( "bar" );
  31. return;
  32. }
  33. getBody( req ).then( function( body ) {
  34. if ( body === "name=peter" ) {
  35. resp.end( "pan" );
  36. } else {
  37. resp.end( "ERROR" );
  38. }
  39. }, next );
  40. },
  41. xml: function( req, resp, next ) {
  42. var content = "<math><calculation>5-2</calculation><result>3</result></math>";
  43. resp.writeHead( 200, { "content-type": "text/xml" } );
  44. if ( req.query.cal === "5-2" ) {
  45. resp.end( content );
  46. return;
  47. }
  48. getBody( req ).then( function( body ) {
  49. if ( body === "cal=5-2" ) {
  50. resp.end( content );
  51. } else {
  52. resp.end( "<error>ERROR</error>" );
  53. }
  54. }, next );
  55. },
  56. atom: function( req, resp, next ) {
  57. resp.writeHead( 200, { "content-type": "atom+xml" } );
  58. resp.end( "<root><element /></root>" );
  59. },
  60. script: function( req, resp ) {
  61. if ( req.query.header === "ecma" ) {
  62. resp.writeHead( 200, { "content-type": "application/ecmascript" } );
  63. } else if ( "header" in req.query ) {
  64. resp.writeHead( 200, { "content-type": "text/javascript" } );
  65. } else {
  66. resp.writeHead( 200, { "content-type": "text/html" } );
  67. }
  68. resp.end( "QUnit.assert.ok( true, \"mock executed\" );" );
  69. },
  70. testbar: function( req, resp ) {
  71. resp.writeHead( 200 );
  72. resp.end(
  73. "this.testBar = 'bar'; " +
  74. "jQuery('#ap').html('bar'); " +
  75. "QUnit.assert.ok( true, 'mock executed');"
  76. );
  77. },
  78. json: function( req, resp ) {
  79. if ( req.query.header ) {
  80. resp.writeHead( 200, { "content-type": "application/json" } );
  81. }
  82. if ( req.query.array ) {
  83. resp.end( JSON.stringify(
  84. [ { name: "John", age: 21 }, { name: "Peter", age: 25 } ]
  85. ) );
  86. } else {
  87. resp.end( JSON.stringify(
  88. { data: { lang: "en", length: 25 } }
  89. ) );
  90. }
  91. },
  92. jsonp: function( req, resp, next ) {
  93. var callback;
  94. if ( Array.isArray( req.query.callback ) ) {
  95. callback = Promise.resolve( req.query.callback[ req.query.callback.length - 1 ] );
  96. } else if ( req.query.callback ) {
  97. callback = Promise.resolve( req.query.callback );
  98. } else if ( req.method === "GET" ) {
  99. callback = Promise.resolve( req.url.match( /^.+\/([^\/?]+)\?.+$/ )[ 1 ] );
  100. } else {
  101. callback = getBody( req ).then( function( body ) {
  102. return body.trim().replace( "callback=", "" );
  103. } );
  104. }
  105. var json = req.query.array ?
  106. JSON.stringify(
  107. [ { name: "John", age: 21 }, { name: "Peter", age: 25 } ]
  108. ) :
  109. JSON.stringify(
  110. { data: { lang: "en", length: 25 } }
  111. );
  112. callback.then( function( cb ) {
  113. resp.end( cb + "(" + json + ")" );
  114. }, next );
  115. },
  116. xmlOverJsonp: function( req, resp ) {
  117. var callback = req.query.callback;
  118. var body = fs.readFileSync( __dirname + "/data/with_fries.xml" ).toString();
  119. resp.writeHead( 200 );
  120. resp.end( callback + "(" + JSON.stringify( body ) + ")\n" );
  121. },
  122. error: function( req, resp ) {
  123. if ( req.query.json ) {
  124. resp.writeHead( 400, { "content-type": "application/json" } );
  125. resp.end( "{ \"code\": 40, \"message\": \"Bad Request\" }" );
  126. } else {
  127. resp.writeHead( 400 );
  128. resp.end( "plain text message" );
  129. }
  130. },
  131. headers: function( req, resp ) {
  132. resp.writeHead( 200, {
  133. "Sample-Header": "Hello World",
  134. "Empty-Header": "",
  135. "Sample-Header2": "Hello World 2",
  136. "List-Header": "Item 1",
  137. "list-header": "Item 2",
  138. "constructor": "prototype collision (constructor)"
  139. } );
  140. req.query.keys.split( "|" ).forEach( function( key ) {
  141. if ( req.headers[ key.toLowerCase() ] ) {
  142. resp.write( key + ": " + req.headers[ key.toLowerCase() ] + "\n" );
  143. }
  144. } );
  145. resp.end();
  146. },
  147. echoData: function( req, resp, next ) {
  148. getBody( req ).then( function( body ) {
  149. resp.end( body );
  150. }, next );
  151. },
  152. echoQuery: function( req, resp ) {
  153. resp.end( req.parsed.search.slice( 1 ) );
  154. },
  155. echoMethod: function( req, resp ) {
  156. resp.end( req.method );
  157. },
  158. echoHtml: function( req, resp, next ) {
  159. resp.writeHead( 200, { "Content-Type": "text/html" } );
  160. resp.write( "<div id='method'>" + req.method + "</div>" );
  161. resp.write( "<div id='query'>" + req.parsed.search.slice( 1 ) + "</div>" );
  162. getBody( req ).then( function( body ) {
  163. resp.write( "<div id='data'>" + body + "</div>" );
  164. resp.end( body );
  165. }, next );
  166. },
  167. etag: function( req, resp ) {
  168. var hash = Number( req.query.ts ).toString( 36 );
  169. var etag = "W/\"" + hash + "\"";
  170. if ( req.headers[ "if-none-match" ] === etag ) {
  171. resp.writeHead( 304 );
  172. resp.end();
  173. return;
  174. }
  175. resp.writeHead( 200, {
  176. "Etag": etag
  177. } );
  178. resp.end();
  179. },
  180. ims: function( req, resp, next ) {
  181. var ts = req.query.ts;
  182. if ( req.headers[ "if-modified-since" ] === ts ) {
  183. resp.writeHead( 304 );
  184. resp.end();
  185. return;
  186. }
  187. resp.writeHead( 200, {
  188. "Last-Modified": ts
  189. } );
  190. resp.end();
  191. },
  192. status: function( req, resp, next ) {
  193. resp.writeHead( Number( req.query.code ) );
  194. resp.end();
  195. },
  196. testHTML: function( req, resp ) {
  197. resp.writeHead( 200, { "Content-Type": "text/html" } );
  198. var body = fs.readFileSync( __dirname + "/data/test.include.html" ).toString();
  199. body = body.replace( /{{baseURL}}/g, req.query.baseURL );
  200. resp.end( body );
  201. },
  202. cspFrame: function( req, resp ) {
  203. resp.writeHead( 200, {
  204. "Content-Type": "text/html",
  205. "Content-Security-Policy": "default-src 'self'; report-uri /base/test/data/mock.php?action=cspLog"
  206. } );
  207. var body = fs.readFileSync( __dirname + "/data/csp.include.html" ).toString();
  208. resp.end( body );
  209. },
  210. cspNonce: function( req, resp ) {
  211. var testParam = req.query.test ? "-" + req.query.test : "";
  212. resp.writeHead( 200, {
  213. "Content-Type": "text/html",
  214. "Content-Security-Policy": "script-src 'nonce-jquery+hardcoded+nonce'; report-uri /base/test/data/mock.php?action=cspLog"
  215. } );
  216. var body = fs.readFileSync(
  217. __dirname + "/data/csp-nonce" + testParam + ".html" ).toString();
  218. resp.end( body );
  219. },
  220. cspLog: function( req, resp ) {
  221. cspLog = "error";
  222. resp.writeHead( 200 );
  223. resp.end();
  224. },
  225. cspClean: function( req, resp ) {
  226. cspLog = "";
  227. resp.writeHead( 200 );
  228. resp.end();
  229. },
  230. errorWithScript: function( req, resp ) {
  231. if ( req.query.withScriptContentType ) {
  232. resp.writeHead( 404, { "Content-Type": "application/javascript" } );
  233. } else {
  234. resp.writeHead( 404 );
  235. }
  236. if ( req.query.callback ) {
  237. resp.end( req.query.callback + "( {\"status\": 404, \"msg\": \"Not Found\"} )" );
  238. } else {
  239. resp.end( "QUnit.assert.ok( false, \"Mock return erroneously executed\" );" );
  240. }
  241. }
  242. };
  243. var handlers = {
  244. "test/data/mock.php": function( req, resp, next ) {
  245. if ( !mocks[ req.query.action ] ) {
  246. resp.writeHead( 400 );
  247. resp.end( "Invalid action query.\n" );
  248. console.log( "Invalid action query:", req.method, req.url );
  249. return;
  250. }
  251. mocks[ req.query.action ]( req, resp, next );
  252. },
  253. "test/data/support/csp.log": function( req, resp ) {
  254. resp.writeHead( 200 );
  255. resp.end( cspLog );
  256. },
  257. "test/data/404.txt": function( req, resp ) {
  258. resp.writeHead( 404 );
  259. resp.end( "" );
  260. }
  261. };
  262. /**
  263. * Connect-compatible middleware factory for mocking server responses.
  264. * Used by Ajax unit tests when run via Karma.
  265. *
  266. * Despite Karma using Express, it uses Connect to deal with custom middleware,
  267. * which passes the raw Node Request and Response objects instead of the
  268. * Express versions of these (e.g. no req.path, req.query, resp.set).
  269. */
  270. function MockserverMiddlewareFactory() {
  271. /**
  272. * @param {http.IncomingMessage} req
  273. * @param {http.ServerResponse} resp
  274. * @param {Function} next Continue request handling
  275. */
  276. return function( req, resp, next ) {
  277. var parsed = url.parse( req.url, /* parseQuery */ true ),
  278. path = parsed.pathname.replace( /^\/base\//, "" ),
  279. query = parsed.query,
  280. subReq = Object.assign( Object.create( req ), {
  281. query: query,
  282. parsed: parsed
  283. } );
  284. if ( /^test\/data\/mock.php\//.test( path ) ) {
  285. // Support REST-like Apache PathInfo
  286. path = "test\/data\/mock.php";
  287. }
  288. if ( !handlers[ path ] ) {
  289. next();
  290. return;
  291. }
  292. handlers[ path ]( subReq, resp, next );
  293. };
  294. }
  295. function getBody( req ) {
  296. return req.method !== "POST" ?
  297. Promise.resolve( "" ) :
  298. getRawBody( req, {
  299. encoding: true
  300. } );
  301. }
  302. module.exports = MockserverMiddlewareFactory;