Lab.experiment('WEB VIEW API', function() { Lab.experiment('GET /{view_name}', function() { Lab.test("retrieves index", function(done) { var options = { method: "GET", url: "/" }; server.inject(options, function(response) { var result = response.result; Lab.expect(response.statusCode).to.equal(200); assert(/html>/.test(result)); assert(/html/.test(response.headers["content-type"])); done(); }); }); Lab.test("retrieves about view", function(done) { var options = { method: "GET", url: "/about" }; server.inject(options, function(response) { Lab.expect(response.statusCode).to.equal(200); assert(/html/.test(response.headers["content-type"])); done(); }); }); Lab.test("Not found error when view does not exist.", function(done) { var options = { method: "GET", url: "/non_view_name" }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 404); assert.equal(result.error, 'Not Found'); done(); }); }); }); });
Lab.experiment('args', function() { Lab.it('should load the global args variable', function(done) { var service = Service.allServices()[0]; Lab.expect(service.args['--batman']).to.eql('greatest-detective'); done(); }); Lab.it('should override global args with service specific args', function(done) { var service = Service.allServices()[0]; Lab.expect(service.args['--dog']).to.eql('also-cute'); done(); }); Lab.it('should handle an object rather than a value for service args', function(done) { var service = Service.allServices()[0]; Lab.expect(service.args['--dog']).to.eql('also-cute'); done(); }); Lab.it('should handle an object rather than a value for global args', function(done) { var service = Service.allServices()[2]; Lab.expect(service.args['--frontdoor-url']).to.eql('http://127.0.0.1:8080'); done(); }); Lab.experiment('array arguments', function() { Lab.it('should handle array args', function(done) { var service = Service.allServices()[1]; Lab.expect(service.args.indexOf('--apple')).to.be.gt(-1); done(); }); Lab.it('should combine global args with service level args', function(done) { Config({ serviceJsonPath: './test/fixtures/args-service.json' }); var service = Service.allServices()[0]; Lab.expect(service.args[0]).to.eql('a'); Lab.expect(service.args.indexOf("--apple")).to.not.eql(-1); done(); }); }); });
Lab.experiment("Orders:", function () { Lab.test("post endpoint recieves Order", function (done) { var assertions = { logStatus: "success" }; var options = { method: "POST", url: "/api/orders", credentials: creds, payload: { farmer: "test 1", farmerInitials: "t1", notes: "Nothing to report", price: [0.5, 1], quantity: [2, 1], unit: ["oz", "oz"], transportation: "true", productName: ["oregano", "tomillo"], } }; server.inject(options, function (response) { //console.error(response); var result = response.result; Lab.expect(response.statusCode).to.equal(200); Lab.expect(result).to.be.instanceof(Object); Lab.expect(result.logStatus).to.equal(assertions.logStatus); done(); }); }); });
Lab.experiment('USER API', function() { Lab.experiment('GET /api/users/id', function() { Lab.test("retrieves public user object for a user when valid id sent", function(done) { var sample_mongo_id = support.fakes.credentials().id; var options = { method: "GET", url: "/api/users/" + sample_mongo_id }; server.inject(options, function(response) { var result = response.result; Lab.expect(response.statusCode).to.equal(200); Lab.expect(result).to.be.instanceof(Object); assert.equal(result.id, sample_mongo_id); assert(!result.email); done(); }); }); Lab.test("retrieves self user object for a user when valid id sent", function(done) { var creds = support.fakes.credentials(); var options = { method: "GET", url: "/api/users/" + creds.id, credentials: creds }; server.inject(options, function(response) { var result = response.result; Lab.expect(response.statusCode).to.equal(200); Lab.expect(result).to.be.instanceof(Object); assert.deepEqual(creds, result); done(); }); }); Lab.test("returns error when not valid id", function(done) { var options = { method: "GET", url: "/api/users/random54" }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 400); assert.equal(result.error, 'Bad Request'); done(); }); }); Lab.test("returns error when id does not exist", function(done) { var options = { method: "GET", url: "/api/users/" + support.fakes.mongo_id() }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 404); assert.equal(result.error, 'Not Found'); done(); }); }); }); Lab.experiment('PUT /api/users/id', function() { Lab.test("returns 200 and updated object.", function(done) { var creds = support.fakes.credentials(); var bio = 'This is my new bio. ' + Math.random(); var options = { method: "PUT", url: "/api/users/" + creds.id, credentials: creds, payload: { bio: bio } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 200); assert.equal(result.bio, bio); done(); }); }); Lab.test("returns error when no acceptable fields.", function(done) { var creds = support.fakes.credentials(); var options = { method: "PUT", url: "/api/users/" + creds.id, credentials: creds, payload: { hello: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 400); assert.equal(result.error, 'Bad Request'); done(); }); }); Lab.test("returns error when trying to edit a different user.", function(done) { var options = { method: "PUT", url: "/api/users/" + support.fakes.mongo_id(), credentials: support.fakes.credentials(), payload: { bio: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 403); assert.equal(result.error, 'Forbidden'); done(); }); }); Lab.test("returns error when unauthed", function(done) { var options = { method: "PUT", url: "/api/users/" + support.fakes.mongo_id(), payload: { bio: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 401); assert.equal(result.error, 'Unauthorized'); done(); }); }); Lab.test("returns error when not valid id", function(done) { var options = { method: "PUT", url: "/api/users/random45", credentials: support.fakes.credentials(), payload: { bio: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 400); assert.equal(result.error, 'Bad Request'); done(); }); }); }); });
Lab.experiment('Users', function () { Lab.test('main endpoint', function (done) { var options = { method: 'GET', url: '/' }; server.inject(options, function (resp) { var result = resp.result; Lab.expect(resp.statusCode).to.equal(200); Lab.expect(result).to.be.a('string'); Lab.expect(result).to.equal('Hello, world!'); done(); }); }); Lab.test('adding a param', function (done) { var options = { method: 'GET', url: '/Node' }; server.inject(options, function (resp) { var result = resp.result; Lab.expect(resp.statusCode).to.equal(200); Lab.expect(result).to.be.a('string'); Lab.expect(result).to.equal('Hello, Node!'); done(); }); }); Lab.test('adding a param', function (done) { var options = { method: 'GET', url: '/Tod/Copper' }; server.inject(options, function (resp) { var result = resp.result; Lab.expect(resp.statusCode).to.equal(200); Lab.expect(result).to.be.a('string'); Lab.expect(result).to.equal('Hello, Tod and Copper!'); done(); }); }); Lab.test('adding a param', function (done) { var options = { method: 'GET', url: '/Tod/Copper/Bob' }; server.inject(options, function (resp) { var result = resp.result; Lab.expect(resp.statusCode).to.equal(200); Lab.expect(result).to.be.a('string'); Lab.expect(result).to.equal('Hello, Tod, Copper, and Bob!'); done(); }); }); });
Lab.experiment('files get read from buildDirectory', function () { var tmpHash = crypto.randomBytes(16).toString('hex'); var buildDir = path.join(os.tmpdir(), tmpHash); Lab.before(function (done) { async.series([ function (next) { fs.mkdir(buildDir, next); }, function (next) { fs.writeFile(path.join(buildDir, 'app.deadbeef.min.js'), 'javascript!' + tmpHash, next); }, function (next) { fs.writeFile(path.join(buildDir, 'app.deadbeef.min.css'), 'cascading stylesheets!' + tmpHash, next); }, function (next) { fs.writeFile(path.join(buildDir, 'readme.md'), '# this file will be ignored in the builddir', next); } ], function () { var options = { main: __dirname + '/../fixtures/app/app.js', jsFileName: 'app', cssFileName: 'app', buildDirectory: buildDir, stylesheets: [ __dirname + '/../fixtures/stylesheets/style.css' ] }; moonboots = new Moonboots(options); moonboots.on('ready', done); }); }); Lab.after(function (done) { async.series([ function (next) { fs.unlink(path.join(buildDir, 'app.deadbeef.min.js'), next); }, function (next) { fs.unlink(path.join(buildDir, 'app.deadbeef.min.css'), next); }, function (next) { fs.unlink(path.join(buildDir, 'readme.md'), next); }, function (next) { fs.rmdir(buildDir, next); } ], function (err) { if (err) {throw err; } done(); }); }); Lab.test('htmlContext', function (done) { var context = moonboots.htmlContext(); Lab.expect(context).to.have.keys('jsFileName', 'cssFileName'); Lab.expect(context.jsFileName).to.equal('app.deadbeef.min.js'); Lab.expect(context.cssFileName).to.equal('app.deadbeef.min.css'); done(); }); Lab.test('js', function (done) { moonboots.jsSource(function (err, js) { Lab.expect(js).to.equal('javascript!' + tmpHash); done(); }); }); Lab.test('css', function (done) { moonboots.cssSource(function (err, css) { Lab.expect(css).to.equal('cascading stylesheets!' + tmpHash); done(); }); }); });
var Lab = require('lab'); var sh = require('execSync'); Lab.experiment('CLI', function () { Lab.test('Exits with 0', function (done) { var r = sh.run('node index.js sample/config.js --quiet'); Lab.expect(r).to.equal(0); done(); }); Lab.test('Exits with non 0', function (done) { var r = sh.run('node index.js sample/cong.js 2>/dev/null'); Lab.expect(r).to.not.equal(0); done(); }); });
Lab.experiment('labels parameter', function () { Lab.before(function (done) { async.parallel({ pack: function (next) { pack = new Hapi.Pack(); //TODO clean up once https://github.com/spumko/hapi/pull/1425 is merged server3001 = pack.server(3001, {labels: ['foo']}); server3002 = pack.server(3002, {labels: ['bar']}); //server3001 = new Hapi.Server('localhost', 3001, {labels: ['foo']}); //server3002 = new Hapi.Server('localhost', 3002, {labels: ['bar']}); //pack._server(server3001); //pack._server(server3002); pack.require({'..': options }, next); }, getSource: function (next) { appSource = moonboots.htmlSource(); next(); } }, function (err) { if (err) { process.stderr.write('Unable to setUp tests', err, '\n'); process.exit(1); } done(); }); }); Lab.test('server with matching label', function (done) { server3001.inject({ method: 'GET', url: '/app' }, function _getApp(res) { Lab.expect(res.statusCode, 'response code').to.equal(200); Lab.expect(res.payload, 'response body').to.equal(appSource, 'application source'); done(); }); }); Lab.test('server without matching label', function (done) { server3002.inject({ method: 'GET', url: '/app' }, function _getApp(res) { Lab.expect(res.statusCode, 'response code').to.equal(404); done(); }); }); });
Lab.experiment('Hash is the same', function () { function setup(done) { var options = { main: __dirname + '/../fixtures/app/appImports.js', jsFileName: 'app', minify: false }; var moonboots = new Moonboots(options); moonboots.on('ready', function () { done(moonboots); }); } Lab.test('50 times', function (done) { async.timesSeries(50, function (index, next) { setup(function (moonboots) { var filename = moonboots.jsFileName(); moonboots.jsSource(function (err, js) { next(null, [filename, js]); }); }); }, function (err, results) { var filenames = results.map(function (r) { return r[0]; }); var js = results.map(function (r) { return r[1]; }); Lab.expect(arrEqual(filenames)).to.equal(true); Lab.expect(arrEqual(js)).to.equal(true); done(); }); }); });
Lab.experiment("Make sure that the facebook login", function () { test("should just work without any option", function (done) { hp({ authenticate: function () { return undefined; } })()(requestStub, {}); done(); }); test("should pass down the authentication", function (done) { var called = false; hp({ authenticate: function () { called = true; } })({})(requestStub, {}); expect(called).to.equal(true); done(); }); test("should put redirect on the strategies object", function (done) { var called = false, url = "hello world", responseMethod = function () { return { redirect: function (resultUrl) { expect(resultUrl).to.equal(url); called = true; } }; }; hp({ authenticate: function () { this.redirect(url); expect(called).to.equal(true); } })({})(requestStub, responseMethod); done(); }); test("should pass failure's to the failure option", function (done) { var called = false, mockFail = function (error) { expect(error.message).to.equal("foo"); called = true; }; hp({ authenticate: function () { this.fail({message: "foo"}); } })({ onFailed: mockFail })(requestStub, {}); expect(called).to.equal(true); done(); }); test("should pass error's to the error option", function (done) { var called = false, mockError = function mockError(error) { expect(error.message).to.equal("foo"); called = true; }; hp({ authenticate: function () { this.error({message: "foo"}); } })({ onError: mockError })(requestStub, {}); expect(called).to.equal(true); done(); }); test("should pass error's to the error option", function (done) { var called = false, mockError = function mockError(error) { expect(error.message).to.equal("foo"); called = true; }; hp({ authenticate: function () { this.error({message: "foo"}); } })({ onError: mockError })(requestStub, {}); expect(called).to.equal(true); done(); }); test("should use a error redirect if given", function (done) { var redirect = "http://test", originalError = {message: "foo"}, called = "", replyMethod = function (message, error) { expect(message).to.equal("Error while trying to login..."); expect(error).to.equal(originalError); called += "a"; return { redirect: function (uri) { expect(uri).to.equal(redirect); called += "b"; } }; }; hp({ authenticate: function () { this.error(originalError); } })({ errorRedirect: redirect })(requestStub, replyMethod); expect(called).to.equal("ab"); done(); }); test("should use a fail redirect if given", function (done) { var redirect = "http://test", originalError = {message: "foo"}, called = "", replyMethod = function (message, error) { expect(message).to.equal("Login failed, redirecting..."); expect(error).to.equal(originalError); called += "a"; return replyMethod; }; replyMethod.redirect = function (uri) { expect(uri).to.equal(redirect); called += "b"; }; hp({ authenticate: function () { this.fail(originalError); } })({ failRedirect: redirect })(requestStub, replyMethod); expect(called).to.equal("ab"); done(); }); test("should use a success redirect if given", function (done) { var redirect = "http://test", originalError = {message: "foo"}, called = "", replyMethod = function (message, error) { expect(message).to.equal("Login successful, redirecting..."); expect(error).to.equal(originalError); called += "a"; return replyMethod; }; replyMethod.redirect = function (uri) { expect(uri).to.equal(redirect); called += "b"; }; hp({ authenticate: function () { this.success(originalError); } })({ successRedirect: redirect })(requestStub, replyMethod); expect(called).to.equal("ab"); done(); }); test("should just reply with a error when a error occurs", function (done) { var originalError = {message: "foo"}, called = "", replyMethod = function (error) { expect(error).to.equal(originalError); called += "a"; return replyMethod; }; hp({ authenticate: function () { this.error(originalError); } })()(requestStub, replyMethod); expect(called).to.equal("a"); done(); }); test("should just reply with the fail message when a failure occurs", function (done) { var originalError = {message: "foo"}, called = "", replyMethod = function (error) { expect(error).to.equal(originalError); called += "a"; return replyMethod; }; hp({ authenticate: function () { this.fail(originalError); } })()(requestStub, replyMethod); expect(called).to.equal("a"); done(); }); test("should just reply with the info message when the request was successful", function (done) { var originalInfo = {message: "foo"}, called = "", replyMethod = function (error) { expect(error).to.equal(originalInfo); called += "a"; return replyMethod; }; hp({ authenticate: function () { this.success(originalInfo); } })()(requestStub, replyMethod); expect(called).to.equal("a"); done(); }); });
var Lab = require('lab'); var Moonboots = require('..'); var express = require('express'); Lab.experiment('Development mode', function () { Lab.test('Development mode sets cache to 0', function (done) { var moonboots = new Moonboots({ moonboots: { main: __dirname + '../sample/app/app.js', developmentMode: true }, server: express() }); Lab.expect(moonboots.options.cachePeriod).to.equal(0); done(); }); });
var Moonboots = require('..'); var moonboots; var EXPECTED_JS_HASH = 'app.794c89f5.js'; var EXPECTED_JS_MIN_HASH = 'app.794c89f5.min.js'; Lab.experiment('js with default options', function () { Lab.before(function (done) { var options = { main: __dirname + '/../fixtures/app/app.js', jsFileName: 'app' }; moonboots = new Moonboots(options); moonboots.on('ready', done); }); Lab.test('filename', function (done) { Lab.expect(moonboots.jsFileName(), 'js filename').to.equal(EXPECTED_JS_MIN_HASH); done(); }); /* Lab.test('content', function (done) { Lab.expect(moonboots.jsSource(), 'js source').to.equal('how do we even test this?'); done(); }); */ }); Lab.experiment('js with uglify options', function () { Lab.before(function (done) { var options = { main: __dirname + '/../fixtures/app/app.js', jsFileName: 'app',
Lab.experiment('STORY API', function() { var story_created_by_another_id; Lab.before(function(done) { support.helpers.add_story(support.fakes.mongo_id(), null, function(id_o) { story_created_by_another_id = id_o; done(); }); }); Lab.after(function(done) { support.helpers.delete_all_stories(done); }); Lab.experiment('GET /api/stories/id', function() { var story_created_by_self_id; var story_unpublished_by_another_id; var story_unpublished_by_self_id; Lab.before(function(done) { var payload = { title: 'test title', text: 'sample text', location: { "type": "Point", "coordinates": [125.6, 10.1] }, location_description: 'loc desc', tags: ['keyword_a', 'keyword_b'] }; support.helpers.add_story(support.fakes.credentials().id, null, function(id_s) { story_created_by_self_id = id_s; support.helpers.add_story(support.fakes.credentials().id, payload, function(id_us) { story_unpublished_by_self_id = id_us; support.helpers.add_story(support.fakes.mongo_id(), payload, function(id_uo) { story_unpublished_by_another_id = id_uo; done(); }); }); }); }); Lab.test("retrieves published story with no auth", function(done) { var options = { method: "GET", url: "/api/stories/" + story_created_by_self_id }; server.inject(options, function(response) { var result = response.result; Lab.expect(response.statusCode).to.equal(200); Lab.expect(result).to.be.instanceof(Object); assert.equal(result.id, story_created_by_self_id); assert(typeof result.title === 'string'); assert(typeof result.text === 'string'); assert(typeof result.location == 'object'); done(); }); }); Lab.test("retrieves own-created not published story", function(done) { var options = { method: "GET", url: "/api/stories/" + story_unpublished_by_self_id, credentials: support.fakes.credentials() }; server.inject(options, function(response) { var result = response.result; Lab.expect(response.statusCode).to.equal(200); Lab.expect(result).to.be.instanceof(Object); assert.equal(result.id, story_unpublished_by_self_id); assert(typeof result.title === 'string'); assert(typeof result.text === 'string'); assert(typeof result.location == 'object'); done(); }); }); Lab.test("error when retrieving someone elses un-published story with your auth", function(done) { var options = { method: "GET", url: "/api/stories/" + story_unpublished_by_another_id, credentials: support.fakes.credentials() }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 403); assert.equal(result.error, 'Forbidden'); done(); }); }); Lab.test("error when retrieving someone elses un-published story with no auth", function(done) { var options = { method: "GET", url: "/api/stories/" + story_unpublished_by_another_id }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 403); assert.equal(result.error, 'Forbidden'); done(); }); }); Lab.test("returns error when not valid id", function(done) { var options = { method: "GET", url: "/api/stories/random54" }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 400); assert.equal(result.error, 'Bad Request'); done(); }); }); Lab.test("returns error when id does not exist", function(done) { var options = { method: "GET", url: "/api/stories/" + support.fakes.mongo_id() }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 404); assert.equal(result.error, 'Not Found'); done(); }); }); }); Lab.experiment('DELETE /api/stories/id', function() { var story_created_by_self_id; var story_created_by_self_id2; Lab.before(function(done) { support.helpers.add_story(support.fakes.credentials().id, null, function(id_s) { story_created_by_self_id = id_s; support.helpers.add_story(support.fakes.credentials().id, null, function(id_s2) { story_created_by_self_id2 = id_s2; done(); }); }); }); Lab.test("returns 200 and deletes object.", function(done) { var creds = support.fakes.credentials(); var title = 'different title. ' + Math.random(); var options = { method: "DELETE", url: "/api/stories/" + story_created_by_self_id, credentials: creds, payload: { title: title, publish: false } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 200); assert(result.success); support.helpers.get_story(story_created_by_self_id, creds, function(result) { assert.equal(result.error, 'Not Found'); done(); }); }); }); Lab.test("returns error when trying to edit a different story.", function(done) { var options = { method: "DELETE", url: "/api/stories/" + story_created_by_another_id, credentials: support.fakes.credentials() }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 403); assert.equal(result.error, 'Forbidden'); done(); }); }); Lab.test("returns error when unauthed", function(done) { var options = { method: "DELETE", url: "/api/stories/" + story_created_by_self_id2, payload: { bio: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 401); assert.equal(result.error, 'Unauthorized'); done(); }); }); Lab.test("returns error when not valid id", function(done) { var options = { method: "DELETE", url: "/api/stories/random45", credentials: support.fakes.credentials(), payload: { title: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 400); assert.equal(result.error, 'Bad Request'); done(); }); }); }); Lab.experiment('PUT /api/stories/id', function() { var story_created_by_self_id; Lab.before(function(done) { support.helpers.add_story(support.fakes.credentials().id, null, function(id_s) { story_created_by_self_id = id_s; done(); }); }); Lab.test("returns 200 and updated object.", function(done) { var creds = support.fakes.credentials(); var title = 'different title. ' + Math.random(); var options = { method: "PUT", url: "/api/stories/" + story_created_by_self_id, credentials: creds, payload: { title: title, publish: false } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 200); assert.equal(result.title, title); assert(!result.publish); assert.equal(result.id, story_created_by_self_id); done(); }); }); Lab.test("returns error when no acceptable fields.", function(done) { var creds = support.fakes.credentials(); var options = { method: "PUT", url: "/api/stories/" + story_created_by_self_id, credentials: creds, payload: { hello: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 400); assert.equal(result.error, 'Bad Request'); done(); }); }); Lab.test("returns error when trying to edit a different story.", function(done) { var options = { method: "PUT", url: "/api/stories/" + story_created_by_another_id, credentials: support.fakes.credentials(), payload: { title: "Test title change." } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 403); assert.equal(result.error, 'Forbidden'); done(); }); }); Lab.test("returns error when unauthed", function(done) { var options = { method: "PUT", url: "/api/stories/" + story_created_by_self_id, payload: { bio: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 401); assert.equal(result.error, 'Unauthorized'); done(); }); }); Lab.test("returns error when not valid id", function(done) { var options = { method: "PUT", url: "/api/stories/random45", credentials: support.fakes.credentials(), payload: { title: "Test User" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 400); assert.equal(result.error, 'Bad Request'); done(); }); }); }); Lab.experiment('POST /api/stories', function() { Lab.test("returns 200 and new object.", function(done) { var creds = support.fakes.credentials(); var title = 'new title ' + Math.random(); var options = { method: "POST", url: "/api/stories", credentials: creds, payload: { title: title, text: 'sample text', location: { "type": "Point", "coordinates": [125.6, 10.1] }, location_description: 'loc desc', tags: ['keyword_a', 'keyword_b'], publish: true } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 200); assert.equal(result.title, title); assert(result.publish); assert(result.first_published_time); assert(result.location); assert(result.location_description); assert(result.tags); assert(result.id); support.helpers.manage_story(result.id, creds.id); done(); }); }); Lab.test("returns error when no title.", function(done) { var creds = support.fakes.credentials(); var options = { method: "POST", url: "/api/stories", credentials: creds, payload: { text: "Test text" } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 400); assert.equal(result.error, 'Bad Request'); done(); }); }); Lab.test("returns error when unauthed", function(done) { var options = { method: "POST", url: "/api/stories", payload: { title: 'hi' } }; server.inject(options, function(response) { var result = response.result; assert.equal(response.statusCode, 401); assert.equal(result.error, 'Unauthorized'); done(); }); }); }); });
"use strict"; var Lab = require("lab"); var server = require("../"); var Item = require("../lib/item"); Lab.experiment("Item", function () { Lab.test("does something", function (done) { var item = new Item(); Lab.expect(item.doSomething("bob")).to.equal("bob"); done(); }); Lab.test("has a name", function (done) { var item = new Item(); Lab.expect(item.name).to.exist; done(); }); });
Lab.experiment('image builder without versions', function () { Lab.before(function (done) { // set up ImageBuilder this.ib = new ImageBuilder({ dockerHost: 'http://localhost', dockerPort: 4243, context: context, aws: { accessKeyId: 'AN-AWS-ACCESS-KEY', secretAccessKey: 'AN-AWS-SECRET-ACCESS-KEY' } }); // mocks for amazon requests // nock.recorder.rec(); nock('https://bucket.s3.amazonaws.com:443') .get('/path/to/some/source/Dockerfile?response-content-type=application%2Fjson') .reply(200, "FROM runnable/node\n\nWORKDIR /root\nRUN git clone https://github.com/heroku/node-js-sample\n\nWORKDIR /root/node-js-sample\nRUN npm install\nENTRYPOINT [\"node\"]\nCMD [\"web.js\"]"); nock('https://bucket.s3.amazonaws.com:443') .get('/?prefix=path%2Fto%2Fsome%2Fsource%2F') .reply(200, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Name>bucket</Name><Prefix>path/to/some/source/</Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated><Contents></Contents></ListBucketResult>"); nock('https://bucket.s3.amazonaws.com:443') .get('/source/1/?response-content-type=application%2Fjson') .reply(200, ""); // mocks for docker requests nock('http://localhost:4243') .filteringRequestBody(function (path) { return '*'; }) .post('/build?t=owner%2Fweb-server', '*') .reply(200, '{"stream": "Successfully built 0123456789001"}'); done(); }); Lab.after(function (done) { delete this.ib; done(); }); Lab.test('returns docker image ids built from latest', function (done) { this.ib.run(function (err, results) { if (err) { done(err); } else { Lab.expect(Object.keys(results)).to.have.length(1); Lab.expect(results['owner/web-server']).to.equal('0123456789001'); done(); } }); }); });
Lab.experiment("Add", function () { var options = {}, server, delay = 0 Lab.before(function (done) { server = new Server.getServer() options.headers = headers // Wait 1 second setTimeout(function () { done() }, 3000) }) Lab.beforeEach(function (done) { options = {} options.headers = headers done() }) Lab.test("Ensure Correct word insertion without optional params", function (done) { options = fixtures.load('add/success-partial', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(200) var result = response.result Lab.expect(result.success).to.be.true setTimeout(done, delay) }) }) Lab.test("Ensure Correct word insertion without optional params 2", function (done) { options = fixtures.load('add/success-partial-2', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(200) var result = response.result Lab.expect(result.success).to.be.true setTimeout(done, delay) }) }) Lab.test("Ensure Correct word insertion with all params", function (done) { options = fixtures.load('add/success', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(200) var result = response.result var payload = options.payload Lab.expect(result.success).to.be.true setTimeout(done, delay) }) }) Lab.test("Raise duplicate word", function (done) { options = fixtures.load('add/success', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20053) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Word already exists') setTimeout(done, delay) }) }) Lab.test("Raise wrong gerund pattern", function (done) { options = fixtures.load('add/wrong-gerund', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(400) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') setTimeout(done, delay) }) }) Lab.test("Raise Unknow Language", function (done) { options = fixtures.load('add/unknow-language', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20001) var result = response.result Lab.expect(result.message).to.equal("Unknown Language") setTimeout(done, delay) }) }) Lab.test("Raise Unknow Country", function (done) { options = fixtures.load('add/unknow-country', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20003) var result = response.result Lab.expect(result.message).to.equal("Unknown Country") setTimeout(done, delay) }) }) Lab.test("Raise duplicate hyperlink", function (done) { options = fixtures.load('add/duplicate-hyperlink', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20056) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Hyperlink already exists') setTimeout(done, delay) }) }) Lab.test("Raise duplicate definition", function (done) { options = fixtures.load('add/duplicate-definition', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20054) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Definition already exists') setTimeout(done, delay) }) }) Lab.test("Raise duplicate example", function (done) { options = fixtures.load('add/duplicate-example', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20055) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Example already exists') setTimeout(done, delay) }) }) Lab.test("Raise unknow synonym", function (done) { options = fixtures.load('add/unknow-synonym', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20004) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Unknown Synonym') setTimeout(done, delay) }) }) Lab.test("Raise word equal synonym", function (done) { options = fixtures.load('add/word-equal-synonym', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20050) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Conflict : SynonymId equal WordId') setTimeout(done, delay) }) }) Lab.test("Raise unknow antonym", function (done) { options = fixtures.load('add/unknow-antonym', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20005) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Unknown Antonym') setTimeout(done, delay) }) }) Lab.test("Raise word equal antonym", function (done) { options = fixtures.load('add/word-equal-antonym', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20051) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Conflict : AntonymId equal WordId') setTimeout(done, delay) }) }) Lab.test("Raise unknow relative", function (done) { options = fixtures.load('add/unknow-relative', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20007) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Unknown Relative') setTimeout(done, delay) }) }) Lab.test("Raise word equal relative", function (done) { options = fixtures.load('add/word-equal-relative', options) server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(20052) var result = response.result Lab.expect(result.error).to.be.equal('Bad Request') Lab.expect(result.message).to.be.equal('Conflict : RelativeId equal WordId') setTimeout(done, delay) }) }) Lab.test("Raise unknow field", function (done) { options.method = "PUT", options.url = '/api', options.payload = { word: "bonjour", } server.inject(options, function (response) { Lab.expect(response.statusCode).to.equal(400) var result = response.result setTimeout(done, delay) }) }) })
Lab.experiment('Server', function() { Lab.beforeEach(function(done) { if (app.room.channel) app.room.channel.end(); app.room.channel = new Stream.PassThrough(); // Reload channel app.room.users = []; // Reload user list done(); }); Lab.experiment('Root page', function() { Lab.test('should render successfully', function(done) { var options = { method: 'GET', url: '/' }; app.server.inject(options, function(response) { Lab.expect(response.statusCode).to.equal(200); done(); }); }); }); Lab.experiment('GET /room/messages', function() { Lab.test('should set correct headers', function(done) { var options = { method: 'GET', url: '/room/messages' }; app.room.channel.end(); // End the messages stream app.server.inject(options, function(response) { Lab.expect(response.headers.connection).to.equal('keep-alive'); Lab.expect(response.headers['cache-control']).to.equal('no-cache'); done(); }); }); Lab.test('should propagate messages from the main channel', function(done) { var options = { method: 'GET', url: '/room/messages' }; app.room.channel.write('Hey, QChatters'); app.room.channel.end(); // End the messages stream app.server.inject(options, function(response) { Lab.expect(response.payload).to.equal('Hey, QChatters'); done(); }); }); }); Lab.experiment('POST /room/messages', function() { Lab.test("should post messages to the main channel in JSON format", function(done) { var options = { method: 'POST', url: '/room/messages', payload: { message: { text: "Qu-Qquu.", sender: "Hipster" } } }; var result = ''; app.room.channel.on('data', function(chunk) { result += chunk.toString(); }); app.server.inject(options, function(response) { Lab.expect(result).to.equal(JSON.stringify(options.payload.message)); done(); }); }); Lab.test("should store the sender in a list of users connected to the room", function(done) { var options = { method: 'POST', url: '/room/messages', payload: { message: { text: "Qu-Qquu.", sender: "Hipster" } } }; app.server.inject(options, function(response) { Lab.expect(app.room.users.length).to.equal(1); Lab.expect(app.room.users[0].name).to.equal('Hipster'); done(); }); }); Lab.test("should store the sender only once", function(done) { var options = { method: 'POST', url: '/room/messages', payload: { message: { text: "Qu-Qquu.", sender: "Hipster" } } }; app.server.inject(options, function(response) { app.server.inject(options, function(response) { app.server.inject(options, function(response) { Lab.expect(app.room.users.length).to.equal(1); Lab.expect(app.room.users[0].name).to.equal('Hipster'); done(); }); }); }); }); }); Lab.experiment('GET /room/users', function() { Lab.test('should return all users connected to the room', function(done) { var options = { method: 'GET', url: '/room/users' }; app.room.users = ['Hipster', 'Fellow']; app.server.inject(options, function(response) { Lab.expect(response.result.users.length).to.equal(2); Lab.expect(response.result.users[0]).to.equal('Hipster'); Lab.expect(response.result.users[1]).to.equal('Fellow'); done(); }); }); }); });
var Lab = require("lab"), // the Lab server = require("../"); // require index.js Lab.experiment("Basic HTTP Tests", function() { // tests Lab.test("Main endpoint /{yourname*} ", function(done) { var options = { method: "GET", url: "/Timmy" }; // server.inject lets you similate an http request server.inject(options, function(response) { Lab.expect(response.statusCode).to.equal(200); // Expect http response status code to be 200 ("Ok") Lab.expect(response.result).to.have.length(12); // Expect result to be "Hello Timmy!" (12 chars long) done(); // done() callback is required to end the test. }); }); }); Lab.experiment("Authentication Required to View Photo", function() { // tests Lab.test("Deny view of photo if unauthenticated /photo/{id*} ", function(done) { var options = { method: "GET", url: "/photo/8795" }; // server.inject lets you similate an http request server.inject(options, function(response) { Lab.expect(response.statusCode).to.equal(401); // Expect http response status code to be 200 ("Ok") Lab.expect(response.result.message).to.equal("Please log-in to see that"); // (Don't hard-code error messages) done(); });
Lab.experiment('multiple apps happy path', function () { Lab.before(function (done) { server = new Hapi.Server('localhost', 3001); async.parallel({ plugin: function (next) { server.pack.require({ '..': [options1, options2] }, next); }, getSource: function (next) { appSource1 = moonboots1.htmlSource(); appSource2 = moonboots2.htmlSource(); next(); }, getJs: function (next) { moonboots1.jsSource(function _getJsSource(err, js) { jsSource1 = js; next(err); }); }, getJs2: function (next) { moonboots2.jsSource(function _getJsSource(err, js) { jsSource2 = js; next(err); }); }, getCss: function (next) { moonboots1.cssSource(function _getCssSource(err, css) { cssSource1 = css; next(err); }); }, getCss2: function (next) { moonboots2.cssSource(function _getCssSource(err, css) { cssSource2 = css; next(err); }); } }, function (err) { if (err) { process.stderr.write('Unable to setUp tests', err, '\n'); process.exit(1); } done(); }); }); Lab.test('serves app1 where expected', function (done) { server.inject({ method: 'GET', url: '/app1' }, function _getApp(res) { Lab.expect(res.statusCode, 'response code').to.equal(200); Lab.expect(res.payload, 'response body').to.equal(appSource1, 'application source'); done(); }); }); Lab.test('serves app2 where expected', function (done) { server.inject({ method: 'GET', url: '/app2' }, function _getApp(res) { Lab.expect(res.statusCode, 'response code').to.equal(200); Lab.expect(res.payload, 'response body').to.equal(appSource2, 'application source'); done(); }); }); Lab.test('serves app1 js where expected', function (done) { server.inject({ method: 'GET', url: '/moonboots-hapi-js1.nonCached.js' }, function _getJs(res) { Lab.expect(res.statusCode, 'response code').to.equal(200); Lab.expect(res.payload, 'response body').to.equal(jsSource1, 'js source'); done(); }); }); Lab.test('serves app2 js where expected', function (done) { server.inject({ method: 'GET', url: '/moonboots-hapi-js2.nonCached.js' }, function _getJs(res) { Lab.expect(res.statusCode, 'response code').to.equal(200); Lab.expect(res.payload, 'response body').to.equal(jsSource2, 'js source'); done(); }); }); Lab.test('serves app1 css where expected', function (done) { server.inject({ method: 'GET', url: '/moonboots-hapi-css1.nonCached.css' }, function _getJs(res) { Lab.expect(res.statusCode, 'response code').to.equal(200); Lab.expect(res.payload, 'response body').to.equal(cssSource1, 'css source'); done(); }); }); Lab.test('serves app1 css where expected', function (done) { server.inject({ method: 'GET', url: '/moonboots-hapi-css2.nonCached.css' }, function _getJs(res) { Lab.expect(res.statusCode, 'response code').to.equal(200); Lab.expect(res.payload, 'response body').to.equal(cssSource2, 'css source'); done(); }); }); Lab.test('app1 clientConfig is exposed', function (done) { server.plugins.moonboots_hapi.clientConfig(0, function (config) { Lab.expect(config, 'client config').to.equal(options1, 'moonboots-hapi config'); done(); }); }); Lab.test('app2 clientConfig is exposed', function (done) { server.plugins.moonboots_hapi.clientConfig(1, function (config) { Lab.expect(config, 'client config').to.equal(options2, 'moonboots-hapi config'); done(); }); }); Lab.test('app1 clientApp is exposed', function (done) { server.plugins.moonboots_hapi.clientApp(0, function (clientApp) { Lab.expect(clientApp, 'client app').to.be.instanceOf(Moonboots); //TODO confirm this is the right app maybe? done(); }); }); Lab.test('app2 clientApp is exposed', function (done) { server.plugins.moonboots_hapi.clientApp(1, function (clientApp) { Lab.expect(clientApp, 'client app').to.be.instanceOf(Moonboots); //TODO confirm this is the right app maybe? done(); }); }); });
var Lab = require('lab'); var spawn = require('child_process').spawn; Lab.experiment('CLI', function () { Lab.test('Exits with 0', function (done) { var test = spawn('node', ['index.js', 'sample/config.js', '--quiet']); test.on('close', function (code) { Lab.expect(code).to.equal(0); done(); }); }); Lab.test('Exits with non 0', function (done) { var test = spawn('node', ['index.js', 'sample/cong.js', '2>/dev/null']); test.on('close', function (code) { Lab.expect(code).to.not.equal(0); done(); }); }); });
Lab.experiment("Path", function() { var options = {}, server, delay = 0 Lab.before(function (done) { server = new Server.getServer() options.headers = headers // Wait 1 second setTimeout(function () { done() }, 1000) }) Lab.beforeEach(function (done) { options = {} options.headers = headers done() }) // Lab.test("Authentication Error", function (done) { // options = fixtures.load('path/methodForbidden') // server.inject(options, function(response) { // Lab.expect(response.statusCode).to.equal(401) // setTimeout(done, delay) // }) // }) Lab.test("notFound error", function (done) { options = fixtures.load('path/notFound', options) server.inject(options, function(response) { Lab.expect(response.statusCode).to.equal(404) setTimeout(done, delay) }) }) // Lab.test("methodForbidden error", function (done) { // options = fixtures.load('path/methodForbidden', options) // server.inject(options, function(response) { // console.log(response) // Lab.expect(response.statusCode).to.equal(400) // setTimeout(done, delay) // }) // }) })
var moonboots; var EXPECTED_JS_MIN_HASH = 'app.794c89f5.min.js'; var EXPECTED_CSS_MIN_HASH = 'app.38ea6c96.min.css'; Lab.experiment('html with default options', function () { Lab.before(function (done) { var options = { main: __dirname + '/../fixtures/app/app.js', jsFileName: 'app', cssFileName: 'app', stylesheets: [ __dirname + '/../fixtures/stylesheets/style.css' ] }; moonboots = new Moonboots(options); moonboots.on('ready', done); }); Lab.test('htmlContext', function (done) { var context = moonboots.htmlContext(); Lab.expect(context).to.have.keys('jsFileName', 'cssFileName'); Lab.expect(context.jsFileName).to.equal(EXPECTED_JS_MIN_HASH); Lab.expect(context.cssFileName).to.equal(EXPECTED_CSS_MIN_HASH); done(); }); Lab.test('htmlSource', function (done) { var source = moonboots.htmlSource(); Lab.expect(source).to.equal('<!DOCTYPE html>\n<link href=\"/' + EXPECTED_CSS_MIN_HASH + '\" rel=\"stylesheet\" type=\"text/css\">\n<script src=\"/' + EXPECTED_JS_MIN_HASH + '\"></script>'); done(); }); });
Lab.experiment("TicTacToe", function () { Lab.test("creates a new, blank board", function (done) { var ttt = new TicTacToe(); Lab.expect(ttt.board).to.exist; done(); }); Lab.test("creates a pre-populated board", function (done) { var testBoard = [ ["x", "o", "."], [".", "x", "o"], [".", ".", "x"] ]; var tttOptions = { board: testBoard, }; var ttt = new TicTacToe(tttOptions); Lab.expect(ttt.board).to.equal(testBoard); done(); }); Lab.test("winner returns undefined if there is no winner", function (done) { var t = new TicTacToe({ }); Lab.expect(t.winner()).to.be.undefined; done(); }); Lab.test("checks a row for a winner", function (done) { var testBoard1 = [ ["x", "x", "x"], [".", ".", "o"], ["o", ".", "."] ]; var t1 = new TicTacToe({ board: testBoard1, }); Lab.expect(t1.checkRow(0)).to.equal("x"); Lab.expect(t1.checkRow(1)).to.be.undefined; Lab.expect(t1.checkRow(2)).to.be.undefined; var testBoard2 = [ ["o", "o", "o"], ["x", ".", "x"], ["x", ".", "."] ]; var t2 = new TicTacToe({ board: testBoard2, }); Lab.expect(t2.checkRow(0)).to.equal("o"); Lab.expect(t2.checkRow(1)).to.be.undefined; Lab.expect(t2.checkRow(2)).to.be.undefined; var testBoard3 = [ [".", "o", "o"], ["x", "x", "x"], ["o", ".", "."] ]; var t3 = new TicTacToe({ board: testBoard3, }); Lab.expect(t3.checkRow(0)).to.be.undefined; Lab.expect(t3.checkRow(1)).to.equal("x"); Lab.expect(t3.checkRow(2)).to.be.undefined; var testBoard4 = [ [".", "x", "x"], ["o", "o", "o"], ["x", ".", "."] ]; var t4 = new TicTacToe({ board: testBoard4, }); Lab.expect(t4.checkRow(0)).to.be.undefined; Lab.expect(t4.checkRow(1)).to.equal("o"); Lab.expect(t4.checkRow(2)).to.be.undefined; var testBoard5 = [ ["o", "x", "o"], [".", "o", "."], ["x", "x", "x"] ]; var t5 = new TicTacToe({ board: testBoard5, }); Lab.expect(t5.checkRow(0)).to.be.undefined; Lab.expect(t5.checkRow(1)).to.be.undefined; Lab.expect(t5.checkRow(2)).to.equal("x"); var testBoard6 = [ ["x", ".", "x"], [".", "x", "."], ["o", "o", "o"] ]; var t6 = new TicTacToe({ board: testBoard6, }); Lab.expect(t6.checkRow(0)).to.be.undefined; Lab.expect(t6.checkRow(1)).to.be.undefined; Lab.expect(t6.checkRow(2)).to.equal("o"); done(); }); Lab.test("checks a column for a winner", function (done) { var testBoard1 = [ ["x", ".", "."], ["x", ".", "o"], ["x", "o", "."] ]; var t1 = new TicTacToe({ board: testBoard1, }); Lab.expect(t1.checkColumn(0)).to.equal("x"); Lab.expect(t1.checkColumn(1)).to.be.undefined; Lab.expect(t1.checkColumn(2)).to.be.undefined; var testBoard2 = [ ["o", ".", "x"], ["o", ".", "x"], ["o", "x", "."] ]; var t2 = new TicTacToe({ board: testBoard2, }); Lab.expect(t2.checkColumn(0)).to.equal("o"); Lab.expect(t2.checkColumn(1)).to.be.undefined; Lab.expect(t2.checkColumn(2)).to.be.undefined; var testBoard3 = [ ["o", "x", "."], [".", "x", "."], ["o", "x", "o"] ]; var t3 = new TicTacToe({ board: testBoard3, }); Lab.expect(t3.checkColumn(0)).to.be.undefined; Lab.expect(t3.checkColumn(1)).to.equal("x"); Lab.expect(t3.checkColumn(2)).to.be.undefined; var testBoard4 = [ ["x", "o", "."], [".", "o", "x"], ["x", "o", "."] ]; var t4 = new TicTacToe({ board: testBoard4, }); Lab.expect(t4.checkColumn(0)).to.be.undefined; Lab.expect(t4.checkColumn(1)).to.equal("o"); Lab.expect(t4.checkColumn(2)).to.be.undefined; var testBoard5 = [ ["o", "o", "x"], [".", ".", "x"], [".", "o", "x"] ]; var t5 = new TicTacToe({ board: testBoard5, }); Lab.expect(t5.checkColumn(0)).to.be.undefined; Lab.expect(t5.checkColumn(1)).to.be.undefined; Lab.expect(t5.checkColumn(2)).to.equal("x"); var testBoard6 = [ ["x", ".", "o"], [".", ".", "o"], ["x", "x", "o"] ]; var t6 = new TicTacToe({ board: testBoard6, }); Lab.expect(t6.checkColumn(0)).to.be.undefined; Lab.expect(t6.checkColumn(1)).to.be.undefined; Lab.expect(t6.checkColumn(2)).to.equal("o"); done(); }); Lab.test("checks diagonals for a winner", function (done) { var testBoard1 = [ ["x", ".", "o"], [".", "x", "o"], ["o", ".", "x"] ]; var t1 = new TicTacToe({ board: testBoard1, }); Lab.expect(t1.checkDiagonal(0)).to.equal("x"); Lab.expect(t1.checkDiagonal(1)).to.be.undefined; var testBoard2 = [ ["o", ".", "x"], ["x", "o", "x"], ["x", ".", "o"] ]; var t2 = new TicTacToe({ board: testBoard2, }); Lab.expect(t2.checkDiagonal(0)).to.equal("o"); Lab.expect(t2.checkDiagonal(1)).to.be.undefined; var testBoard3 = [ ["o", ".", "x"], [".", "x", "o"], ["x", ".", "o"] ]; var t3 = new TicTacToe({ board: testBoard3, }); Lab.expect(t3.checkDiagonal(0)).to.be.undefined; Lab.expect(t3.checkDiagonal(1)).to.equal("x"); var testBoard4 = [ ["x", ".", "o"], [".", "o", "x"], ["o", ".", "x"] ]; var t4 = new TicTacToe({ board: testBoard4, }); Lab.expect(t4.checkDiagonal(0)).to.be.undefined; Lab.expect(t4.checkDiagonal(1)).to.equal("o"); done(); }); Lab.test("tests overall game for a winner", function (done) { var testBoard1 = [ ["x", "x", "x"], [".", ".", "o"], ["o", ".", "."] ]; var t1 = new TicTacToe({ board: testBoard1, }); Lab.expect(t1.winner()).to.equal("x"); var testBoard2 = [ ["o", "o", "o"], ["x", ".", "x"], [".", ".", "."] ]; var t2 = new TicTacToe({ board: testBoard2, }); Lab.expect(t2.winner()).to.equal("o"); var testBoard3 = [ ["x", "o", "."], ["x", ".", "o"], ["x", ".", "."] ]; var t3 = new TicTacToe({ board: testBoard3, }); Lab.expect(t3.winner()).to.equal("x"); var testBoard4 = [ [".", "o", "."], [".", "o", "x"], ["x", "o", "."] ]; var t4 = new TicTacToe({ board: testBoard4, }); Lab.expect(t4.winner()).to.equal("o"); var testBoard5 = [ ["o", "x", "."], [".", "o", "x"], [".", ".", "o"] ]; var t5 = new TicTacToe({ board: testBoard5, }); Lab.expect(t5.winner()).to.equal("o"); done(); }); Lab.test("knows if board is full", function (done) { var testBoard1 = [ ["x", "o", "x"], ["x", "o", "o"], ["o", "x", "x"] ]; var t1 = new TicTacToe({ board: testBoard1 }); Lab.expect(t1.isFull()).to.be.true; var testBoard2 = [ ["x", "o", "x"], ["x", "o", "o"], ["o", "x", "."] ]; var t2 = new TicTacToe({ board: testBoard2 }); Lab.expect(t2.isFull()).to.be.false; done(); }); Lab.test("knows when the game is in stalemate", function (done) { var testBoard1 = [ ["x", "o", "x"], ["x", "o", "o"], ["o", "x", "x"] ]; var t1 = new TicTacToe({ board: testBoard1 }); Lab.expect(t1.isStalemate()).to.be.true; var testBoard2 = [ ["x", "o", "x"], ["x", "o", "o"], ["o", "x", "."] ]; var t2 = new TicTacToe({ board: testBoard2 }); Lab.expect(t2.isStalemate()).to.be.false; var testBoard3 = [ ["x", "o", "x"], ["o", "o", "x"], ["o", "x", "x"] ]; var t3 = new TicTacToe({ board: testBoard3 }); Lab.expect(t3.isStalemate()).to.be.false; done(); }); Lab.test("knows who the current player is", function (done) { var t1 = new TicTacToe({ }); Lab.expect(t1.currentPlayer()).to.equal("x"); var t2 = new TicTacToe({ currentPlayer: "o" }); Lab.expect(t2.currentPlayer()).to.equal("o"); done(); }); Lab.test("can switch to the next player", function (done) { var t1 = new TicTacToe(); Lab.expect(t1.currentPlayer()).to.equal("x"); t1.nextPlayer(); Lab.expect(t1.currentPlayer()).to.equal("o"); t1.nextPlayer(); Lab.expect(t1.currentPlayer()).to.equal("x"); done(); }); Lab.test("can make plays and updates to the next player", function (done) { var t1 = new TicTacToe(); t1.play({ row: 0, column: 0 }); Lab.expect(t1.board[0][0]).to.equal("x"); t1.play({ row: 0, column: 1 }); Lab.expect(t1.board[0][1]).to.equal("o"); done(); }); Lab.test("won't allow a play on an already occupied space", function (done) { var t1 = new TicTacToe(); t1.play({ row: 0, column: 0 }); t1.play({ row: 0, column: 0 }); Lab.expect(t1.board[0][0]).to.equal("x"); Lab.expect(t1.currentPlayer()).to.equal("o"); done(); }); Lab.test("has its own toString", function (done) { var t1 = new TicTacToe(); Lab.expect(t1.toString()).to.equal("...\n...\n...\n"); done(); }); });
Lab.experiment('generateScript', function() { function sharedAssertions(script) { // local environment variables populated. Lab.expect(script).to.match(/PORT/); Lab.expect(script).to.match(/8000/); // global environment variables populated. Lab.expect(script).to.match(/APP/) Lab.expect(script).to.match(/my-test-app/); // local args varibles populated. Lab.expect(script).to.match(/--kitten/); Lab.expect(script).to.match(/cute/); // global ags variables populated. Lab.expect(script).to.match(/--batman/); Lab.expect(script).to.match(/greatest-detective/); } Lab.experiment('darwin', function() { Lab.it('should genterate a script with the appropriate variables populated', function(done) { // test generating a script for darwin. Config({ platform: 'darwin', daemonsDirectory: './' }); var service = Service.allServices()[0]; service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // it should populate the bin for the script. Lab.expect(script).to.match(/>.\/test.js/) done(); }); }); }); Lab.experiment('centos', function() { Lab.it('should genterate a script with the appropriate variables populated', function(done) { Config({ platform: 'centos', daemonsDirectory: './' }); var service = Service.allServices()[0] service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // we should not try to su. Lab.expect(script).to.not.match(/su -/); // it should populate the bin for the script. Lab.expect(script).to.match(/bin\/node \.\/test.js/) done(); }); }); Lab.it('should switch su to uid user, if uid is provided', function(done) { Config({ platform: 'centos', daemonsDirectory: './', uid: 'npm' }); var service = Service.allServices()[0]; service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // we should try to step down our privileges. Lab.expect(script).to.match(/su - npm/); done(); }); }); }); Lab.experiment('ubuntu', function() { Lab.it('should genterate a script with the appropriate variables populated', function(done) { Config({ platform: 'linux', daemonsDirectory: './' }); var service = Service.allServices()[0] service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // it should populate the bin for the script. Lab.expect(script).to.match(/bin\/node \.\/test.js/) done(); }); }); }); Lab.it('should raise an appropriate exception if JSON is invalid', function(done) { Config({ platform: 'linux', daemonsDirectory: './', serviceJsonPath: './test/fixtures/invalid-service.json' }); Lab.expect(function() { var service = Service.allServices(); }).to.throw(Error, /invalid service.json, check file for errors/); done(); }); Lab.it('should pass arguments after -- to generated script', function(done) { Config({ platform: 'linux', daemonsDirectory: './' }); Array.prototype.push.apply(process.argv, ['--', '--foovar', 'barvalue']) var service = Service.allServices()[0] service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // it should populate the bin for the script. Lab.expect(script).to.match(/--foovar barvalue/) done(); }); }); Lab.it('should output an array of arguments appropriately to generated script', function(done) { Config({ platform: 'linux', daemonsDirectory: './', serviceJsonPath: './test/fixtures/args-service.json' }); var service = Service.allServices()[0]; service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); // it should populate the bin for the script. Lab.expect(script).to.match(/--spider-man sad/) done(); }); }); Lab.it('should redirect stderr and stdout to log file by default', function(done) { Config({ platform: 'linux', daemonsDirectory: './', serviceJsonPath: './test/fixtures/args-service.json' }); var service = Service.allServices()[0]; service.generateScript(function() { var script = fs.readFileSync(service.scriptPath()).toString(); // it should redirect script output. Lab.expect(script).to.match(/>>.* 2>&1/); done(); }); }); Lab.it('should allow stdout/stderr redirect to be overridden by console', function(done) { Config({ platform: 'linux', daemonsDirectory: './', console: 'log', serviceJsonPath: './test/fixtures/args-service.json' }); var service = Service.allServices()[0]; service.generateScript(function() { var script = fs.readFileSync(service.scriptPath()).toString(); Lab.expect(script).to.not.match(/>>.* 2>&1/); // it should use upstart's logging. Lab.expect(script).to.match(/console log/); done(); }); }); });
Lab.experiment('image builder with versions', function () { Lab.before(function (done) { // set up ImageBuilder this.ib = new ImageBuilder({ dockerHost: 'http://localhost', dockerPort: 4243, context: context, aws: { accessKeyId: 'AN-AWS-ACCESS-KEY', secretAccessKey: 'AN-AWS-SECRET-ACCESS-KEY' } }); // mocks for amazon requests nock('https://bucket.s3.amazonaws.com:443') .get('/path/to/some/source/Dockerfile?versionId=1234&response-content-type=application%2Fjson') .reply(200, "FROM runnable/node\n\nWORKDIR /root\nRUN git clone https://github.com/heroku/node-js-sample\n\nWORKDIR /root/node-js-sample\nRUN npm install\nENTRYPOINT [\"node\"]\nCMD [\"web.js\"]"); nock('https://bucket.s3.amazonaws.com:443') .get('/path/to/some/source/?versionId=5678&response-content-type=application%2Fjson') .reply(200, ""); // mocks for docker requests nock('http://localhost:4243') .filteringRequestBody(function (path) { return '*'; }) .post('/build?t=owner%2Fweb-server', '*') .reply(200, '{"stream": "Successfully built 0123456789001"}'); done(); }); Lab.after(function (done) { delete this.ib; done(); }); Lab.test('returns docker image ids built from latest', function (done) { this.ib.run(function (err, results) { if (err) { done(err); } else { Lab.expect(Object.keys(results)).to.have.length(1); Lab.expect(results['owner/web-server']).to.equal('0123456789001'); done(); } }); }); });
Lab.experiment('service', function() { Lab.experiment('allServices', function() { Lab.it('returns all services if no filter is provided', function(done) { Lab.expect(Service.allServices().length).to.eql(3); done(); }); Lab.it('should filter a specific service if filter is argument is provided', function(done) { var services = Service.allServices('ndm'), service = services[0]; Lab.expect(services.length).to.eql(1); Lab.expect(service.name).to.eql('ndm'); done(); }); }); Lab.experiment('env', function() { Lab.it('should default module to service name, if no module stanza provided', function(done) { var service = Service.allServices()[0]; Lab.expect(service.module).to.eql(service.name); done(); }); Lab.it('should allow npm-module to be overridden', function(done) { var service = Service.allServices()[1]; Lab.expect(service.module).to.eql('ndm-test'); done(); }); Lab.it('should load global environment stanza if present', function(done) { var service = Service.allServices()[1]; Lab.expect(service.env.APP).to.eql('my-test-app'); done(); }); Lab.it('should handle object rather than value for service env', function(done) { var service = Service.allServices()[1]; Lab.expect(service.env.HOST).to.eql('localhost'); done(); }); Lab.it('should handle object rather than value for global env', function(done) { var service = Service.allServices()[1]; Lab.expect(service.env.ENVIRONMENT).to.eql('test'); done(); }); }); Lab.experiment('args', function() { Lab.it('should load the global args variable', function(done) { var service = Service.allServices()[0]; Lab.expect(service.args['--batman']).to.eql('greatest-detective'); done(); }); Lab.it('should override global args with service specific args', function(done) { var service = Service.allServices()[0]; Lab.expect(service.args['--dog']).to.eql('also-cute'); done(); }); Lab.it('should handle an object rather than a value for service args', function(done) { var service = Service.allServices()[0]; Lab.expect(service.args['--dog']).to.eql('also-cute'); done(); }); Lab.it('should handle an object rather than a value for global args', function(done) { var service = Service.allServices()[2]; Lab.expect(service.args['--frontdoor-url']).to.eql('http://127.0.0.1:8080'); done(); }); Lab.experiment('array arguments', function() { Lab.it('should handle array args', function(done) { var service = Service.allServices()[1]; Lab.expect(service.args.indexOf('--apple')).to.be.gt(-1); done(); }); Lab.it('should combine global args with service level args', function(done) { Config({ serviceJsonPath: './test/fixtures/args-service.json' }); var service = Service.allServices()[0]; Lab.expect(service.args[0]).to.eql('a'); Lab.expect(service.args.indexOf("--apple")).to.not.eql(-1); done(); }); }); }); Lab.experiment('commands', function() { Lab.it('should generate appropriate start/stop/restart commands for OSX', function(done) { Config({ platform: 'darwin', daemonsDirectory: './' }); var service = Service.allServices()[0]; service.execCommand = function(command, cb) { Lab.expect(command).to.match(/launchctl.*load.*/) }; service.runCommand('start'); service.execCommand = function(command, cb) { Lab.expect(command).to.match(/launchctl.*unload.*launchctl.*load/) }; service.runCommand('restart'); service.execCommand = function(command, cb) { Lab.expect(command).to.match(/launchctl.*unload.*/); }; service.runCommand('stop'); done(); }); Lab.it('should generate appropriate start/stop/restart commands for Centos', function(done) { Config({ platform: 'centos', daemonsDirectory: './' }); var service = Service.allServices()[0] service.execCommand = function(command, cb) { Lab.expect(command).to.eql("initctl start ndm-test"); }; service.runCommand('start'); service.execCommand = function(command, cb) { Lab.expect(command).to.eql("initctl restart ndm-test"); }; service.runCommand('restart'); service.execCommand = function(command, cb) { Lab.expect(command).to.eql("initctl stop ndm-test"); }; service.runCommand('stop'); done(); }); Lab.it('should generate appropriate start/stop/restart commands for Ubuntu', function(done) { Config({ platform: 'ubuntu', daemonsDirectory: './' }); var service = Service.allServices()[0]; service.execCommand = function(command, cb) { Lab.expect(command).to.eql("service ndm-test start"); }; service.runCommand('start'); service.execCommand = function(command, cb) { Lab.expect(command).to.eql("service ndm-test restart"); }; service.runCommand('restart'); service.execCommand = function(command, cb) { Lab.expect(command).to.eql("service ndm-test stop"); }; service.runCommand('stop'); done(); }); }); Lab.experiment('generateScript', function() { function sharedAssertions(script) { // local environment variables populated. Lab.expect(script).to.match(/PORT/); Lab.expect(script).to.match(/8000/); // global environment variables populated. Lab.expect(script).to.match(/APP/) Lab.expect(script).to.match(/my-test-app/); // local args varibles populated. Lab.expect(script).to.match(/--kitten/); Lab.expect(script).to.match(/cute/); // global ags variables populated. Lab.expect(script).to.match(/--batman/); Lab.expect(script).to.match(/greatest-detective/); } Lab.experiment('darwin', function() { Lab.it('should genterate a script with the appropriate variables populated', function(done) { // test generating a script for darwin. Config({ platform: 'darwin', daemonsDirectory: './' }); var service = Service.allServices()[0]; service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // it should populate the bin for the script. Lab.expect(script).to.match(/>.\/test.js/) done(); }); }); }); Lab.experiment('centos', function() { Lab.it('should genterate a script with the appropriate variables populated', function(done) { Config({ platform: 'centos', daemonsDirectory: './' }); var service = Service.allServices()[0] service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // we should not try to su. Lab.expect(script).to.not.match(/su -/); // it should populate the bin for the script. Lab.expect(script).to.match(/bin\/node \.\/test.js/) done(); }); }); Lab.it('should switch su to uid user, if uid is provided', function(done) { Config({ platform: 'centos', daemonsDirectory: './', uid: 'npm' }); var service = Service.allServices()[0]; service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // we should try to step down our privileges. Lab.expect(script).to.match(/su - npm/); done(); }); }); }); Lab.experiment('ubuntu', function() { Lab.it('should genterate a script with the appropriate variables populated', function(done) { Config({ platform: 'linux', daemonsDirectory: './' }); var service = Service.allServices()[0] service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // it should populate the bin for the script. Lab.expect(script).to.match(/bin\/node \.\/test.js/) done(); }); }); }); Lab.it('should raise an appropriate exception if JSON is invalid', function(done) { Config({ platform: 'linux', daemonsDirectory: './', serviceJsonPath: './test/fixtures/invalid-service.json' }); Lab.expect(function() { var service = Service.allServices(); }).to.throw(Error, /invalid service.json, check file for errors/); done(); }); Lab.it('should pass arguments after -- to generated script', function(done) { Config({ platform: 'linux', daemonsDirectory: './' }); Array.prototype.push.apply(process.argv, ['--', '--foovar', 'barvalue']) var service = Service.allServices()[0] service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); sharedAssertions(script); // it should populate the bin for the script. Lab.expect(script).to.match(/--foovar barvalue/) done(); }); }); Lab.it('should output an array of arguments appropriately to generated script', function(done) { Config({ platform: 'linux', daemonsDirectory: './', serviceJsonPath: './test/fixtures/args-service.json' }); var service = Service.allServices()[0]; service.generateScript(function() { // inspect the generated script, and make sure we've // populated the appropriate stanzas. var script = fs.readFileSync(service.scriptPath()).toString(); // it should populate the bin for the script. Lab.expect(script).to.match(/--spider-man sad/) done(); }); }); Lab.it('should redirect stderr and stdout to log file by default', function(done) { Config({ platform: 'linux', daemonsDirectory: './', serviceJsonPath: './test/fixtures/args-service.json' }); var service = Service.allServices()[0]; service.generateScript(function() { var script = fs.readFileSync(service.scriptPath()).toString(); // it should redirect script output. Lab.expect(script).to.match(/>>.* 2>&1/); done(); }); }); Lab.it('should allow stdout/stderr redirect to be overridden by console', function(done) { Config({ platform: 'linux', daemonsDirectory: './', console: 'log', serviceJsonPath: './test/fixtures/args-service.json' }); var service = Service.allServices()[0]; service.generateScript(function() { var script = fs.readFileSync(service.scriptPath()).toString(); Lab.expect(script).to.not.match(/>>.* 2>&1/); // it should use upstart's logging. Lab.expect(script).to.match(/console log/); done(); }); }); }); Lab.experiment('removeScript', function() { Lab.it('should remove a generated script', function(done) { Config({ platform: 'darwin', daemonsDirectory: './' }); //generate a script so we have something to remove var service = Service.allServices()[0]; service.generateScript(function() { service.removeScript(function() { var exists = fs.existsSync(service.scriptPath()); // it should populate the bin for the script. Lab.expect(exists).to.eql(false) done(); }); }); }); }); Lab.experiment('listScripts', function() { Lab.it('should list scripts provided by service', function(done) { Config({ headless: true, logger: { success: function(msg) { Lab.expect(msg).to.match(/foo/) done(); } } }); var service = Service.allServices()[0]; service.listScripts(); }) }); Lab.experiment('hasScript', function() { Lab.it('returns true if a script exists corresponding to the name provided', function(done) { var service = Service.allServices()[0]; Lab.expect(service.hasScript('foo')).to.eql(true); done(); }); Lab.it('returns false if a script does not exist corresponding to the name provided', function(done) { var service = Service.allServices()[0]; Lab.expect(service.hasScript('bar')).to.eql(false); done(); }); }); Lab.experiment('runScript', function() { Lab.it('should execute matching script for service', function(done) { Config({ headless: true, utils: { loadServiceJson: require('../lib/utils').loadServiceJson, resolve: path.resolve, exec: function(cmd, cb) { Lab.expect(cmd).to.match(/\.\/bin\/foo\.js/); done(); } } }); var service = Service.allServices()[0]; service.runScript('foo'); }); Lab.it('should not explode if script does not exist', function(done) { Config({ headless: true, }); var service = Service.allServices()[0]; service.runScript('banana', function() { done(); }); }); Lab.it('should execute the script with the appropriate arguments', function(done) { Config({ headless: true, utils: { loadServiceJson: require('../lib/utils').loadServiceJson, resolve: path.resolve, exec: function(cmd, cb) { Lab.expect(cmd).to.match(/--dog also-cute/); Lab.expect(cmd).to.match(/--batman greatest-detective/); done(); } } }); var service = Service.allServices()[0]; service.runScript('foo'); }); Lab.it('should execute the script with environment variables prepended', function(done) { Config({ headless: true, utils: { loadServiceJson: require('../lib/utils').loadServiceJson, resolve: path.resolve, exec: function(cmd, cb) { Lab.expect(cmd).to.match(/PORT="8000"/); done(); } } }); var service = Service.allServices()[0]; service.runScript('foo'); }); Lab.it('should pass process.argv arguments to script', function(done) { Config({ headless: true, utils: { loadServiceJson: require('../lib/utils').loadServiceJson, resolve: path.resolve, exec: function(cmd, cb) { Lab.expect(cmd).to.match(/--timeout=8000/); done(); } } }); var service = Service.allServices()[0]; service.runScript('foo'); }); }); Lab.experiment('_startScript', function() { Lab.it('should remove node bin from the start script', function(done) { var service = Service.allServices()[0], startScript = service._startScript([]); Lab.expect(startScript).to.eql('./test.js'); done(); }); Lab.it('should add arguments from scripts.start to flatArgs', function(done) { var service = Service.allServices()[0], args = ['foo'], startScript = service._startScript(args); Lab.expect(args[0]).to.eql('convert'); Lab.expect(args).to.contain('foo'); done(); }); }); Lab.experiment('_fixPath', function() { Lab.it('should replace ./ with absolute path to working directory', function(done) { var service = Service.allServices()[0]; Lab.expect(service._fixPath('./foo')).to.eql(path.resolve('./foo')); Lab.expect(service._fixPath('bar=./foo')).to.eql('bar=' + path.resolve('./foo')); done(); }); Lab.it('should replace ~/ with absolute path to the home directory', function(done) { var service = Service.allServices()[0]; Lab.expect(service._fixPath('~/foo')).to.eql(process.env['HOME'] + '/foo'); Lab.expect(service._fixPath('bar=~/foo')).to.eql('bar=' + process.env['HOME'] + '/foo'); done(); }); }); Lab.experiment('_workingDirectory', function() { Lab.it('uses ./node_modules/<service-name> if not self-referential module', function(done) { var service = Service.allServices()[0]; Lab.expect(service.workingDirectory).to.match(/node_modules\/ndm-test/); done(); }); Lab.it('uses ./ if self-referential module', function(done) { var service = Service.allServices()[2]; Lab.expect(service.workingDirectory).to.eql(path.resolve(__dirname, '../')); done(); }); }); Lab.experiment('_serviceJsonPath', function() { Lab.it('returns serviceJsonPath if it exists', function(done) { var expectedPath = path.resolve(__dirname, '../service.json'), config = Config({ headless: true, serviceJsonPath: expectedPath, }); Lab.expect(Service._serviceJsonPath()).to.eql(expectedPath); Lab.expect(config.logsDirectory).to.eql(config.defaultLogsDirectory()); done(); }); Lab.it('returns package.json path if no service.json found', function(done) { var config = Config({ headless: true, serviceJsonPath: path.resolve(__dirname, './fixtures/node_modules/@npm/ndm-test2/service.json') }); Lab.expect(Service._serviceJsonPath()).to.eql( path.resolve(__dirname, './fixtures/node_modules/@npm/ndm-test2/package.json') ); done(); }); Lab.it('finds service in ./node_modules if no service.json found elsewhere', function(done) { var config = Config({ headless: true, serviceJsonPath: './bin/service.json', // path to service.json that does not exist. }); Lab.expect(Service._serviceJsonPath('ndm-test')).to.match(/\/node_modules\/ndm-test\/service\.json/); Lab.expect(config.serviceJsonPath).to.match(/\/node_modules\/ndm-test\/service\.json/); Lab.expect(config.baseWorkingDirectory).to.match(/\/node_modules\/ndm-test/); done(); }); Lab.it('falls back to package.json from service.json when installing global module', function(done) { var config = Config({ headless: true, serviceJsonPath: './bin/service.json', // path to service.json that does not exist. }); Lab.expect(Service._serviceJsonPath('mocha')).to.match(/\/node_modules\/mocha\/package\.json/); Lab.expect(config.serviceJsonPath).to.match(/\/node_modules\/mocha\/package\.json/); Lab.expect(config.baseWorkingDirectory).to.match(/\/node_modules\/mocha/); done(); }); Lab.it('finds service in modulePrefix directory if no service.json found elsewhere', function(done) { var config = Config({ headless: true, modulePrefix: './test/fixtures', serviceJsonPath: './bin/service.json', // path to service.json that does not exist. }); Lab.expect(Service._serviceJsonPath('ndm-test')).to.match( /\/fixtures\/node_modules\/ndm-test\/service\.json/ ); Lab.expect(config.serviceJsonPath).to.match( /\/fixtures\/node_modules\/ndm-test\/service\.json/ ); done(); }); Lab.it('uses os logging directory if service is found using discovery', function(done) { var config = Config({ headless: true, modulePrefix: './test/fixtures', serviceJsonPath: './bin/service.json', // path to service.json that does not exist. }); Service._serviceJsonPath('ndm-test'); Lab.expect(config.logsDirectory).to.eql(config.osLogsDirectory); done(); }); Lab.it('uses logging directory flag if an override is provided', function(done) { var config = Config({ headless: true, logsDirectory: '/special/logs', modulePrefix: './test/fixtures', serviceJsonPath: './bin/service.json', // path to service.json that does not exist. }); Service._serviceJsonPath('ndm-test'); Lab.expect(config.logsDirectory).to.eql('/special/logs'); done(); }); }); Lab.experiment('transformPackageJson', function() { Lab.it('can load a service from package.json rather than service.json', function(done) { var serviceJson = JSON.parse(fs.readFileSync( './node_modules/ndm-test/package.json', 'utf-8' )); var serviceJson = Service.transformPackageJson(serviceJson); Lab.expect(Object.keys(serviceJson)[0]).to.eql('ndm-test'); Lab.expect(serviceJson['ndm-test'].scripts.start).to.eql('node ./test.js'); done(); }); }); });
Lab.experiment('developmentMode flag properly affects caching', function () { Lab.before(function (done) { prodServer = new Hapi.Server('localhost', 3001); devServer = new Hapi.Server('localhost', 3002); async.parallel({ prod: function (next) { prodServer.pack.register([{ plugin: MoonbootsHapi, options: prod_options }], next); }, dev: function (next) { devServer.pack.register([{ plugin: MoonbootsHapi, options: dev_options }], next); } }, function (err) { if (err) { process.stderr.write('Unable to setUp tests', err, '\n'); process.exit(1); } done(); }); }); Lab.test('app path cache header', function (done) { devServer.inject({ method: 'GET', url: '/app', }, function _devApp(res) { Lab.expect(res.headers['cache-control'], 'cache-control header').to.equal('no-store'); done(); }); }); Lab.test('js path cache header', function (done) { devServer.inject({ method: 'GET', url: '/' + devMoonboots.jsFileName() }, function _devJs(res) { Lab.expect(res.headers['cache-control'], 'cache-control header').to.equal('no-cache'); done(); }); }); Lab.test('css path cache header', function (done) { devServer.inject({ method: 'GET', url: '/' + devMoonboots.cssFileName() }, function _devCss(res) { Lab.expect(res.headers['cache-control'], 'cache-control header').to.equal('no-cache'); done(); }); }); Lab.test('production app cache header', function (done) { prodServer.inject({ method: 'GET', url: '/app' }, function _prodApp(res) { Lab.expect(res.headers['cache-control'], 'cache-control header').to.equal('no-store'); done(); }); }); Lab.test('prodJs', function (done) { prodServer.inject({ method: 'GET', url: '/' + prodMoonboots.jsFileName() }, function _prodJs(res) { Lab.expect(res.headers['cache-control'], 'cache-control header').to.equal('max-age=31104000, must-revalidate'); done(); }); }); Lab.test('prodCss', function (done) { prodServer.inject({ method: 'GET', url: '/' + prodMoonboots.cssFileName() }, function _prodCss(res) { Lab.expect(res.headers['cache-control'], 'cache-control header').to.equal('max-age=31104000, must-revalidate'); done(); }); }); });
Lab.experiment("Get Random Word", function() { var options = {}, server, delay = 0 Lab.before(function (done) { //don't drop previous inserted data Server.options[1].options.drop = false server = new Server.getServer() options.method = 'GET' options.headers = headers // Wait 1 second setTimeout(function () { done() }, 1000) }) Lab.beforeEach(function (done) { options = {} options.headers = headers done() }) Lab.test("Random word", function (done) { options.url = '/api/word/random' server.inject(options, function(response) { Lab.expect(response.statusCode).to.equal(200) var result = response.result Lab.expect(result).to.be.Object Lab.expect(result.result).to.be.Object Lab.expect(result.result.createdAt).not.to.be.ok Lab.expect(result.result.id).to.be.ok setTimeout(done, delay) }) }) Lab.test("Random Word and extended", function (done) { options.url = '/api/word/random?extended=true' server.inject(options, function(response) { Lab.expect(response.statusCode).to.equal(200) var result = response.result Lab.expect(result).to.be.Object Lab.expect(result.result).to.be.Object Lab.expect(result.result.createdAt).to.be.ok setTimeout(done, delay) }) }) })
var Lab = require('lab'); var restfs = require('../fileserver.js'); var express = require('express'); var server = express(); restfs(server); Lab.experiment('create tests', function () { Lab.test('try to create without express app', function (done) { try { restfs(); } catch (err) { if (err) { return done(); } return (err); } }); Lab.test('test invalid setModifyOut', function (done) { try { server.setModifyOut("fake"); } catch (err) { done(); } }); });
Lab.experiment('basic create tests', function () { Lab.beforeEach(function (done) { cleanBase(done); }); Lab.test('create empty file PUT', function (done) { var filepath = baseFolder+'/test_file.txt'; createFile(filepath, done); }); Lab.test('create empty file POST', function (done) { var filepath = baseFolder+'/test_file.txt'; createFilePost(filepath, done); }); Lab.test('create empty file POST w/ encoding', function (done) { var filepath = baseFolder+'/test_file.txt'; createFilePost(filepath, {encoding: "utf8"}, done); }); Lab.test('create empty file POST w/ mode', function (done) { var filepath = baseFolder+'/test_file.txt'; createFilePost(filepath, {mode: 777}, done); }); Lab.test('create empty file POST w/ content', function (done) { var filepath = baseFolder+'/test_file.txt'; createFilePost(filepath, {content: "testText"}, done); }); Lab.test('create empty file PUT w/ encoding', function (done) { var filepath = baseFolder+'/test_file.txt'; createFile(filepath, {encoding: "utf8"}, done); }); Lab.test('create empty file PUT w/ mode', function (done) { var filepath = baseFolder+'/test_file.txt'; createFile(filepath, {mode: 777}, done); }); Lab.test('create file with spaces in filename PUT', function (done) { var filepath = baseFolder+'/test file.txt'; createFile(filepath, done); }); Lab.test('create file with text PUT', function (done) { var filepath = baseFolder+'/test_file.txt'; var testText = "test"; createFile(filepath, {content: testText}, function(err) { fs.readFile(filepath, { encoding: 'utf8' }, function (err, data) { if (err) { return done(err); } else if (!~data.indexOf(testText)) { return done(new Error('incorrect data')); } else { return done(); } }); }); }); Lab.test('create file with text and spaces in file name PUT', function (done) { var filepath = baseFolder+'/test file.txt'; var testText = "test"; createFile(filepath, {content: testText}, function(err) { fs.readFile(filepath, { encoding: 'utf8' }, function (err, data) { if (err) { return done(err); } else if (!~data.indexOf(testText)) { return done(new Error('incorrect data')); } else { return done(); } }); }); }); Lab.test('create file in path that does not exist PUT', function (done) { var filepath = baseFolder+'/fake/test_file.txt'; createFile(filepath, function (err, data) { if (err) { if (err.code === 'ENOENT') { return done(); } return done(new Error('file should not have been created')); } }); }); Lab.test('overwrite file PUT', function (done) { var filepath = baseFolder+'/test_file.txt'; var testText = "test"; var testText2 = "wonder"; createFile(filepath, {content: testText}, function(err) { createFile(filepath, {content: testText2}, function(err) { fs.readFile(filepath, { encoding: 'utf8' }, function (err, data) { if (err) { return done(err); } else if (!~data.indexOf(testText2)) { return done(new Error('incorrect data')); } else { return done(); } }); }); }); }); });