<commit_before>'use strict';
const Path = require('path');
const Chai = require('chai');
const expect = Chai.expect;
const Sinon = require('sinon');

const sinonChai = require('sinon-chai');
Chai.use(sinonChai);

const page = require(Path.resolve(__dirname, '../../../src/controllers/pageController.js'));
const Board = require('../../../src/model/Board');
const Game = require('../../../src/model/Game');
const Thread = require('../../../src/model/Thread');
const Post = require('../../../src/model/Post');

describe('Page API controller', () => {
	let sandbox;

	beforeEach(() => {
		sandbox = Sinon.createSandbox();
	});

	afterEach( () => {
		sandbox.restore();
	});

	describe('Home page', () => {

		it('should exist', () => {
			expect(page.getHomePage).to.be.a('function');
		});

		it('should render the home template', () => {
			sandbox.stub(Board, 'getAllBoards').resolves();
			sandbox.stub(Game, 'getAllGames').resolves();

			const fakeRes = {
				render: sandbox.stub(),
				status: (num) => {
					expect(num).to.equal(200);
				}
			};

			const fakeReq = {};
			return page.getHomePage(fakeReq, fakeRes).then(() => {
				expect(fakeRes.render.calledWith('home')).to.be.equal(true);
			});
		});

		it('should return 500 on error retrieving boards', () => {
			const errortext = new Error(`foo bared her tits to the world in ${Math.floor(Math.random() * 10000)}`);
			sandbox.stub(Board, 'getAllBoards').rejects(errortext);
			sandbox.stub(Game, 'getAllGames').resolves();

			const fakeRes = {
				render: sandbox.stub(),
				status: sandbox.stub(),
				send: sandbox.stub()
			};
			fakeRes.status.returns(fakeRes);

			const fakeReq = {};
			return page.getHomePage(fakeReq, fakeRes)
				.then(() => fakeRes.status.should.have.been.calledWith(500))
				.then(() => fakeRes.send.should.have.been.calledWith({
					error: errortext.toString()
				}));
		});

		it('should render a list of boards', () => {
			const fakeRes = {
				render: sandbox.stub(),
				status: (num) => {
					expect(num).to.equal(200);
				}
			};

			const boardList = [{
				ID: '1',
				Name: 'test board',
				Adult: false,
				Tags: [],
				IC: null,
				Canonical: '/api/boards/1'
			}, {
				ID: '2',
				Name: 'test board 2',
				Adult: false,
				Tags: [],
				IC: null,
				Canonical: '/api/boards/2'
			}];

			const fakeReq = {};

			sandbox.stub(Board, 'getAllBoards').resolves(boardList.map((board) => new Board(board)));
			sandbox.stub(Game, 'getAllGames').resolves();

			return page.getHomePage(fakeReq, fakeRes).then(() => {
				expect(Board.getAllBoards.called).to.be.equal(true);
				expect(fakeRes.render.calledWith('home')).to.be.equal(true);
				const data = fakeRes.render.args[0][1];
				expect(data.boards).to.deep.equal(boardList);
			});
		});

		it('should render a list of games', () => {
			const fakeRes = {
				render: sandbox.stub(),
				status: (num) => {
					expect(num).to.equal(200);
				}
			};

			const gameList = [{
				ID: '1',
				Name: 'test board',
				Adult: false,
				Tags: [],
				IC: null,
				Canonical: '/api/games/1',
				Game: {
					ID: 1,
					gameDescription: ''
				}
			}, {
				ID: '2',
				Name: 'test board 2',
				Adult: false,
				Tags: [],
				IC: null,
				Canonical: '/api/games/2',
				Game: {
					ID: 1,
					gameDescription: ''
				}
			}];

			const fakeReq = {};

			sandbox.stub(Board, 'getAllBoards').resolves();
			sandbox.stub(Game, 'getAllGames').resolves(gameList.map((game) => new Game(game)));

			return page.getHomePage(fakeReq, fakeRes).then(() => {
				expect(Game.getAllGames.called).to.be.equal(true);
				expect(fakeRes.render.calledWith('home')).to.be.equal(true);
				const data = fakeRes.render.args[0][1];
				expect(data.games).to.deep.equal(gameList);
			});
		});
	});

	describe('Board view', () => {
		let fakeRes, boardData;

		beforeEach(() => {
			sandbox = Sinon.createSandbox();
			fakeRes = {
				render: sandbox.stub(),
				status: sandbox.stub(),
				send: sandbox.stub(),
				end: sandbox.stub()
			};

			boardData = {
				ID: Math.random(),
				Name: 'some board'
			};
		});

		afterEach( () => {
			sandbox.restore();
		});

		it('should exist', () => {
			expect(page.getBoardView).to.be.a('function');
		});

		it('should fetch board and threads from the api', () => {
			const board = new Board(boardData);
			sandbox.stub(Board, 'getBoard').resolves(board);
			sandbox.stub(Thread, 'getThreadsInBoard').resolves([]);
			sandbox.spy(board, 'serialize');

			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(Board.getBoard).to.have.been.calledWith(100);
				expect(Thread.getThreadsInBoard).to.have.been.calledWith(100);
				expect(board.serialize).to.have.been.called;
			});
		});

		it('should fetch board and threads from the api (null threads)', () => {
			const board = new Board(boardData);
			sandbox.stub(Board, 'getBoard').resolves(board);
			sandbox.stub(Thread, 'getThreadsInBoard').resolves(null);
			sandbox.spy(board, 'serialize');

			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(Board.getBoard).to.have.been.calledWith(100);
				expect(Thread.getThreadsInBoard).to.have.been.calledWith(100);
				expect(board.serialize).to.have.been.called;
			});
		});

		it('should render the template', () => {
			const board = new Board(boardData);

			const threadData = {
				Title: 'some thread',
				ID: 2942,
				Canonical: '/api/threads/2942'
			};

			sandbox.stub(Board, 'getBoard').resolves(board);
			sandbox.stub(Thread, 'getThreadsInBoard').resolves([new Thread(threadData)]);
			sandbox.spy(board, 'serialize');

			const fakeReq = {
				params: {
					id: 100
				}
			};

			const expected = {
				Name: boardData.Name,
				Adult: false,
				Canonical: `/api/boards/${boardData.ID}`,
				ID: boardData.ID,
				threads: [threadData]
			};

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.render).to.have.been.calledWith('board');
				const actual = fakeRes.render.firstCall.args[1];
				expect(actual).to.deep.equal(expected);
			});
		});

		it('should return 404 if no board is found', () => {
			sandbox.stub(Board, 'getBoard').resolves(undefined);
			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.status).to.have.been.calledWith(404);
			});
		});

		it('should return 500 if error is thrown', () => {
			sandbox.stub(Board, 'getBoard').rejects('I AM ERROR');
			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.status).to.have.been.calledWith(500);
			});
		});

	});

	describe('Thread view', () => {
		let fakeRes, fakeThread;

		beforeEach(() => {
			sandbox = Sinon.createSandbox();
			fakeRes = {
				render: sandbox.stub(),
				status: sandbox.stub(),
				send: sandbox.stub(),
				end: sandbox.stub()
			};

			fakeThread = {
				ID: Math.random(),
				Title: 'some thread'
			};
		});

		afterEach( () => {
			sandbox.restore();
		});

		it('should exist', () => {
			expect(page.getThreadView).to.be.a('function');
		});

		it('should fetch thread and posts from the api', () => {
			const threadObj = new Thread(fakeThread);
			sandbox.stub(Thread, 'getThread').resolves(threadObj);
			sandbox.stub(Post, 'getPostsInThread').resolves([]);
			sandbox.spy(threadObj, 'serialize');

			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(Thread.getThread).to.have.been.calledWith(100);
				expect(Post.getPostsInThread).to.have.been.calledWith(100);
				expect(threadObj.serialize).to.have.been.called;
			});
		});

		it('should fetch thread and posts from the api (null posts)', () => {
			const threadObj = new Thread(fakeThread);
			sandbox.stub(Thread, 'getThread').resolves(threadObj);
			sandbox.stub(Post, 'getPostsInThread').resolves(null);
			sandbox.spy(threadObj, 'serialize');

			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(Thread.getThread).to.have.been.calledWith(100);
				expect(Post.getPostsInThread).to.have.been.calledWith(100);
				expect(threadObj.serialize).to.have.been.called;
			});
		});

		it('should render the template', () => {
			const fakePostData = {
				Body: 'The only post in the thread',
				ID: 23,
				Canonical: '/api/posts/23'
			};

			const expected = {
				Title: fakeThread.Title,
				Canonical: `/api/threads/${fakeThread.ID}`,
				ID: fakeThread.ID,
				posts: [fakePostData]
			};

			sandbox.stub(Thread, 'getThread').resolves(new Thread(fakeThread));
			sandbox.stub(Post, 'getPostsInThread').resolves([new Post(fakePostData)]);

			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.render).to.have.been.calledWith('thread');
				const actual = fakeRes.render.firstCall.args[1];
				expect(actual).to.deep.equal(expected);
			});
		});

		it('should return 404 if no thread is found', () => {
			sandbox.stub(Thread, 'getThread').resolves(undefined);
			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.status).to.have.been.calledWith(404);
			});
		});

		it('should return 500 if an error is thrown', () => {
			sandbox.stub(Thread, 'getThread').rejects('SQL kaboom!');
			const fakeReq = {
				params: {
					id: 100
				}
			};

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.status).to.have.been.calledWith(500);
			});
		});
	});
});
<commit_msg>chore: Make pageTests.js happier by setting isAuthenticated always in fake requests. In the future we should consider a more full featured way of dealing with fake request objects maybe?<commit_after>'use strict';
const Path = require('path');
const Chai = require('chai');
const expect = Chai.expect;
const Sinon = require('sinon');

