test-httpd.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. const port = 8099;
  5. const file = require("sdk/io/file");
  6. const { pathFor } = require("sdk/system");
  7. const { Loader } = require("sdk/test/loader");
  8. const options = require("@test/options");
  9. const loader = Loader(module);
  10. const httpd = loader.require("sdk/test/httpd");
  11. if (options.parseable || options.verbose)
  12. loader.sandbox("sdk/test/httpd").DEBUG = true;
  13. exports.testBasicHTTPServer = function(assert, done) {
  14. // Use the profile directory for the temporary file as that will be deleted
  15. // when tests are complete
  16. let basePath = pathFor("ProfD");
  17. let filePath = file.join(basePath, 'test-httpd.txt');
  18. let content = "This is the HTTPD test file.\n";
  19. let fileStream = file.open(filePath, 'w');
  20. fileStream.write(content);
  21. fileStream.close();
  22. let srv = httpd.startServerAsync(port, basePath);
  23. // Request this very file.
  24. let Request = require('sdk/request').Request;
  25. Request({
  26. url: "http://localhost:" + port + "/test-httpd.txt",
  27. onComplete: function (response) {
  28. assert.equal(response.text, content);
  29. srv.stop(done);
  30. }
  31. }).get();
  32. };
  33. exports.testDynamicServer = function (assert, done) {
  34. let content = "This is the HTTPD test file.\n";
  35. let srv = httpd.startServerAsync(port);
  36. // See documentation here:
  37. //http://doxygen.db48x.net/mozilla/html/interfacensIHttpServer.html#a81fc7e7e29d82aac5ce7d56d0bedfb3a
  38. //http://doxygen.db48x.net/mozilla/html/interfacensIHttpRequestHandler.html
  39. srv.registerPathHandler("/test-httpd.txt", function handle(request, response) {
  40. // Add text content type, only to avoid error in `Request` API
  41. response.setHeader("Content-Type", "text/plain", false);
  42. response.write(content);
  43. });
  44. // Request this very file.
  45. let Request = require('sdk/request').Request;
  46. Request({
  47. url: "http://localhost:" + port + "/test-httpd.txt",
  48. onComplete: function (response) {
  49. assert.equal(response.text, content);
  50. srv.stop(done);
  51. }
  52. }).get();
  53. };
  54. exports.testAutomaticPortSelection = function (assert, done) {
  55. const srv = httpd.startServerAsync(-1);
  56. const port = srv.identity.primaryPort;
  57. assert.ok(0 <= port && port <= 65535);
  58. srv.stop(done);
  59. };
  60. require('sdk/test').run(exports);