const sinonChai = require('sinon-chai');
Chai.use(sinonChai);

const page = require(Path.resolve(__dirname, '../../../src/controllers/pageController.js'));
const Board = require('../../../src/model/Board');
const Game = require('../../../src/model/Game');
const Thread = require('../../../src/model/Thread');
const Post = require('../../../src/model/Post');

const unauthenticatedFakeReq = (tbl) => {
	tbl.isAuthenticated = () => false;
	return tbl;
};

describe('Page API controller', () => {
	let sandbox;

	beforeEach(() => {
		sandbox = Sinon.createSandbox();
	});

	afterEach( () => {
		sandbox.restore();
	});

	describe('Home page', () => {

		it('should exist', () => {
			expect(page.getHomePage).to.be.a('function');
		});

		it('should render the home template', () => {
			sandbox.stub(Board, 'getAllBoards').resolves();
			sandbox.stub(Game, 'getAllGames').resolves();

			const fakeRes = {
				render: sandbox.stub(),
				status: (num) => {
					expect(num).to.equal(200);
				}
			};

			const fakeReq = unauthenticatedFakeReq({});
			return page.getHomePage(fakeReq, fakeRes).then(() => {
				expect(fakeRes.render.calledWith('home')).to.be.equal(true);
			});
		});

		it('should return 500 on error retrieving boards', () => {
			const errortext = new Error(`foo bared her tits to the world in ${Math.floor(Math.random() * 10000)}`);
			sandbox.stub(Board, 'getAllBoards').rejects(errortext);
			sandbox.stub(Game, 'getAllGames').resolves();

			const fakeRes = {
				render: sandbox.stub(),
				status: sandbox.stub(),
				send: sandbox.stub()
			};
			fakeRes.status.returns(fakeRes);

			const fakeReq = unauthenticatedFakeReq({});
			return page.getHomePage(fakeReq, fakeRes)
				.then(() => fakeRes.status.should.have.been.calledWith(500))
				.then(() => fakeRes.send.should.have.been.calledWith({
					error: errortext.toString()
				}));
		});

		it('should render a list of boards', () => {
			const fakeRes = {
				render: sandbox.stub(),
				status: (num) => {
					expect(num).to.equal(200);
				}
			};

			const boardList = [{
				ID: '1',
				Name: 'test board',
				Adult: false,
				Tags: [],
				IC: null,
				Canonical: '/api/boards/1'
			}, {
				ID: '2',
				Name: 'test board 2',
				Adult: false,
				Tags: [],
				IC: null,
				Canonical: '/api/boards/2'
			}];

			const fakeReq = unauthenticatedFakeReq({});

			sandbox.stub(Board, 'getAllBoards').resolves(boardList.map((board) => new Board(board)));
			sandbox.stub(Game, 'getAllGames').resolves();

			return page.getHomePage(fakeReq, fakeRes).then(() => {
				expect(Board.getAllBoards.called).to.be.equal(true);
				expect(fakeRes.render.calledWith('home')).to.be.equal(true);
				const data = fakeRes.render.args[0][1];
				expect(data.boards).to.deep.equal(boardList);
			});
		});

		it('should render a list of games', () => {
			const fakeRes = {
				render: sandbox.stub(),
				status: (num) => {
					expect(num).to.equal(200);
				}
			};

			const gameList = [{
				ID: '1',
				Name: 'test board',
				Adult: false,
				Tags: [],
				IC: null,
				Canonical: '/api/games/1',
				Game: {
					ID: 1,
					gameDescription: ''
				}
			}, {
				ID: '2',
				Name: 'test board 2',
				Adult: false,
				Tags: [],
				IC: null,
				Canonical: '/api/games/2',
				Game: {
					ID: 1,
					gameDescription: ''
				}
			}];

			const fakeReq = unauthenticatedFakeReq({});

			sandbox.stub(Board, 'getAllBoards').resolves();
			sandbox.stub(Game, 'getAllGames').resolves(gameList.map((game) => new Game(game)));

			return page.getHomePage(fakeReq, fakeRes).then(() => {
				expect(Game.getAllGames.called).to.be.equal(true);
				expect(fakeRes.render.calledWith('home')).to.be.equal(true);
				const data = fakeRes.render.args[0][1];
				expect(data.games).to.deep.equal(gameList);
			});
		});
	});

	describe('Board view', () => {
		let fakeRes, boardData;

		beforeEach(() => {
			sandbox = Sinon.createSandbox();
			fakeRes = {
				render: sandbox.stub(),
				status: sandbox.stub(),
				send: sandbox.stub(),
				end: sandbox.stub()
			};

			boardData = {
				ID: Math.random(),
				Name: 'some board'
			};
		});

		afterEach( () => {
			sandbox.restore();
		});

		it('should exist', () => {
			expect(page.getBoardView).to.be.a('function');
		});

		it('should fetch board and threads from the api', () => {
			const board = new Board(boardData);
			sandbox.stub(Board, 'getBoard').resolves(board);
			sandbox.stub(Thread, 'getThreadsInBoard').resolves([]);
			sandbox.spy(board, 'serialize');

			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(Board.getBoard).to.have.been.calledWith(100);
				expect(Thread.getThreadsInBoard).to.have.been.calledWith(100);
				expect(board.serialize).to.have.been.called;
			});
		});

		it('should fetch board and threads from the api (null threads)', () => {
			const board = new Board(boardData);
			sandbox.stub(Board, 'getBoard').resolves(board);
			sandbox.stub(Thread, 'getThreadsInBoard').resolves(null);
			sandbox.spy(board, 'serialize');

			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(Board.getBoard).to.have.been.calledWith(100);
				expect(Thread.getThreadsInBoard).to.have.been.calledWith(100);
				expect(board.serialize).to.have.been.called;
			});
		});

		it('should render the template', () => {
			const board = new Board(boardData);

			const threadData = {
				Title: 'some thread',
				ID: 2942,
				Canonical: '/api/threads/2942'
			};

			sandbox.stub(Board, 'getBoard').resolves(board);
			sandbox.stub(Thread, 'getThreadsInBoard').resolves([new Thread(threadData)]);
			sandbox.spy(board, 'serialize');

			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			const expected = {
				Name: boardData.Name,
				Adult: false,
				Canonical: `/api/boards/${boardData.ID}`,
				ID: boardData.ID,
				threads: [threadData]
			};

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.render).to.have.been.calledWith('board');
				const actual = fakeRes.render.firstCall.args[1];
				expect(actual).to.deep.equal(expected);
			});
		});

		it('should return 404 if no board is found', () => {
			sandbox.stub(Board, 'getBoard').resolves(undefined);
			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.status).to.have.been.calledWith(404);
			});
		});

		it('should return 500 if error is thrown', () => {
			sandbox.stub(Board, 'getBoard').rejects('I AM ERROR');
			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getBoardView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.status).to.have.been.calledWith(500);
			});
		});

	});

	describe('Thread view', () => {
		let fakeRes, fakeThread;

		beforeEach(() => {
			sandbox = Sinon.createSandbox();
			fakeRes = {
				render: sandbox.stub(),
				status: sandbox.stub(),
				send: sandbox.stub(),
				end: sandbox.stub()
			};

			fakeThread = {
				ID: Math.random(),
				Title: 'some thread'
			};
		});

		afterEach( () => {
			sandbox.restore();
		});

		it('should exist', () => {
			expect(page.getThreadView).to.be.a('function');
		});

		it('should fetch thread and posts from the api', () => {
			const threadObj = new Thread(fakeThread);
			sandbox.stub(Thread, 'getThread').resolves(threadObj);
			sandbox.stub(Post, 'getPostsInThread').resolves([]);
			sandbox.spy(threadObj, 'serialize');

			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(Thread.getThread).to.have.been.calledWith(100);
				expect(Post.getPostsInThread).to.have.been.calledWith(100);
				expect(threadObj.serialize).to.have.been.called;
			});
		});

		it('should fetch thread and posts from the api (null posts)', () => {
			const threadObj = new Thread(fakeThread);
			sandbox.stub(Thread, 'getThread').resolves(threadObj);
			sandbox.stub(Post, 'getPostsInThread').resolves(null);
			sandbox.spy(threadObj, 'serialize');

			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(Thread.getThread).to.have.been.calledWith(100);
				expect(Post.getPostsInThread).to.have.been.calledWith(100);
				expect(threadObj.serialize).to.have.been.called;
			});
		});

		it('should render the template', () => {
			const fakePostData = {
				Body: 'The only post in the thread',
				ID: 23,
				Canonical: '/api/posts/23'
			};

			const expected = {
				Title: fakeThread.Title,
				Canonical: `/api/threads/${fakeThread.ID}`,
				ID: fakeThread.ID,
				posts: [fakePostData]
			};

			sandbox.stub(Thread, 'getThread').resolves(new Thread(fakeThread));
			sandbox.stub(Post, 'getPostsInThread').resolves([new Post(fakePostData)]);

			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.render).to.have.been.calledWith('thread');
				const actual = fakeRes.render.firstCall.args[1];
				expect(actual).to.deep.equal(expected);
			});
		});

		it('should return 404 if no thread is found', () => {
			sandbox.stub(Thread, 'getThread').resolves(undefined);
			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.status).to.have.been.calledWith(404);
			});
		});

		it('should return 500 if an error is thrown', () => {
			sandbox.stub(Thread, 'getThread').rejects('SQL kaboom!');
			const fakeReq = unauthenticatedFakeReq({
				params: {
					id: 100
				}
			});

			return page.getThreadView(fakeReq, fakeRes).then(() => {
				expect(fakeRes.status).to.have.been.calledWith(500);
			});
		});
	});
});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  user: {
    username: {
      type: 'string',
      minLength: 2,
      maxLength: 32,
      pattern: '^[a-z0-9]+(-[a-z0-9]+)*$'
    },
    email: {
      type: 'string',
      pattern: '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$'
    },
    givenName: {
      type: 'string',
      maxLength: 128
    },
    familyName: {
      type: 'string',
      maxLength: 128
    },
    desc: { // description
      type: 'string',
      maxLength: 2048
    },
    password: {
      type: 'string',
      minLength: 10,
      maxLength: 512
    },
    location: {
      oneOf: [
        {
          type: 'null'
        },
        {
          type: 'array',
          minItems: 2,
          maxItems: 2,
          items: [
            {
              type: 'number',
              minimum: -90,
              maximum: 90
            },
            {
              type: 'number',
              minimum: -180,
              maximum: 180
            }
          ]
        }
      ]
    },
    code: {
      type: 'string',
      pattern: '^[0-9a-f]{32}$'
    }
  },
  tag: {
    tagname: {
      type: 'string',
      minLength: 2,
      maxLength: 64,
      pattern: '^[a-z0-9]+(-[a-z0-9]+)*$'
    }
  },
  userTag: {
    story: {
      type: 'string',
      maxLength: 1024
    },
    relevance: {
      enum: [1, 2, 3, 4, 5]
    }
  },
  contact: {
    trust: {
      enum: [1, 2, 4, 8]
    },
    message: {
      type: 'string',
      maxLength: 2048
    },
    reference: {
      type: 'string',
      maxLength: 2048
    },
  },
  idea: {
    ideaId: {
      type: 'string',
      minLength: 1,
      maxLength: 16,
      pattern: '^[0-9]*$'
    },
    titl: { // title
      type: 'string',
      minLength: 1,
      maxLength: 256,
      pattern: '\\S' // at least one non-space character
    },
    detail: {
      type: 'string',
      maxLength: 2048
    }
  },
  message: {
    body: {
      type: 'string',
      minLength: 1,
      maxLength: 2048,
      pattern: '\\S' // at least one non-space character
    },
    messageId: {
      type: 'string'
    }
  },
  query: {
    page: {
      properties: {
        offset: {
          type: 'number'
        },
        limit: {
          type: 'number',
          maximum: 20
        }
      },
      required: ['offset', 'limit'],
      additionalProperties: false
    },
    page0: {
      properties: {
        offset: {
          type: 'number',
          enum: [0]
        },
        limit: {
          type: 'number',
          maximum: 20
        }
      },
      required: ['offset', 'limit'],
      additionalProperties: false
    }
  }
};
<commit_msg>fix comment<commit_after>'use strict';

module.exports = {
  user: {
    username: {
      type: 'string',
      minLength: 2,
      maxLength: 32,
      pattern: '^[a-z0-9]+(-[a-z0-9]+)*$'
    },
    email: {
      type: 'string',
      pattern: '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$'
    },
    givenName: {
      type: 'string',
      maxLength: 128
    },
    familyName: {
      type: 'string',
      maxLength: 128
    },
    desc: { // description (reserved word in json-schema)
      type: 'string',
      maxLength: 2048
    },
    password: {
      type: 'string',
      minLength: 10,
      maxLength: 512
    },
    location: {
      oneOf: [
        {
          type: 'null'
        },
        {
          type: 'array',
          minItems: 2,
          maxItems: 2,
          items: [
            {
              type: 'number',
              minimum: -90,
              maximum: 90
            },
            {
              type: 'number',
              minimum: -180,
              maximum: 180
            }
          ]
        }
      ]
    },
    code: {
      type: 'string',
      pattern: '^[0-9a-f]{32}$'
    }
  },
  tag: {
    tagname: {
      type: 'string',
      minLength: 2,
      maxLength: 64,
      pattern: '^[a-z0-9]+(-[a-z0-9]+)*$'
    }
  },
  userTag: {
    story: {
      type: 'string',
      maxLength: 1024
    },
    relevance: {
      enum: [1, 2, 3, 4, 5]
    }
  },
  contact: {
    trust: {
      enum: [1, 2, 4, 8]
    },
    message: {
      type: 'string',
      maxLength: 2048
    },
    reference: {
      type: 'string',
      maxLength: 2048
    },
  },
  idea: {
    ideaId: {
      type: 'string',
      minLength: 1,
      maxLength: 16,
      pattern: '^[0-9]*$'
    },
    titl: { // title (reserved word in json-schema)
      type: 'string',
      minLength: 1,
      maxLength: 256,
      pattern: '\\S' // at least one non-space character
    },
    detail: {
      type: 'string',
      maxLength: 2048
    }
  },
  message: {
    body: {
      type: 'string',
      minLength: 1,
      maxLength: 2048,
      pattern: '\\S' // at least one non-space character
    },
    messageId: {
      type: 'string'
    }
  },
  query: {
    page: {
      properties: {
        offset: {
          type: 'number'
        },
        limit: {
          type: 'number',
          maximum: 20
        }
      },
      required: ['offset', 'limit'],
      additionalProperties: false
    },
    page0: {
      properties: {
        offset: {
          type: 'number',
          enum: [0]
        },
        limit: {
          type: 'number',
          maximum: 20
        }
      },
      required: ['offset', 'limit'],
      additionalProperties: false
    }
  }
};
<|endoftext|>


<commit_before>'use strict'

const chai = require('chai')
const dirtyChai = require('dirty-chai')
chai.use(dirtyChai)
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
chai.use(sinonChai)
chai.should()

const expect = chai.expect
const HttpMocks = require('node-mocks-http')

const LoginConsentRequest = require('../../src/handlers/login-consent-request')

describe('LoginConsentRequest', () => {
  describe('constructor()', () => {
    it('should initialize a new instance', () => {
      let params = { consent: true, scope: 'openid' }
      let options = {
        opAuthRequest: {},
        params,
        response: {}
      }

      let request = new LoginConsentRequest(options)

      expect(request.opAuthRequest).to.equal(options.opAuthRequest)
      expect(request.params).to.equal(options.params)
      expect(request.response).to.equal(options.response)
    })
  })

  describe('extractParams()', () => {
    it('should use req.query if present', () => {
      let req = { query: { client_id: '1234' } }
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req, res }

      let params = LoginConsentRequest.extractParams(opAuthRequest)

      expect(params['client_id']).to.equal(req.query['client_id'])
    })

    it('should use req.body if req.query is not present', () => {
      let req = { body: { client_id: '1234' } }
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req, res }

      let params = LoginConsentRequest.extractParams(opAuthRequest)

      expect(params['client_id']).to.equal(req.body['client_id'])
    })
  })

  describe('from()', () => {
    it('should return an initialized instance', () => {
      let body = { consent: true, scope: 'openid' }
      let req = { body }
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req, res }

      let request = LoginConsentRequest.from(opAuthRequest)

      expect(request.opAuthRequest).to.equal(opAuthRequest)
      expect(request.params).to.equal(req.body)
      expect(request.response).to.equal(res)
    })
  })

  describe('handle()', () => {
    it('should return the opAuthRequest object', () => {
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req: { body: {} }, res, subject: {} }

      return LoginConsentRequest.handle(opAuthRequest)
        .then(returnedRequest => {
          expect(returnedRequest).to.equal(opAuthRequest)
        })
    })

    it('should invoke obtainConsent()', () => {
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req: { body: {} }, res, subject: {} }

      let obtainConsent = sinon.spy(LoginConsentRequest, 'obtainConsent')

      return LoginConsentRequest.handle(opAuthRequest)
        .then(() => {
          expect(obtainConsent).to.have.been.called()
          obtainConsent.reset()
        })
    })

    it('should pass through opAuthRequest if skipConsent is set', () => {
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req: { body: {} }, res, subject: {} }
      let skipConsent = true

      return LoginConsentRequest.handle(opAuthRequest, skipConsent)
        .then(() => {
          expect(LoginConsentRequest.obtainConsent).to.not.have.been.called()
          LoginConsentRequest.obtainConsent.reset()
        })
    })

    it('should not invoke obtainConsent() if subject is missing', () => {
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req: { body: {} }, res }

      return LoginConsentRequest.handle(opAuthRequest)
        .then(() => {
          expect(LoginConsentRequest.obtainConsent).to.not.have.been.called()
        })
    })
  })

  describe('clientId getter', () => {
    it('should return the client_id param', () => {
      let res = HttpMocks.createResponse()
      let body = { 'client_id': '1234' }
      let opAuthRequest = { req: { body }, res }

      let request = LoginConsentRequest.from(opAuthRequest)

      expect(request.clientId).to.equal('1234')
    })
  })

  describe('isLocalRpClient()', () => {
    it('should be false if host has no local client initialized', () => {
      let params = { 'client_id': '1234' }
      let response = HttpMocks.createResponse()
      let opAuthRequest = { host: {} }

      let request = new LoginConsentRequest({ params, response, opAuthRequest })

      expect(request.isLocalRpClient('1234')).to.be.false()
    })

    it('should be false if params has no client id', () => {
      let params = {}
      let response = HttpMocks.createResponse()
      let opAuthRequest = {
        host: {}
      }

      let request = new LoginConsentRequest({ params, response, opAuthRequest })

      expect(request.isLocalRpClient(undefined)).to.be.false()
    })

    it('should be false if host local client id does not match params', () => {
      let params = { 'client_id': '1234' }
      let response = HttpMocks.createResponse()
      let opAuthRequest = {
        host: {
          localClientId: '5678'
        }
      }

      let request = new LoginConsentRequest({ params, response, opAuthRequest })

      expect(request.isLocalRpClient('1234')).to.be.false()
    })

    it('should be true if host local client id equals param client_id', () => {
      let params = { 'client_id': '1234' }
      let response = HttpMocks.createResponse()
      let opAuthRequest = {
        host: {
          localClientId: '1234'
        }
      }

      let request = new LoginConsentRequest({ params, response, opAuthRequest })

      expect(request.isLocalRpClient('1234')).to.be.true()
    })
  })

  describe('obtainConsent()', () => {
    describe('if request is for a local rp client', () => {
      let req, res, opAuthRequest
      const host = { localClientId: '1234' }
      const clientId = '1234'

      beforeEach(() => {
        req = { body: { scope: 'openid', client_id: clientId } }
        res = HttpMocks.createResponse()
        opAuthRequest = { req, res, host }
      })

      it('should mark successful consent automatically', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        return LoginConsentRequest.obtainConsent(request)
          .then(opAuthRequest => {
            expect(opAuthRequest.consent).to.be.true()
            expect(opAuthRequest.scope).to.equal('openid')
          })
      })

      it('should not call checkSavedConsentFor()', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        let checkSavedConsentFor = sinon.spy(request, 'checkSavedConsentFor')

        return LoginConsentRequest.obtainConsent(request)
          .then(() => {
            expect(checkSavedConsentFor).to.not.have.been.called()
          })
      })
    })

    describe('if body.consent param is present', () => {
      let req, res, opAuthRequest
      const host = {}
      const clientId = '1234'

      beforeEach(() => {
        req = { body: { consent: true, scope: 'openid', client_id: clientId } }
        res = HttpMocks.createResponse()
        opAuthRequest = { req, res, host }
      })

      it('should call saveConsentForClient()', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        request.saveConsentForClient = sinon.mock().returns(Promise.resolve())

        return LoginConsentRequest.obtainConsent(request)
          .then(() => {
            expect(request.saveConsentForClient).to.have.been.called()
          })
      })

      it('should set consent property on request', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        return LoginConsentRequest.obtainConsent(request)
          .then(opAuthRequest => {
            expect(opAuthRequest.consent).to.be.true()
          })
      })

      it('should set scope property on request', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        return LoginConsentRequest.obtainConsent(request)
          .then(opAuthRequest => {
            expect(opAuthRequest.scope).to.equal('openid')
          })
      })

      it('should not render any pages', () => {
        let render = sinon.stub(opAuthRequest.res, 'render')
        let request = LoginConsentRequest.from(opAuthRequest)

        return LoginConsentRequest.obtainConsent(request)
          .then(opAuthRequest => {
            expect(render).to.not.have.been.called()
          })
      })
    })

    describe('if body.consent param is NOT present', () => {
      let req, res, opAuthRequest

      beforeEach(() => {
        req = { body: { scope: 'openid' } }
        res = HttpMocks.createResponse()
        opAuthRequest = { req, res }
      })

      it('should check for previously saved consent', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        request.checkSavedConsentFor = sinon.mock()
          .returns(Promise.resolve(false))

        return LoginConsentRequest.obtainConsent(request)
          .then(() => {
            expect(request.checkSavedConsentFor).to.have.been.called()
          })
      })

      describe('if user consent has been previously saved', () => {
        it('should have marked the request as successful', () => {
          let request = LoginConsentRequest.from(opAuthRequest)

          request.checkSavedConsentFor = sinon.mock()
            .returns(Promise.resolve(true))

          return LoginConsentRequest.obtainConsent(request)
            .then(opAuthRequest => {
              expect(opAuthRequest.consent).to.be.true()
              expect(opAuthRequest.scope).to.equal('openid')
            })
        })

        it('should not have called renderConsentPage()', () => {

        })
      })

      describe('if user consent has NOT been previously saved', () => {
        it('should call renderConsentPage()', () => {
          let request = LoginConsentRequest.from(opAuthRequest)

          request.checkSavedConsentFor = sinon.mock()
            .returns(Promise.resolve(false))
          request.response.render = sinon.mock()

          let renderConsentPage = sinon.spy(request, 'renderConsentPage')

          return LoginConsentRequest.obtainConsent(request)
            .then(() => {
              expect(renderConsentPage).to.have.been.called()
            })
        })

        it('should not have marked success', () => {
          let request = LoginConsentRequest.from(opAuthRequest)

          request.checkSavedConsentFor = sinon.mock()
            .returns(Promise.resolve(false))
          request.response.render = sinon.mock()

          return LoginConsentRequest.obtainConsent(request)
            .then(opAuthRequest => {
              expect(opAuthRequest.consent).to.not.exist()
              expect(opAuthRequest.scope).to.not.exist()
            })
        })
      })
    })
  })

  describe('renderConsentPage()', () => {
    it('should call res.render', () => {
      let req = { body: {} }
      let res = HttpMocks.createResponse()

      let render = sinon.stub(res, 'render')

      let opAuthRequest = { req, res }
      let request = LoginConsentRequest.from(opAuthRequest)

      return LoginConsentRequest.obtainConsent(request)
        .then(() => {
          expect(render).to.have.been.calledWith('auth/consent')
        })
    })

    it('should set the headerSent property on opAuthRequest', () => {
      let req = { body: {} }
      let res = HttpMocks.createResponse()

      sinon.stub(res, 'render')

      let opAuthRequest = { req, res }
      let request = LoginConsentRequest.from(opAuthRequest)

      request.checkSavedConsentFor = sinon.mock()
        .returns(Promise.resolve(false))

      return LoginConsentRequest.obtainConsent(request)
        .then(opAuthRequest => {
          expect(opAuthRequest.headersSent).to.be.true()
        })
    })
  })
})
<commit_msg>Rename deprecated sinon reset() to resetHistory()<commit_after>'use strict'

const chai = require('chai')
const dirtyChai = require('dirty-chai')
chai.use(dirtyChai)
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
chai.use(sinonChai)
chai.should()

const expect = chai.expect
const HttpMocks = require('node-mocks-http')

const LoginConsentRequest = require('../../src/handlers/login-consent-request')

describe('LoginConsentRequest', () => {
  describe('constructor()', () => {
    it('should initialize a new instance', () => {
      let params = { consent: true, scope: 'openid' }
      let options = {
        opAuthRequest: {},
        params,
        response: {}
      }

      let request = new LoginConsentRequest(options)

      expect(request.opAuthRequest).to.equal(options.opAuthRequest)
      expect(request.params).to.equal(options.params)
      expect(request.response).to.equal(options.response)
    })
  })

  describe('extractParams()', () => {
    it('should use req.query if present', () => {
      let req = { query: { client_id: '1234' } }
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req, res }

      let params = LoginConsentRequest.extractParams(opAuthRequest)

      expect(params['client_id']).to.equal(req.query['client_id'])
    })

    it('should use req.body if req.query is not present', () => {
      let req = { body: { client_id: '1234' } }
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req, res }

      let params = LoginConsentRequest.extractParams(opAuthRequest)

      expect(params['client_id']).to.equal(req.body['client_id'])
    })
  })

  describe('from()', () => {
    it('should return an initialized instance', () => {
      let body = { consent: true, scope: 'openid' }
      let req = { body }
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req, res }

      let request = LoginConsentRequest.from(opAuthRequest)

      expect(request.opAuthRequest).to.equal(opAuthRequest)
      expect(request.params).to.equal(req.body)
      expect(request.response).to.equal(res)
    })
  })

  describe('handle()', () => {
    it('should return the opAuthRequest object', () => {
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req: { body: {} }, res, subject: {} }

      return LoginConsentRequest.handle(opAuthRequest)
        .then(returnedRequest => {
          expect(returnedRequest).to.equal(opAuthRequest)
        })
    })

    it('should invoke obtainConsent()', () => {
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req: { body: {} }, res, subject: {} }

      let obtainConsent = sinon.spy(LoginConsentRequest, 'obtainConsent')

      return LoginConsentRequest.handle(opAuthRequest)
        .then(() => {
          expect(obtainConsent).to.have.been.called()
          obtainConsent.resetHistory()
        })
    })

    it('should pass through opAuthRequest if skipConsent is set', () => {
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req: { body: {} }, res, subject: {} }
      let skipConsent = true

      return LoginConsentRequest.handle(opAuthRequest, skipConsent)
        .then(() => {
          expect(LoginConsentRequest.obtainConsent).to.not.have.been.called()
          LoginConsentRequest.obtainConsent.resetHistory()
        })
    })

    it('should not invoke obtainConsent() if subject is missing', () => {
      let res = HttpMocks.createResponse()
      let opAuthRequest = { req: { body: {} }, res }

      return LoginConsentRequest.handle(opAuthRequest)
        .then(() => {
          expect(LoginConsentRequest.obtainConsent).to.not.have.been.called()
        })
    })
  })

  describe('clientId getter', () => {
    it('should return the client_id param', () => {
      let res = HttpMocks.createResponse()
      let body = { 'client_id': '1234' }
      let opAuthRequest = { req: { body }, res }

      let request = LoginConsentRequest.from(opAuthRequest)

      expect(request.clientId).to.equal('1234')
    })
  })

  describe('isLocalRpClient()', () => {
    it('should be false if host has no local client initialized', () => {
      let params = { 'client_id': '1234' }
      let response = HttpMocks.createResponse()
      let opAuthRequest = { host: {} }

      let request = new LoginConsentRequest({ params, response, opAuthRequest })

      expect(request.isLocalRpClient('1234')).to.be.false()
    })

    it('should be false if params has no client id', () => {
      let params = {}
      let response = HttpMocks.createResponse()
      let opAuthRequest = {
        host: {}
      }

      let request = new LoginConsentRequest({ params, response, opAuthRequest })

      expect(request.isLocalRpClient(undefined)).to.be.false()
    })

    it('should be false if host local client id does not match params', () => {
      let params = { 'client_id': '1234' }
      let response = HttpMocks.createResponse()
      let opAuthRequest = {
        host: {
          localClientId: '5678'
        }
      }

      let request = new LoginConsentRequest({ params, response, opAuthRequest })

      expect(request.isLocalRpClient('1234')).to.be.false()
    })

    it('should be true if host local client id equals param client_id', () => {
      let params = { 'client_id': '1234' }
      let response = HttpMocks.createResponse()
      let opAuthRequest = {
        host: {
          localClientId: '1234'
        }
      }

      let request = new LoginConsentRequest({ params, response, opAuthRequest })

      expect(request.isLocalRpClient('1234')).to.be.true()
    })
  })

  describe('obtainConsent()', () => {
    describe('if request is for a local rp client', () => {
      let req, res, opAuthRequest
      const host = { localClientId: '1234' }
      const clientId = '1234'

      beforeEach(() => {
        req = { body: { scope: 'openid', client_id: clientId } }
        res = HttpMocks.createResponse()
        opAuthRequest = { req, res, host }
      })

      it('should mark successful consent automatically', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        return LoginConsentRequest.obtainConsent(request)
          .then(opAuthRequest => {
            expect(opAuthRequest.consent).to.be.true()
            expect(opAuthRequest.scope).to.equal('openid')
          })
      })

      it('should not call checkSavedConsentFor()', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        let checkSavedConsentFor = sinon.spy(request, 'checkSavedConsentFor')

        return LoginConsentRequest.obtainConsent(request)
          .then(() => {
            expect(checkSavedConsentFor).to.not.have.been.called()
          })
      })
    })

    describe('if body.consent param is present', () => {
      let req, res, opAuthRequest
      const host = {}
      const clientId = '1234'

      beforeEach(() => {
        req = { body: { consent: true, scope: 'openid', client_id: clientId } }
        res = HttpMocks.createResponse()
        opAuthRequest = { req, res, host }
      })

      it('should call saveConsentForClient()', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        request.saveConsentForClient = sinon.mock().returns(Promise.resolve())

        return LoginConsentRequest.obtainConsent(request)
          .then(() => {
            expect(request.saveConsentForClient).to.have.been.called()
          })
      })

      it('should set consent property on request', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        return LoginConsentRequest.obtainConsent(request)
          .then(opAuthRequest => {
            expect(opAuthRequest.consent).to.be.true()
          })
      })

      it('should set scope property on request', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        return LoginConsentRequest.obtainConsent(request)
          .then(opAuthRequest => {
            expect(opAuthRequest.scope).to.equal('openid')
          })
      })

      it('should not render any pages', () => {
        let render = sinon.stub(opAuthRequest.res, 'render')
        let request = LoginConsentRequest.from(opAuthRequest)

        return LoginConsentRequest.obtainConsent(request)
          .then(opAuthRequest => {
            expect(render).to.not.have.been.called()
          })
      })
    })

    describe('if body.consent param is NOT present', () => {
      let req, res, opAuthRequest

      beforeEach(() => {
        req = { body: { scope: 'openid' } }
        res = HttpMocks.createResponse()
        opAuthRequest = { req, res }
      })

      it('should check for previously saved consent', () => {
        let request = LoginConsentRequest.from(opAuthRequest)

        request.checkSavedConsentFor = sinon.mock()
          .returns(Promise.resolve(false))

        return LoginConsentRequest.obtainConsent(request)
          .then(() => {
            expect(request.checkSavedConsentFor).to.have.been.called()
          })
      })

      describe('if user consent has been previously saved', () => {
        it('should have marked the request as successful', () => {
          let request = LoginConsentRequest.from(opAuthRequest)

          request.checkSavedConsentFor = sinon.mock()
            .returns(Promise.resolve(true))

          return LoginConsentRequest.obtainConsent(request)
            .then(opAuthRequest => {
              expect(opAuthRequest.consent).to.be.true()
              expect(opAuthRequest.scope).to.equal('openid')
            })
        })

        it('should not have called renderConsentPage()', () => {

        })
      })

      describe('if user consent has NOT been previously saved', () => {
        it('should call renderConsentPage()', () => {
          let request = LoginConsentRequest.from(opAuthRequest)

          request.checkSavedConsentFor = sinon.mock()
            .returns(Promise.resolve(false))
          request.response.render = sinon.mock()

          let renderConsentPage = sinon.spy(request, 'renderConsentPage')

          return LoginConsentRequest.obtainConsent(request)
            .then(() => {
              expect(renderConsentPage).to.have.been.called()
            })
        })

        it('should not have marked success', () => {
          let request = LoginConsentRequest.from(opAuthRequest)

          request.checkSavedConsentFor = sinon.mock()
            .returns(Promise.resolve(false))
          request.response.render = sinon.mock()

          return LoginConsentRequest.obtainConsent(request)
            .then(opAuthRequest => {
              expect(opAuthRequest.consent).to.not.exist()
              expect(opAuthRequest.scope).to.not.exist()
            })
        })
      })
    })
  })

  describe('renderConsentPage()', () => {
    it('should call res.render', () => {
      let req = { body: {} }
      let res = HttpMocks.createResponse()

      let render = sinon.stub(res, 'render')

      let opAuthRequest = { req, res }
      let request = LoginConsentRequest.from(opAuthRequest)

      return LoginConsentRequest.obtainConsent(request)
        .then(() => {
          expect(render).to.have.been.calledWith('auth/consent')
        })
    })

    it('should set the headerSent property on opAuthRequest', () => {
      let req = { body: {} }
      let res = HttpMocks.createResponse()

      sinon.stub(res, 'render')

      let opAuthRequest = { req, res }
      let request = LoginConsentRequest.from(opAuthRequest)

      request.checkSavedConsentFor = sinon.mock()
        .returns(Promise.resolve(false))

      return LoginConsentRequest.obtainConsent(request)
        .then(opAuthRequest => {
          expect(opAuthRequest.headersSent).to.be.true()
        })
    })
  })
})
<|endoftext|>


<commit_before>var assert     = require('assert');
var packets    = require('../../../lib/packets/index.js');

var buf = new Buffer('0a000004000007dd070116010203', 'hex');

var packet = new packets.Packet(4, buf, 0, buf.length);
var i = packet.readInt16();
var d = packet.readDateTime();

assert.equal(+d, 1358776923000);
assert.equal(packet.offset, packet.end);

buf = new Buffer('18000006000004666f6f310be00702090f01095d7f06000462617231', 'hex');
packet = new packets.Packet(6, buf, 0, buf.length);

i = packet.readInt16();
var s = packet.readLengthCodedString();
assert.equal(s, 'foo1');
d = packet.readDateTime();
assert.equal(+d, 1454990894821);

var s1 = packet.readLengthCodedString();
assert.equal(s1, 'bar1');
assert.equal(packet.offset, packet.end);
<commit_msg>adjust assertion to zero TZ offset<commit_after>var assert     = require('assert');
var packets    = require('../../../lib/packets/index.js');

var buf = new Buffer('0a000004000007dd070116010203', 'hex');

var packet = new packets.Packet(4, buf, 0, buf.length);
var i = packet.readInt16();
var d = packet.readDateTime();

assert.equal(+d, 1358816523000);

buf = new Buffer('18000006000004666f6f310be00702090f01095d7f06000462617231', 'hex');
packet = new packets.Packet(6, buf, 0, buf.length);

i = packet.readInt16();
var s = packet.readLengthCodedString();
assert.equal(s, 'foo1');
d = packet.readDateTime();
assert.equal(+d, 1455030494821);

var s1 = packet.readLengthCodedString();
assert.equal(s1, 'bar1');
assert.equal(packet.offset, packet.end);
<|endoftext|>


<commit_before>const chai = require('chai')
chai.use(require('chai-as-promised'))
const expect = chai.expect
const readConfigStream = require('../../lib/readConfigStream')
const options = require('../../lib/options');
const Readable = require('stream').Readable

function generateStreamFromYaml (yaml) {
  const stream = new Readable()
  stream.push(yaml)
  stream.push(null)
  return stream
}
function generateStream (url, ctfKey, insertHints, insertHintUrls) {
  const yaml = `
juiceShopUrl: ${url}
ctfKey: ${ctfKey}
insertHints: ${insertHints}
insertHintUrls: ${insertHintUrls}
`
  return generateStreamFromYaml(yaml)
}

describe('Read config stream', () => {
  it('should reject with an error when using an unparsable yaml', () => {
    const stream = generateStreamFromYaml(`
juiceShopUrl: http://thejuiceshopurl.com
ctfK`)

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 2, 2} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, paid, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'paid', 'paid')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.paidTextHints,
      insertHintUrls: options.paidHintUrls
    })
  })

  it('should resolve with {127.0.0.1, theCtfKey, 2, 2} when using a yaml containing 127.0.0.1, theCtfKey, paid, paid', () => {
    const stream = generateStream('127.0.0.1', 'theCtfKey', 'paid', 'paid')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: '127.0.0.1',
      ctfKey: 'theCtfKey',
      insertHints: options.paidTextHints,
      insertHintUrls: options.paidHintUrls
    })
  })

  it('should reject with an error when using a yaml containing notAUriNorAnIpValue, theCtfKey, paid, paid', () => {
    const stream = generateStream('notAUriNorAnIpValue', 'theCtfKey', 'paid', 'paid')

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })

  it('should reject with an error when using a yaml containing http://thejuiceshopurl.com\', 0, paid, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 0, 'paid', 'paid')

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 0, 2} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, none, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'none', 'paid')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.noTextHints,
      insertHintUrls: options.paidHintUrls
    })
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 1, 2} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, free, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'free', 'paid')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.freeTextHints,
      insertHintUrls: options.paidHintUrls
    })
  })

  it('should reject with an error when using a yaml containing http://thejuiceshopurl.com, theCtfKey, invalidValue, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'invalidValue', 'paid')

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 2, 0} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, none, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'paid', 'none')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.paidTextHints,
      insertHintUrls: options.noHintUrls
    })
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 2, 1} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, free, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'paid', 'free')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.paidTextHints,
      insertHintUrls: options.freeHintUrls
    })
  })

  it('should reject with an error when using a yaml containing http://thejuiceshopurl.com, theCtfKey, paid, invalidValue', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'paid', 'invalidValue')

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })
})
<commit_msg>linting<commit_after>const chai = require('chai')
chai.use(require('chai-as-promised'))
const expect = chai.expect
const readConfigStream = require('../../lib/readConfigStream')
const options = require('../../lib/options')
const Readable = require('stream').Readable

function generateStreamFromYaml (yaml) {
  const stream = new Readable()
  stream.push(yaml)
  stream.push(null)
  return stream
}
function generateStream (url, ctfKey, insertHints, insertHintUrls) {
  const yaml = `
juiceShopUrl: ${url}
ctfKey: ${ctfKey}
insertHints: ${insertHints}
insertHintUrls: ${insertHintUrls}
`
  return generateStreamFromYaml(yaml)
}

describe('Read config stream', () => {
  it('should reject with an error when using an unparsable yaml', () => {
    const stream = generateStreamFromYaml(`
juiceShopUrl: http://thejuiceshopurl.com
ctfK`)

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 2, 2} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, paid, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'paid', 'paid')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.paidTextHints,
      insertHintUrls: options.paidHintUrls
    })
  })

  it('should resolve with {127.0.0.1, theCtfKey, 2, 2} when using a yaml containing 127.0.0.1, theCtfKey, paid, paid', () => {
    const stream = generateStream('127.0.0.1', 'theCtfKey', 'paid', 'paid')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: '127.0.0.1',
      ctfKey: 'theCtfKey',
      insertHints: options.paidTextHints,
      insertHintUrls: options.paidHintUrls
    })
  })

  it('should reject with an error when using a yaml containing notAUriNorAnIpValue, theCtfKey, paid, paid', () => {
    const stream = generateStream('notAUriNorAnIpValue', 'theCtfKey', 'paid', 'paid')

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })

  it('should reject with an error when using a yaml containing http://thejuiceshopurl.com\', 0, paid, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 0, 'paid', 'paid')

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 0, 2} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, none, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'none', 'paid')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.noTextHints,
      insertHintUrls: options.paidHintUrls
    })
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 1, 2} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, free, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'free', 'paid')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.freeTextHints,
      insertHintUrls: options.paidHintUrls
    })
  })

  it('should reject with an error when using a yaml containing http://thejuiceshopurl.com, theCtfKey, invalidValue, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'invalidValue', 'paid')

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 2, 0} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, none, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'paid', 'none')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.paidTextHints,
      insertHintUrls: options.noHintUrls
    })
  })

  it('should resolve with {http://thejuiceshopurl.com, theCtfKey, 2, 1} when using a yaml containing http://thejuiceshopurl.com, theCtfKey, free, paid', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'paid', 'free')

    expect(readConfigStream(stream)).to.eventually.deep.equal({
      juiceShopUrl: 'http://thejuiceshopurl.com',
      ctfKey: 'theCtfKey',
      insertHints: options.paidTextHints,
      insertHintUrls: options.freeHintUrls
    })
  })

  it('should reject with an error when using a yaml containing http://thejuiceshopurl.com, theCtfKey, paid, invalidValue', () => {
    const stream = generateStream('http://thejuiceshopurl.com', 'theCtfKey', 'paid', 'invalidValue')

    expect(readConfigStream(stream)).to.be.rejectedWith(Error)
  })
})
<|endoftext|>


<commit_before>'use strict';

const should = require('should'),
      sinon = require('sinon'),
      proxyquire = require('proxyquire');

describe('Resource Factory', () => {
  const DefinitionDouble = {
          foo: {
            instance: [
              'ping'
            ],
            statics: [
              'pong'
            ]
          },
          bar: {
            instance: [
              'ping'
            ],
            statics: [
              'pong'
            ]
          },
          singleton: {
            statics: [
              'pong'
            ]
          }
        },
        factoryDouble = {
          staticFactory: sinon.stub(),
          instanceFactory: sinon.stub()
        };

  const factory = proxyquire('../../../lib/resource/factory', {
    './definition': DefinitionDouble,
    '../sdk/factory': factoryDouble
  });

  let memoizeId = 0;

  beforeEach(() => {
    factoryDouble.staticFactory.reset();
    factoryDouble.instanceFactory.reset();
  });

  describe('function', () => {
    it('throws if there is no defintion', () => {
      const resource = 'undef',
            request = sinon.spy();

      (function () {
        factory(resource, request);
      }).should.throw(/Could not find definition for resource: undef./);
    });

    it('returns a non constructable object when resource is defined as a singleton', () => {
      const resource = 'singleton',
            request = sinon.spy();

      factoryDouble.staticFactory.returns([]);
      factoryDouble.instanceFactory.returns([]);

      const result = factory(resource, request);

      (function () {
        new result();
      }).should.throw('result is not a constructor');
    });

    it('memoizes between calls based on resource and request', () => {
      const resourceOne = 'foo',
            resourceTwo = 'bar',
            request = sinon.spy();

      factoryDouble.staticFactory.returns([]);
      factoryDouble.instanceFactory.returns([]);

      const firstResult = factory(resourceOne, request),
            secondResult = factory(resourceTwo, request),
            thirdResult = factory(resourceOne, request);

      // we should not be regenerating.
      factoryDouble.staticFactory.callCount.should.eql(2);
      factoryDouble.instanceFactory.callCount.should.eql(2);
    });

    it('adds static methods to resource', () => {
      const resource = 'foo',
            options = sinon.spy(),
            request = sinon.spy();

      factoryDouble.staticFactory.
        withArgs(request, resource, DefinitionDouble.foo.statics, options).
        returns({
          'ping': 'pong'
        });

      factoryDouble.instanceFactory.returns([]);

      const result = factory(resource, request, options, memoizeId++);

      result.should.have.property('ping');
      result.ping.should.eql('pong');
    });

    it('adds instance methods to prototype', () => {
      const resource = 'foo',
            options = sinon.spy(),
            request = sinon.spy();

      factoryDouble.staticFactory.returns([]);

      factoryDouble.instanceFactory.
        withArgs(request, resource, DefinitionDouble.foo.instance).
        returns({
          'ping': 'pong'
        });

      const Result = factory(resource, request, options, memoizeId++);

      const instance = new Result();

      Result.should.not.have.property('ping');
      instance.should.have.property('ping');
      instance.ping.should.eql('pong');
    });
  });

  describe('addMethod', () => {
    const { addMethod } = factory;

    it('attaches the method to the prototype with the given name', () => {
      const Resource = {
              prototype: {}
            },
            method = sinon.stub(),
            name = 'alpha';

      addMethod(Resource, method, name);

      Resource.prototype.alpha.should.eql(method);
    });

    it('returns the Resource', () => {
      const Resource = {
              prototype: {}
            },
            method = sinon.stub(),
            name = 'alpha';

      const result = addMethod(Resource, method, name);

      result.should.eql(Resource);
    });
  });

  describe('addStatic', () => {
    const { addStatic } = factory;

    it('attaches method directly to object', () => {
      const Resource = {},
            method = sinon.stub(),
            name = 'alpha';

      addStatic(Resource, method, name);

      Resource.alpha.should.eql(method);
    });

    it('returns the Resource', () => {
      const Resource = {},
            method = sinon.stub(),
            name = 'alpha';

      const result = addStatic(Resource, method, name);

      result.should.eql(Resource);
    });
  });

  describe('addStatics', () => {
    const { addStatics } = factory;

    it('attaches a collection of statics to the object', () => {
      const Resource = {},
            statics = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      addStatics(Resource, statics);

      Resource.should.have.property('alpha');
      Resource.alpha.should.eql(statics.alpha);
      Resource.should.have.property('alpha');
      Resource.beta.should.eql(statics.beta);
    });

    it('returns the Resource', () => {
      const Resource = {},
            statics = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      const result = addStatics(Resource, statics);

      result.should.eql(Resource);
    });
  });

  describe('addMethods', () => {
    const { addMethods } = factory;

    it('attaches a collection of instance methods to the object', () => {
      const Resource = {
              prototype: {}
            },
            request = sinon.stub(),
            methods = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      addMethods(Resource, request, methods);

      Resource.should.have.propertyByPath('prototype', 'alpha');
      Resource.prototype.alpha.should.eql(methods.alpha);
      Resource.should.have.propertyByPath('prototype', 'beta');
      Resource.prototype.beta.should.eql(methods.beta);
    });

    it('attaches the request to the Resource prototype', () => {
      const Resource = {
              prototype: {}
            },
            request = sinon.stub(),
            methods = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      addMethods(Resource, request, methods);

      Resource.should.have.propertyByPath('prototype', '_request');
      Resource.prototype._request.should.eql(request);
    });

    it('returns the Resource', () => {
      const Resource = {
              prototype: {}
            },
            request = sinon.stub(),
            methods = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      const result = addMethods(Resource, request, methods);

      result.should.eql(Resource);
    });
  });

  describe('getMemoizeKey', () => {
    const { getMemoizeKey } = factory;

    it('returns the correct memoize complex key', () => {
      const resource = 'alpha',
            cid = 33;

      const result = getMemoizeKey(resource, undefined, undefined, cid);

      result.should.eql('alpha.33');
    });
  });

  describe('definesSingleton', () => {
    const { definesSingleton } = factory;

    it('returns true if instances is not defined', () => {
      const definition = {
              statics: ['alpha']
            };

      const result = definesSingleton(definition);

      result.should.eql(true);
    });

    it('returns true if instance is empty', () => {
      const definition = {
              statics: ['alpha'],
              instance: []
            };

      const result = definesSingleton(definition);

      result.should.eql(true);
    });

    it('returns false is instances is defined and has items', () => {
      const definition = {
              statics: ['alpha'],
              instance: ['bar']
            };

      const result = definesSingleton(definition);

      result.should.eql(false);
    });
  });

  describe('createResource', () => {
    const { createResource } = factory;

    it('returns a function that is newable', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      (function () {
        new Resource();
      }).should.not.throw();
    });

    it('sets the passed resource name on the instance', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource();

      instance.resource.should.eql(resource);
    });

    it('assigns passed data onto the object', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({ ding: 'dong' });

      instance.ding.should.eql('dong');
    });

    it('sets .isNew to true', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({});

      instance.should.have.property('isNew');
      instance.isNew.should.eql(true);
    });

    it('defaults .eid to null', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({});

      (instance.eid === null).should.eql(true);
    });

    it('sets .eid if passed in attributes', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({ eid: 'lala' });

      instance.eid.should.eql('lala');
    });

    it('assigns attributes to _attributes', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({ ding: 'dong' });

      instance.should.have.property('_attributes');
      instance._attributes.should.eql({
        ding: 'dong'
      });
    });

    it('will not assign reserved keywords', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({
        meta: 'alpha',
        relationships: 'alpha'
      });

      if ('meta' in instance) {
        instance.meta.should.not.eql('alpha');
      }

      if ('relationships' in instance) {
        instance.relationships.should.not.eql('alpha');
      }
    });
  });
});
<commit_msg>add empty methods test<commit_after>'use strict';

const should = require('should'),
      sinon = require('sinon'),
      proxyquire = require('proxyquire');

describe('Resource Factory', () => {
  const DefinitionDouble = {
          foo: {
            instance: [
              'ping'
            ],
            statics: [
              'pong'
            ]
          },
          bar: {
            instance: [
              'ping'
            ],
            statics: [
              'pong'
            ]
          },
          singleton: {
            statics: [
              'pong'
            ]
          }
        },
        factoryDouble = {
          staticFactory: sinon.stub(),
          instanceFactory: sinon.stub()
        };

  const factory = proxyquire('../../../lib/resource/factory', {
    './definition': DefinitionDouble,
    '../sdk/factory': factoryDouble
  });

  let memoizeId = 0;

  beforeEach(() => {
    factoryDouble.staticFactory.reset();
    factoryDouble.instanceFactory.reset();
  });

  describe('function', () => {
    it('throws if there is no defintion', () => {
      const resource = 'undef',
            request = sinon.spy();

      (function () {
        factory(resource, request);
      }).should.throw(/Could not find definition for resource: undef./);
    });

    it('returns a non constructable object when resource is defined as a singleton', () => {
      const resource = 'singleton',
            request = sinon.spy();

      factoryDouble.staticFactory.returns([]);
      factoryDouble.instanceFactory.returns([]);

      const result = factory(resource, request);

      (function () {
        new result();
      }).should.throw('result is not a constructor');
    });

    it('memoizes between calls based on resource and request', () => {
      const resourceOne = 'foo',
            resourceTwo = 'bar',
            request = sinon.spy();

      factoryDouble.staticFactory.returns([]);
      factoryDouble.instanceFactory.returns([]);

      const firstResult = factory(resourceOne, request),
            secondResult = factory(resourceTwo, request),
            thirdResult = factory(resourceOne, request);

      // we should not be regenerating.
      factoryDouble.staticFactory.callCount.should.eql(2);
      factoryDouble.instanceFactory.callCount.should.eql(2);
    });

    it('adds static methods to resource', () => {
      const resource = 'foo',
            options = sinon.spy(),
            request = sinon.spy();

      factoryDouble.staticFactory.
        withArgs(request, resource, DefinitionDouble.foo.statics, options).
        returns({
          'ping': 'pong'
        });

      factoryDouble.instanceFactory.returns([]);

      const result = factory(resource, request, options, memoizeId++);

      result.should.have.property('ping');
      result.ping.should.eql('pong');
    });

    it('adds instance methods to prototype', () => {
      const resource = 'foo',
            options = sinon.spy(),
            request = sinon.spy();

      factoryDouble.staticFactory.returns([]);

      factoryDouble.instanceFactory.
        withArgs(request, resource, DefinitionDouble.foo.instance).
        returns({
          'ping': 'pong'
        });

      const Result = factory(resource, request, options, memoizeId++);

      const instance = new Result();

      Result.should.not.have.property('ping');
      instance.should.have.property('ping');
      instance.ping.should.eql('pong');
    });
  });

  describe('addMethod', () => {
    const { addMethod } = factory;

    it('attaches the method to the prototype with the given name', () => {
      const Resource = {
              prototype: {}
            },
            method = sinon.stub(),
            name = 'alpha';

      addMethod(Resource, method, name);

      Resource.prototype.alpha.should.eql(method);
    });

    it('returns the Resource', () => {
      const Resource = {
              prototype: {}
            },
            method = sinon.stub(),
            name = 'alpha';

      const result = addMethod(Resource, method, name);

      result.should.eql(Resource);
    });
  });

  describe('addStatic', () => {
    const { addStatic } = factory;

    it('attaches method directly to object', () => {
      const Resource = {},
            method = sinon.stub(),
            name = 'alpha';

      addStatic(Resource, method, name);

      Resource.alpha.should.eql(method);
    });

    it('returns the Resource', () => {
      const Resource = {},
            method = sinon.stub(),
            name = 'alpha';

      const result = addStatic(Resource, method, name);

      result.should.eql(Resource);
    });
  });

  describe('addStatics', () => {
    const { addStatics } = factory;

    it('attaches a collection of statics to the object', () => {
      const Resource = {},
            statics = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      addStatics(Resource, statics);

      Resource.should.have.property('alpha');
      Resource.alpha.should.eql(statics.alpha);
      Resource.should.have.property('alpha');
      Resource.beta.should.eql(statics.beta);
    });

    it('returns the Resource', () => {
      const Resource = {},
            statics = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      const result = addStatics(Resource, statics);

      result.should.eql(Resource);
    });
  });

  describe('addMethods', () => {
    const { addMethods } = factory;

    it('returns the Resource if methods are empty and does not throw', () => {
      const Resource = {}, // no prototype
            request = sinon.stub(),
            methods = {};

      (function () {
        const result = addMethods(Resource, request, methods);

        result.should.eql(Resource);
      }).should.not.throw();
    });

    it('attaches a collection of instance methods to the object', () => {
      const Resource = {
              prototype: {}
            },
            request = sinon.stub(),
            methods = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      addMethods(Resource, request, methods);

      Resource.should.have.propertyByPath('prototype', 'alpha');
      Resource.prototype.alpha.should.eql(methods.alpha);
      Resource.should.have.propertyByPath('prototype', 'beta');
      Resource.prototype.beta.should.eql(methods.beta);
    });

    it('attaches the request to the Resource prototype', () => {
      const Resource = {
              prototype: {}
            },
            request = sinon.stub(),
            methods = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      addMethods(Resource, request, methods);

      Resource.should.have.propertyByPath('prototype', '_request');
      Resource.prototype._request.should.eql(request);
    });

    it('returns the Resource', () => {
      const Resource = {
              prototype: {}
            },
            request = sinon.stub(),
            methods = {
              alpha: sinon.stub(),
              beta: sinon.stub()
            };

      const result = addMethods(Resource, request, methods);

      result.should.eql(Resource);
    });
  });

  describe('getMemoizeKey', () => {
    const { getMemoizeKey } = factory;

    it('returns the correct memoize complex key', () => {
      const resource = 'alpha',
            cid = 33;

      const result = getMemoizeKey(resource, undefined, undefined, cid);

      result.should.eql('alpha.33');
    });
  });

  describe('definesSingleton', () => {
    const { definesSingleton } = factory;

    it('returns true if instances is not defined', () => {
      const definition = {
              statics: ['alpha']
            };

      const result = definesSingleton(definition);

      result.should.eql(true);
    });

    it('returns true if instance is empty', () => {
      const definition = {
              statics: ['alpha'],
              instance: []
            };

      const result = definesSingleton(definition);

      result.should.eql(true);
    });

    it('returns false is instances is defined and has items', () => {
      const definition = {
              statics: ['alpha'],
              instance: ['bar']
            };

      const result = definesSingleton(definition);

      result.should.eql(false);
    });
  });

  describe('createResource', () => {
    const { createResource } = factory;

    it('returns a function that is newable', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      (function () {
        new Resource();
      }).should.not.throw();
    });

    it('sets the passed resource name on the instance', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource();

      instance.resource.should.eql(resource);
    });

    it('assigns passed data onto the object', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({ ding: 'dong' });

      instance.ding.should.eql('dong');
    });

    it('sets .isNew to true', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({});

      instance.should.have.property('isNew');
      instance.isNew.should.eql(true);
    });

    it('defaults .eid to null', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({});

      (instance.eid === null).should.eql(true);
    });

    it('sets .eid if passed in attributes', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({ eid: 'lala' });

      instance.eid.should.eql('lala');
    });

    it('assigns attributes to _attributes', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({ ding: 'dong' });

      instance.should.have.property('_attributes');
      instance._attributes.should.eql({
        ding: 'dong'
      });
    });

    it('will not assign reserved keywords', () => {
      const resource = 'foo',
            Resource = createResource(resource);

      const instance = new Resource({
        meta: 'alpha',
        relationships: 'alpha'
      });

      if ('meta' in instance) {
        instance.meta.should.not.eql('alpha');
      }

      if ('relationships' in instance) {
        instance.relationships.should.not.eql('alpha');
      }
    });
  });
});
<|endoftext|>


<commit_before>
var test = require('tape')
require('rewire-global').enable()
const sinon = require('sinon')
const proxyquire = require('proxyquire').noCallThru()
const Promise = require('bluebird') // enable Promise.finally()

require('kth-node-log').init({
  level: 'error',
  console: {
    enabled: true
  }})

const readMessageFromQueueStub = sinon.stub().returns(Promise.resolve())
const deleteMessageFromQueue = sinon.stub().returns(Promise.resolve())

const queue = sinon.stub().returns({
  readMessageFromQueue: readMessageFromQueueStub,
  deleteMessageFromQueue
})

const consumeMessages = proxyquire('../../../messages/consumeMessages', {
  'node-queue-adapter': queue,
  './handleMessage': sinon.stub().returns(Promise.resolve())
})

function reset () {
  readMessageFromQueueStub.reset()
  deleteMessageFromQueue.reset()
}

function readMessageUnlessReading(){
  consumeMessages.__get__('readMessageUnlessReading')()
}

test('if it is already reading, then it should just return ', t=>{
  t.plan(1)
  readMessage = sinon.stub()
  consumeMessages.__set__('readMessage', readMessage)
  consumeMessages.__set__('isReading', true)

  readMessageUnlessReading()
  t.equal(readMessage.called,false)
})

test('if it is not already reading, then it should just call readMessage ', t=>{
  t.plan(1)
  readMessage = sinon.stub()
  consumeMessages.__set__('readMessage', readMessage)
  consumeMessages.__set__('isReading', false)

  readMessageUnlessReading()
  t.equal(readMessage.called,true)
})

test.skip('no message from azure should abort promise chain',t =>{
  t.plan(1)
  consumeMessages.__set__('isReading', false)
  const parseBody = sinon.stub()
  consumeMessages.__set__('parseBody', parseBody)
  consumeMessages.readMessage().then(msg =>{
      t.equal(parseBody.called, false)
  })
})

// test('read message without body should call read message again', t => {})
//
// test('read message without message should call read message again', t => {})
//
// test('read message with incorrect body should call read message again', t => {})
//
// test('read message with correct body should call read message again', t => {})
<commit_msg>two passing tests<commit_after>
var test = require('tape')
require('rewire-global').enable()
const sinon = require('sinon')
const proxyquire = require('proxyquire').noCallThru()
const Promise = require('bluebird') // enable Promise.finally()

require('kth-node-log').init({
  level: 'error',
  console: {
    enabled: true
  }})

const readMessageFromQueueStub = sinon.stub().returns(Promise.resolve())
const deleteMessageFromQueue = sinon.stub().returns(Promise.resolve())

const queue = sinon.stub().returns({
  readMessageFromQueue: readMessageFromQueueStub,
  deleteMessageFromQueue
})

const consumeMessages = proxyquire('../../../messages/consumeMessages', {
  'node-queue-adapter': queue,
  './handleMessage': sinon.stub().returns(Promise.resolve())
})

function reset () {
  readMessageFromQueueStub.reset()
  deleteMessageFromQueue.reset()
}

function readMessageUnlessReading(){
  consumeMessages.__get__('readMessageUnlessReading')()
}

test('if it is already reading, then it should just return ', t=>{
  t.plan(1)
  readMessage = sinon.stub()
  consumeMessages.__set__('readMessage', readMessage)
  consumeMessages.__set__('isReading', true)

  readMessageUnlessReading()
  t.equal(readMessage.called,false)
})

test('if it is not already reading, then it should just call readMessage ', t=>{
  t.plan(1)
  readMessage = sinon.stub()
  consumeMessages.__set__('readMessage', readMessage)
  consumeMessages.__set__('isReading', false)

  readMessageUnlessReading()
  t.equal(readMessage.called,true)
})

// test.skip('no message from azure should abort promise chain',t =>{
//   t.plan(1)
//   consumeMessages.__set__('isReading', false)
//   const parseBody = sinon.stub()
//   consumeMessages.__set__('parseBody', parseBody)
//   consumeMessages.readMessage().then(msg =>{
//       t.equal(parseBody.called, false)
//   })
})

// test('read message without body should call read message again', t => {})
//
// test('read message without message should call read message again', t => {})
//
// test('read message with incorrect body should call read message again', t => {})
//
// test('read message with correct body should call read message again', t => {})
<|endoftext|>