<commit_before>var base_path = '../../../..';
var services_path = base_path + '/services';
var models = require(base_path + '/models/models');
var java = require('java');
java.classpath.push(base_path +'/java_lib/Triplet_Extraction.jar');
var Nlp_Parser = require(services_path + '/parsers/nlp_parser_async.js');
var alpha_report_service = require(services_path + '/database/alpha_report.js');
var Assertion_Service = require(services_path + '/database/assertion.js');
var config = require(base_path + '/config.js');

var winston = require('winston');
var logger = new (winston.Logger)({
	transports: [new (winston.transports.Console)({level:config.log_level}),
		new (winston.transports.File)({filename: base_path + '/logs/jasmine_testing.log'})]
});
var assertionService = new Assertion_Service(models, null, logger);
var nlpParser = new Nlp_Parser({assertionService: assertionService}, logger);

describe('To verify the the nlp parsers ', function() {
	it('ability to run', function(){
		var ar_object = {
			"_id":"51f80c293cc187ca150000d1",
			"reporter_id":"51f80c293cc187ca150000d0",
			"source_name":"Twitter",
			"source_id":"5",
			"message_body":"A rare black squirrel has become a regular visitor to a suburban garden. A rare black squirrel has become a regular visitor to a suburban garden."
		};

		spyOn(logger, 'info').andCallThrough();
		var assert = spyOn(assertionService, 'saveAssertion').andCallThrough();

		nlpParser.parseAndSave(ar_object);

		expect(logger.info).toHaveBeenCalled();
		expect(assert).toHaveBeenCalled();
		expect(assert.callCount).toEqual(2);
	});

	it('ability to not call save when message_body won\'t yield a triplet', function(){
		var ar_object = {
			"_id":"51f80c293cc187ca150000d1",
			"reporter_id":"51f80c293cc187ca150000d0",
			"source_name":"Twitter",
			"source_id":"5",
			"message_body":"Hi"
		};

		spyOn(assertionService, 'saveAssertion').andCallThrough();

		nlpParser.parseAndSave(ar_object);

		expect(assertionService.saveAssertion).not.toHaveBeenCalled();
	});

});

describe('To check the functionality of the individual java calls coming in through node-java ', function(){

	it('checking the parser ', function(){
		var Parser = java.import('com.nextcentury.TripletExtraction.CoreNlpParser');
		var parser = new Parser();

		var tree = parser.parseSync("I never went to school when I was a kid");
		expect(tree.sizeSync()).toEqual(1);
	});

	it('checking the extraction service', function(){
		var Parser = java.import('com.nextcentury.TripletExtraction.CoreNlpParser');
		var parser = new Parser();
		var ExtractionService = java.import('com.nextcentury.TripletExtraction.ExtractionService');
		var extractor = new ExtractionService();

		var tree = parser.parseSync("A rare black squirrel has become a regular visitor to a suburban garden");
		var leaf = tree.getSync(0);

		var output = extractor.extractTripletSync(leaf);

		expect(output.getEntity1StringSync()).toEqual('squirrel');
		expect(output.getRelationStringSync()).toEqual('become');
		expect(output.getEntity2StringSync()).toEqual('visitor');
	});
});<commit_msg>Fixed the npl test spec to work with how the npl_parser module is defined.  All tests currently passing.<commit_after>var base_path = '../../../..';
var services_path = base_path + '/services';
var models = require(base_path + '/models/models');
var java = require('java');
java.classpath.push(base_path +'/java_lib/Triplet_Extraction.jar');
var Nlp_Parser = require(services_path + '/parsers/nlp_parser_async.js');
var alpha_report_service = require(services_path + '/database/alpha_report.js');
var Assertion_Service = require(services_path + '/database/assertion.js');
var config = require(base_path + '/config.js');

var winston = require('winston');
var logger = new (winston.Logger)({
	transports: [new (winston.transports.Console)({level:config.log_level}),
		new (winston.transports.File)({filename: base_path + '/logs/jasmine_testing.log'})]
});
var assertionService = new Assertion_Service(models, null, logger);
var nlpParser = new Nlp_Parser({assertionService: assertionService}, logger);

describe('To verify the the nlp parsers ', function() {
	it('ability to run', function(){
		var ar_object = {
			"_id":"51f80c293cc187ca150000d1",
			"reporter_id":"51f80c293cc187ca150000d0",
			"source_name":"Twitter",
			"source_id":"5",
			"message_body":"A rare black squirrel has become a regular visitor to a suburban garden. A rare black squirrel has become a regular visitor to a suburban garden."
		};

		spyOn(logger, 'info').andCallThrough();
		var assert = spyOn(assertionService, 'saveAssertion').andCallThrough();

		nlpParser.parseAndSave(ar_object);
		waits(1000);
		runs(function () {
			expect(logger.info).toHaveBeenCalled();
			expect(assert).toHaveBeenCalled();
			expect(assert.callCount).toEqual(2);
		});
	});

	it('ability to not call save when message_body won\'t yield a triplet', function(){
		var ar_object = {
			"_id":"51f80c293cc187ca150000d1",
			"reporter_id":"51f80c293cc187ca150000d0",
			"source_name":"Twitter",
			"source_id":"5",
			"message_body":"Hi"
		};

		spyOn(assertionService, 'saveAssertion').andCallThrough();

		nlpParser.parseAndSave(ar_object);

		expect(assertionService.saveAssertion).not.toHaveBeenCalled();
	});

});

describe('To check the functionality of the individual java calls coming in through node-java ', function(){

	it('checking the parser ', function(){
		var Parser = java.import('com.nextcentury.TripletExtraction.CoreNlpParser');
		var parser = new Parser();

		var tree = parser.parseSync("I never went to school when I was a kid");
		expect(tree.sizeSync()).toEqual(1);
	});

	it('checking the extraction service', function(){
		var Parser = java.import('com.nextcentury.TripletExtraction.CoreNlpParser');
		var parser = new Parser();
		var ExtractionService = java.import('com.nextcentury.TripletExtraction.ExtractionService');
		var extractor = new ExtractionService();

		var tree = parser.parseSync("A rare black squirrel has become a regular visitor to a suburban garden");
		var leaf = tree.getSync(0);

		var output = extractor.extractTripletSync(leaf);

		expect(output.getEntity1StringSync()).toEqual('squirrel');
		expect(output.getRelationStringSync()).toEqual('become');
		expect(output.getEntity2StringSync()).toEqual('visitor');
	});
});<|endoftext|>


<commit_before>var test = require('tap').test
var path = require('path')
var fs = require('fs')
var rimraf = require('rimraf')
var common = require('../common-tap.js')
var Tacks = require('tacks')
var File = Tacks.File
var Dir = Tacks.Dir

var testdir = path.resolve(__dirname, path.basename(__filename, '.js'))
var cachedir = path.resolve(testdir, 'cache')
var config = ['--cache=' + cachedir, '--loglevel=error']

var shrinkwrap = {
  name: 'shrinkwrap-local-dependency',
  version: '1.0.0',
  dependencies: {
    mod2: {
      version: '1.0.0',
      from: 'mods/mod2',
      resolved: 'file:mods/mod2',
      dependencies: {
        mod1: {
          version: '1.0.0',
          from: 'mods/mod1',
          resolved: 'file:mods/mod1'
        }
      }
    }
  }
}

var fixture = new Tacks(
  Dir({
    cache: Dir(),
    mods: Dir({
      mod1: Dir({
        'package.json': File({
          name: 'mod1',
          version: '1.0.0'
        })
      }),
      mod2: Dir({
        'package.json': File({
          name: 'mod2',
          version: '1.0.0',
          dependencies: {
            mod1: 'file:../mod1'
          }
        })
      })
    }),
    'package.json': File({
      name: 'shrinkwrap-local-dependency',
      version: '1.0.0',
      dependencies: {
        mod2: 'file:mods/mod2'
      }
    })
  })
)

function setup () {
  cleanup()
  fixture.create(testdir)
}

function cleanNodeModules () {
  rimraf.sync(path.resolve(testdir, 'node_modules'))
}

function cleanup () {
  fixture.remove(testdir)
}

test('shrinkwrap uses resolved with file: on local deps', function (t) {
  setup()

  common.npm(config.concat(['install', '--legacy']), {cwd: testdir}, function (err, code, stdout, stderr) {
    if (err) throw err
    t.comment(stdout.trim())
    t.comment(stderr.trim())
    t.equal(code, 0, 'npm exited normally')

    common.npm(config.concat('shrinkwrap'), {cwd: testdir}, function (err, code, stdout, stderr) {
      if (err) throw err
      t.comment(stdout.trim())
      t.comment(stderr.trim())
      t.equal(code, 0, 'npm exited normally')
      var data = fs.readFileSync(path.join(testdir, 'npm-shrinkwrap.json'), { encoding: 'utf8' })
      t.deepEqual(JSON.parse(data), shrinkwrap, 'shrinkwrap looks correct')
      t.end()
    })
  })
})

function exists (file) {
  try {
    fs.statSync(file)
    return true
  } catch (ex) {
    return false
  }
}

test("'npm install' should install local packages from shrinkwrap", function (t) {
  cleanNodeModules()

  common.npm(config.concat(['install']), {cwd: testdir}, function (err, code, stdout, stderr) {
    if (err) throw err
    t.comment(stdout.trim())
    t.comment(stderr.trim())
    t.equal(code, 0, 'npm exited normally')
    t.ok(exists(path.join(testdir, 'node_modules', 'mod2')), 'mod2 exists')
    t.ok(exists(path.join(testdir, 'node_modules', 'mod2', 'node_modules', 'mod1')), 'mod1 exists')
    t.end()
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})

<commit_msg>test: fix Windows path issue for local shrinkwrap test<commit_after>var test = require('tap').test
var path = require('path')
var fs = require('fs')
var rimraf = require('rimraf')
var common = require('../common-tap.js')
var Tacks = require('tacks')
var File = Tacks.File
var Dir = Tacks.Dir

var testdir = path.resolve(__dirname, path.basename(__filename, '.js'))
var cachedir = path.resolve(testdir, 'cache')
var config = ['--cache=' + cachedir, '--loglevel=error']

var shrinkwrap = {
  name: 'shrinkwrap-local-dependency',
  version: '1.0.0',
  dependencies: {
    mod2: {
      version: '1.0.0',
      from: path.join('mods', 'mod2'),
      resolved: 'file:' + path.join('mods', 'mod2'),
      dependencies: {
        mod1: {
          version: '1.0.0',
          from: path.join('mods', 'mod1'),
          resolved: 'file:' + path.join('mods', 'mod1')
        }
      }
    }
  }
}

var fixture = new Tacks(
  Dir({
    cache: Dir(),
    mods: Dir({
      mod1: Dir({
        'package.json': File({
          name: 'mod1',
          version: '1.0.0'
        })
      }),
      mod2: Dir({
        'package.json': File({
          name: 'mod2',
          version: '1.0.0',
          dependencies: {
            mod1: 'file:' + path.join('..', 'mod1')
          }
        })
      })
    }),
    'package.json': File({
      name: 'shrinkwrap-local-dependency',
      version: '1.0.0',
      dependencies: {
        mod2: 'file:' + path.join('mods', 'mod2')
      }
    })
  })
)

function setup () {
  cleanup()
  fixture.create(testdir)
}

function cleanNodeModules () {
  rimraf.sync(path.resolve(testdir, 'node_modules'))
}

function cleanup () {
  fixture.remove(testdir)
}

test('shrinkwrap uses resolved with file: on local deps', function (t) {
  setup()

  common.npm(config.concat(['install', '--legacy']), {cwd: testdir}, function (err, code, stdout, stderr) {
    if (err) throw err
    t.comment(stdout.trim())
    t.comment(stderr.trim())
    t.equal(code, 0, 'npm exited normally')

    common.npm(config.concat('shrinkwrap'), {cwd: testdir}, function (err, code, stdout, stderr) {
      if (err) throw err
      t.comment(stdout.trim())
      t.comment(stderr.trim())
      t.equal(code, 0, 'npm exited normally')
      var data = fs.readFileSync(path.join(testdir, 'npm-shrinkwrap.json'), { encoding: 'utf8' })
      t.deepEqual(JSON.parse(data), shrinkwrap, 'shrinkwrap looks correct')
      t.end()
    })
  })
})

function exists (file) {
  try {
    fs.statSync(file)
    return true
  } catch (ex) {
    return false
  }
}

test("'npm install' should install local packages from shrinkwrap", function (t) {
  cleanNodeModules()

  common.npm(config.concat(['install']), {cwd: testdir}, function (err, code, stdout, stderr) {
    if (err) throw err
    t.comment(stdout.trim())
    t.comment(stderr.trim())
    t.equal(code, 0, 'npm exited normally')
    t.ok(exists(path.join(testdir, 'node_modules', 'mod2')), 'mod2 exists')
    t.ok(exists(path.join(testdir, 'node_modules', 'mod2', 'node_modules', 'mod1')), 'mod1 exists')
    t.end()
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})
<|endoftext|>


<commit_before>function exportBody(){
    if(!data)
        return null;

    var toc = table(data.chapters.map(function(chapter, i){
        return tr(td(chapter.name),
            td(a({href:"#chapter"+i}, "view")));
    }));

    toc.style.width = "100%";

    var chapters = data.chapters.map(function(chapter, i){
        return article(
            h2(a({name:"chapter" + i},
                chapter.name + " ",
                small(a({href:"#TOC"}, "(top)")))),
            chapter.doc
                .replace(/\r\n/g, "\n")
                .replace(/\n{2,}/g, "\n")
                .split(/\n/g).map(function(para){
                return p(para);
            }));
    });

    return [div({id:"table-of-contents"},
                h2(a({name:"TOC"}, "Table of Contents")),
                toc),
            div({id:"main"}, chapters)];
}

function exportHTML(){
    var doc = html(head(
            title("My Book"),
            meta({charset:"utf8"}),
            style("h2{page-break-before:always;}")),
        body(exportBody()));

    saveFileToDesktop("export.html", "text/html;charset=utf-8", doc.outerHTML);
    rptIt("publish");
}<commit_msg>better print styling<commit_after>function exportBody(){
    if(!data)
        return null;

    var toc = table(data.chapters.map(function(chapter, i){
        return tr(td(chapter.name),
            td(a({href:"#chapter"+i}, "view")));
    }));

    toc.style.width = "100%";

    var chapters = data.chapters.map(function(chapter, i){
        return article(
            h2(a({name:"chapter" + i},
                chapter.name + " ",
                small(a({href:"#TOC"}, "(top)")))),
            chapter.doc
                .replace(/\r\n/g, "\n")
                .replace(/\n{2,}/g, "\n")
                .split(/\n/g).map(function(para){
                return p(para);
            }));
    });

    return [div({id:"table-of-contents"},
                h2(a({name:"TOC"}, "Table of Contents")),
                toc),
            div({id:"main"}, chapters)];
}

function exportHTML(){
    var doc = html(head(
            title("My Book"),
            meta({charset:"utf8"}),
            style(
["@page {margin-top: 3cm;margin-bottom:3cm;}",
"@page :left {margin-left: 4cm; margin-right: 3cm;}",
"@page :left :header {content:\"pp. \" decimal(pageno), ,;}",
"@page :left :footer {content:\"pp. \" decimal(pageno), first(chapter),;}",
"@page :right {margin-left: 3cm;margin-right: 4cm;}",
"@page :right :header {content:, , \"pp. \" decimal(pageno);}",
"@page :right :footer {content:, first(chapter), \"pp. \" decimal(pageno);}",
"h2{page-break-before:always;running-head:chapter;}",
"p{text-align:justify}"].join("\n"))),
        body(exportBody()));

    saveFileToDesktop("export.html", "text/html;charset=utf-8", doc.outerHTML);
    rptIt("publish");
}<|endoftext|>


<commit_before>'use strict';

require('dotenv').config();
const test = require('ava');
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const logger = require('heroku-logger');
const rewire = require('rewire');

const stubs = require('../../../helpers/stubs');

// setup "x.should.y" assertion style
chai.should();
chai.use(sinonChai);

// module to be tested
const cacheHelper = rewire('../../../../lib/helpers/cache');

// stubs
const contentfulEntryId = stubs.getContentfulId();
const contentfulEntry = { id: contentfulEntryId };
const rivescriptCacheId = 'contentApi';
const rivescript = '+ hello\n- hi';

const sandbox = sinon.sandbox.create();

test.beforeEach(() => {
  stubs.stubLogger(sandbox, logger);
});

test.afterEach(() => {
  sandbox.restore();
  cacheHelper.__set__('broadcastsCache', undefined);
  cacheHelper.__set__('rivescriptCache', undefined);
  cacheHelper.__set__('topicsCache', undefined);
});

/**
 * Broadcasts cache
 */
test('broadcasts.get should return object when cache exists', async () => {
  cacheHelper.__set__('broadcastsCache', {
    get: () => Promise.resolve(contentfulEntry),
  });
  const result = await cacheHelper.broadcasts.get(contentfulEntryId);
  result.should.deep.equal(contentfulEntry);
});

test('broadcasts.get should return falsy when cache undefined', async (t) => {
  cacheHelper.__set__('broadcastsCache', {
    get: () => Promise.resolve(null),
  });
  const result = await cacheHelper.broadcasts.get(contentfulEntryId);
  t.falsy(result);
});

test('broadcasts.get should throw when cache set fails', async (t) => {
  cacheHelper.__set__('broadcastsCache', {
    get: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.broadcasts.get(contentfulEntryId));
});

test('broadcasts.set should return an object', async () => {
  cacheHelper.__set__('broadcastsCache', {
    set: () => Promise.resolve(JSON.stringify(contentfulEntry)),
  });
  const result = await cacheHelper.broadcasts.set(contentfulEntryId);
  result.should.deep.equal(contentfulEntry);
});

/**
 * Rivescript cache
 */
test('rivescript.get should return object when cache exists', async () => {
  cacheHelper.__set__('rivescriptCache', {
    get: () => Promise.resolve(rivescript),
  });
  const result = await cacheHelper.rivescript.get(rivescriptCacheId);
  result.should.deep.equal(rivescript);
});

test('rivescript.get should return falsy when cache undefined', async (t) => {
  cacheHelper.__set__('rivescriptCache', {
    get: () => Promise.resolve(null),
  });
  const result = await cacheHelper.rivescript.get(rivescriptCacheId);
  t.falsy(result);
});

test('rivescript.get should throw when cache set fails', async (t) => {
  cacheHelper.__set__('rivescriptCache', {
    get: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.rivescript.get(rivescriptCacheId));
});

test('rivescript.set should return an object', async () => {
  cacheHelper.__set__('rivescriptCache', {
    set: () => Promise.resolve(JSON.stringify(rivescript)),
  });
  const result = await cacheHelper.rivescript.set(rivescriptCacheId);
  result.should.deep.equal(rivescript);
});

test('rivescript.set should throw when cache set fails', async (t) => {
  cacheHelper.__set__('rivescriptCache', {
    set: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.rivescript.set(rivescriptCacheId));
});

/**
 * Topics cache
 */
test('topics.get should return object when cache exists', async () => {
  cacheHelper.__set__('topicsCache', {
    get: () => Promise.resolve(contentfulEntry),
  });
  const result = await cacheHelper.topics.get(contentfulEntryId);
  result.should.deep.equal(contentfulEntry);
});

test('topics.get should return falsy when cache undefined', async (t) => {
  cacheHelper.__set__('topicsCache', {
    get: () => Promise.resolve(null),
  });
  const result = await cacheHelper.topics.get(contentfulEntryId);
  t.falsy(result);
});

test('topics.get should throw when cache set fails', async (t) => {
  cacheHelper.__set__('topicsCache', {
    get: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.topics.get(contentfulEntryId));
});

test('topics.set should return an object', async () => {
  cacheHelper.__set__('topicsCache', {
    set: () => Promise.resolve(JSON.stringify(contentfulEntry)),
  });
  const result = await cacheHelper.topics.set(contentfulEntryId);
  result.should.deep.equal(contentfulEntry);
});
<commit_msg>Adds tests for webSignupConfirmations cache<commit_after>'use strict';

require('dotenv').config();
const test = require('ava');
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const logger = require('heroku-logger');
const rewire = require('rewire');

const stubs = require('../../../helpers/stubs');

// setup "x.should.y" assertion style
chai.should();
chai.use(sinonChai);

// module to be tested
const cacheHelper = rewire('../../../../lib/helpers/cache');

// stubs
const contentfulEntryId = stubs.getContentfulId();
const contentfulEntry = { id: contentfulEntryId };
const rivescriptCacheId = 'contentApi';
const rivescript = '+ hello\n- hi';

const sandbox = sinon.sandbox.create();

test.beforeEach(() => {
  stubs.stubLogger(sandbox, logger);
});

test.afterEach(() => {
  sandbox.restore();
  cacheHelper.__set__('broadcastsCache', undefined);
  cacheHelper.__set__('rivescriptCache', undefined);
  cacheHelper.__set__('topicsCache', undefined);
  cacheHelper.__set__('webSignupConfirmationsCache', undefined);
});

/**
 * Broadcasts cache
 */
test('broadcasts.get should return object when cache exists', async () => {
  cacheHelper.__set__('broadcastsCache', {
    get: () => Promise.resolve(contentfulEntry),
  });
  const result = await cacheHelper.broadcasts.get(contentfulEntryId);
  result.should.deep.equal(contentfulEntry);
});

test('broadcasts.get should return falsy when cache undefined', async (t) => {
  cacheHelper.__set__('broadcastsCache', {
    get: () => Promise.resolve(null),
  });
  const result = await cacheHelper.broadcasts.get(contentfulEntryId);
  t.falsy(result);
});

test('broadcasts.get should throw when cache set fails', async (t) => {
  cacheHelper.__set__('broadcastsCache', {
    get: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.broadcasts.get(contentfulEntryId));
});

test('broadcasts.set should return an object', async () => {
  cacheHelper.__set__('broadcastsCache', {
    set: () => Promise.resolve(JSON.stringify(contentfulEntry)),
  });
  const result = await cacheHelper.broadcasts.set(contentfulEntryId);
  result.should.deep.equal(contentfulEntry);
});

/**
 * Rivescript cache
 */
test('rivescript.get should return object when cache exists', async () => {
  cacheHelper.__set__('rivescriptCache', {
    get: () => Promise.resolve(rivescript),
  });
  const result = await cacheHelper.rivescript.get(rivescriptCacheId);
  result.should.deep.equal(rivescript);
});

test('rivescript.get should return falsy when cache undefined', async (t) => {
  cacheHelper.__set__('rivescriptCache', {
    get: () => Promise.resolve(null),
  });
  const result = await cacheHelper.rivescript.get(rivescriptCacheId);
  t.falsy(result);
});

test('rivescript.get should throw when cache set fails', async (t) => {
  cacheHelper.__set__('rivescriptCache', {
    get: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.rivescript.get(rivescriptCacheId));
});

test('rivescript.set should return an object', async () => {
  cacheHelper.__set__('rivescriptCache', {
    set: () => Promise.resolve(JSON.stringify(rivescript)),
  });
  const result = await cacheHelper.rivescript.set(rivescriptCacheId);
  result.should.deep.equal(rivescript);
});

test('rivescript.set should throw when cache set fails', async (t) => {
  cacheHelper.__set__('rivescriptCache', {
    set: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.rivescript.set(rivescriptCacheId));
});

/**
 * Topics cache
 */
test('topics.get should return object when cache exists', async () => {
  cacheHelper.__set__('topicsCache', {
    get: () => Promise.resolve(contentfulEntry),
  });
  const result = await cacheHelper.topics.get(contentfulEntryId);
  result.should.deep.equal(contentfulEntry);
});

test('topics.get should return falsy when cache undefined', async (t) => {
  cacheHelper.__set__('topicsCache', {
    get: () => Promise.resolve(null),
  });
  const result = await cacheHelper.topics.get(contentfulEntryId);
  t.falsy(result);
});

test('topics.get should throw when cache set fails', async (t) => {
  cacheHelper.__set__('topicsCache', {
    get: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.topics.get(contentfulEntryId));
});

test('topics.set should return an object', async () => {
  cacheHelper.__set__('topicsCache', {
    set: () => Promise.resolve(JSON.stringify(contentfulEntry)),
  });
  const result = await cacheHelper.topics.set(contentfulEntryId);
  result.should.deep.equal(contentfulEntry);
});

/**
 * WebSignupConfirmations cache
 */
test('webSignupConfirmations.get should return object when cache exists', async () => {
  cacheHelper.__set__('webSignupConfirmationsCache', {
    get: () => Promise.resolve(contentfulEntry),
  });
  const result = await cacheHelper.webSignupConfirmations.get();
  result.should.deep.equal(contentfulEntry);
});

test('webSignupConfirmations.get should return falsy when cache undefined', async (t) => {
  cacheHelper.__set__('webSignupConfirmationsCache', {
    get: () => Promise.resolve(null),
  });
  const result = await cacheHelper.webSignupConfirmations.get();
  t.falsy(result);
});

test('webSignupConfirmations.get should throw when cache set fails', async (t) => {
  cacheHelper.__set__('webSignupConfirmationsCache', {
    get: () => Promise.reject(new Error()),
  });
  await t.throws(cacheHelper.webSignupConfirmations.get());
});

test('webSignupConfirmations.set should return an array', async () => {
  const data = [contentfulEntry];
  cacheHelper.__set__('webSignupConfirmationsCache', {
    set: () => Promise.resolve(JSON.stringify(data)),
  });
  const result = await cacheHelper.webSignupConfirmations.set(data);
  result.should.deep.equal(data);
});
<|endoftext|>


<commit_before>var root = require('root-path')
require(root('test/setup'))
var GetImageSize = require(root('api/services/GetImageSize'))

describe('GetImageSize', () => {
  it('gets the size', () => {
    return GetImageSize('https://www.hylo.com/favicon.png')
    .then(dimensions => {
      expect(dimensions.width).to.equal(32)
      expect(dimensions.height).to.equal(32)
    })
  })
})
<commit_msg>make a flaky test less flaky<commit_after>var root = require('root-path')
require(root('test/setup'))
var GetImageSize = require(root('api/services/GetImageSize'))

describe('GetImageSize', () => {
  it('gets the size', function () {
    this.timeout(5000)
    return GetImageSize('https://www.hylo.com/favicon.png')
    .then(dimensions => {
      expect(dimensions.width).to.equal(32)
      expect(dimensions.height).to.equal(32)
    })
  })
})
<|endoftext|>


<commit_before>/* eslint-env jest */

const TransformTrim = require('../../../lib/transforms/TransformTrim');
const TransformBase64Decode = require('../../../lib/transforms/TransformBase64Decode');
const TransformSplit = require('../../../lib/transforms/TransformSplit');
const TransformCombine = require('../../../lib/transforms/TransformCombine');
const TransformCompare = require('../../../lib/transforms/TransformCompare');
const TransformDecodeHtml = require('../../../lib/transforms/TransformDecodeHtml');
const TransformDecodeUri = require('../../../lib/transforms/TransformDecodeUri');
const TransformEncodeUri = require('../../../lib/transforms/TransformEncodeUri');
const TransformEqual = require('../../../lib/transforms/TransformEqual');
const TransformGet = require('../../../lib/transforms/TransformGet');
const TransformJoin = require('../../../lib/transforms/TransformJoin');
const TransformMatch = require('../../../lib/transforms/TransformMatch');
const TransformPick = require('../../../lib/transforms/TransformPick');
const TransformPluck = require('../../../lib/transforms/TransformPluck');
const TransformReplace = require('../../../lib/transforms/TransformReplace');
const Storage = require('../../../lib/Storage');

jest.mock('../../../lib/Storage');

describe('Transforms', () => {
  let transform;
  let storage;

  beforeAll(async () => {
    storage = new Storage({});
  });

  describe('TransformTrim', () => {
    test('perform with string', async () => {
      transform = new TransformTrim({
        value: '   test   ',
      });

      expect(transform.doTransform()).toEqual('test');
    });

    test('perform with non-string', async () => {
      transform = new TransformTrim({
        value: 12345,
      });

      expect(transform.doTransform()).toEqual(12345);
    });
  });

  describe('TransformBase64Decode', () => {
    test('perform', async () => {
      transform = new TransformBase64Decode({
        value: 'dGVzdA==',
      });

      expect(transform.doTransform()).toEqual('test');
    });
  });

  describe('TransformSplit', () => {
    test('perform with all default values', async () => {
      transform = new TransformSplit({
        value: '123,345,678',
      });

      expect(transform.doTransform()).toEqual('123');
    });

    test('perform with specified index', async () => {
      transform = new TransformSplit({
        value: '123,345,678',
        options: {
          index: 1,
        },
      });

      expect(transform.doTransform()).toEqual('345');
    });

    test('perform with wrong index', async () => {
      transform = new TransformSplit({
        value: '123,345,678',
        options: {
          index: 5,
        },
      });

      expect(transform.doTransform()).toEqual(null);
    });

    test('perform with specified separator', async () => {
      transform = new TransformSplit({
        value: '123:345:678',
        options: {
          separator: ':',
        },
      });

      expect(transform.doTransform()).toEqual('123');
    });

    test('perform with specified separator as regex', async () => {
      transform = new TransformSplit({
        value: '123:345:678',
        options: {
          separator: [':', 'ui'],
        },
      });

      expect(transform.doTransform()).toEqual('123');
    });

    test('perform with incorrect value', async () => {
      transform = new TransformSplit({
        value: ['123'],
      });

      expect(transform.doTransform()).toEqual('');
    });

    test('perform with specified dataType', async () => {
      transform = new TransformSplit({
        value: '123,345,678',
        options: {
          dataType: 'array',
        },
      });

      expect(transform.doTransform()).toEqual([
        '123',
        '345',
        '678',
      ]);
    });
  });

  describe('TransformCombine', () => {
    test('perform with default values', async () => {
      transform = new TransformCombine({});

      expect(transform.doTransform()).toEqual([]);
    });

    test('perform with data', async () => {
      const data = {
        'one': '1',
        'two': '2',
      };
      storage.get.mockClear();
      storage.get.mockImplementation((key) => data[key]);
      transform = new TransformCombine({
        options: {
          fields: [
            'one',
            'two',
          ],
        },
        storage,
      });

      expect(transform.doTransform()).toEqual(['1', '2']);

      expect(storage.get).toHaveBeenCalledTimes(2);
      expect(storage.get).toHaveBeenCalledWith('one');
      expect(storage.get).toHaveBeenCalledWith('two');
    });

    const checkCombineWithDataType = (dataType, result) => {
      const data = {
        'one': '1',
        'two': '2',
      };
      storage.get.mockClear();
      storage.get.mockImplementation((key) => data[key]);
      transform = new TransformCombine({
        options: {
          fields: [
            'one',
            'two',
          ],
          dataType,
        },
        storage,
      });

      expect(transform.doTransform()).toEqual(result);

      expect(storage.get).toHaveBeenCalledTimes(2);
      expect(storage.get).toHaveBeenCalledWith('one');
      expect(storage.get).toHaveBeenCalledWith('two');
    };

    test('perform with data and data dataType=int.integer', async () => {
      checkCombineWithDataType('int', [1, 2]);
      checkCombineWithDataType('integer', [1, 2]);
    });

    test('perform with data and data dataType=float,number,double', async () => {
      checkCombineWithDataType('float', [1.0, 2.0]);
      checkCombineWithDataType('double', [1.0, 2.0]);
      checkCombineWithDataType('number', [1.0, 2.0]);
    });
  });

  describe('TransformCompare', () => {
    test('perform with data returning true value', async () => {
      const data = {
        'one': '1',
      };
      storage.get.mockClear();
      storage.get.mockImplementation((key) => data[key]);
      transform = new TransformCompare({
        options: {
          field: 'one',
        },
        value: '1',
        storage,
      });

      expect(transform.doTransform()).toEqual(true);

      expect(storage.get).toHaveBeenCalledTimes(1);
      expect(storage.get).toHaveBeenCalledWith('one');
    });

    test('perform with data returning false value', async () => {
      const data = {
        'one': '1',
      };
      storage.get.mockClear();
      storage.get.mockImplementation((key) => data[key]);
      transform = new TransformCompare({
        options: {
          field: 'two',
        },
        value: '1',
        storage,
      });

      expect(transform.doTransform()).toEqual(false);

      expect(storage.get).toHaveBeenCalledTimes(1);
      expect(storage.get).toHaveBeenCalledWith('two');
    });
  });

  describe('TransformDecodeHtml', () => {
    test('perform', async () => {
      transform = new TransformDecodeHtml({
        value: '<>"&©®',
      });

      expect(transform.doTransform()).toEqual('<>"&©®');
    });
  });

  describe('TransformDecodeUri', () => {
    test('perform', async () => {
      transform = new TransformDecodeUri({
        value: 'https://www.google.com/?q=goose-parser%20is%20a%20library%20for%20parsing',
      });

      expect(transform.doTransform()).toEqual('https://www.google.com/?q=goose-parser is a library for parsing');
    });
  });

  describe('TransformEncodeUri', () => {
    test('perform', async () => {
      transform = new TransformEncodeUri({
        value: 'https://www.google.com/?q=goose-parser is a library for parsing',
      });

      expect(transform.doTransform()).toEqual('https://www.google.com/?q=goose-parser%20is%20a%20library%20for%20parsing');
    });
  });

  describe('TransformEqual', () => {
    test('perform with returning true', async () => {
      transform = new TransformEqual({
        value: 'one',
        options: {
          value: 'one',
        },
      });

      expect(transform.doTransform()).toEqual(true);
    });

    test('perform returning false', async () => {
      transform = new TransformEqual({
        value: 'one',
        options: {
          value: 'two',
        },
      });

      expect(transform.doTransform()).toEqual(false);
    });
  });

  describe('TransformGet', () => {
    test('perform', async () => {
      transform = new TransformGet({
        value: {
          one: {
            two: 'three',
          },
        },
        options: {
          path: 'one.two',
        },
      });

      expect(transform.doTransform()).toEqual('three');
    });

    test('perform wrong path without default', async () => {
      transform = new TransformGet({
        value: {
          one: {
            two: 'three',
          },
        },
        options: {
          path: 'one.three',
        },
      });

      expect(transform.doTransform()).toEqual('');
    });

    test('perform wrong path with default', async () => {
      transform = new TransformGet({
        value: {
          one: {
            two: 'three',
          },
        },
        options: {
          path: 'one.three',
          default: 'four',
        },
      });

      expect(transform.doTransform()).toEqual('four');
    });
  });

  describe('TransformJoin', () => {
    test('perform without glue', async () => {
      transform = new TransformJoin({
        value: ['one', 'two', 'three'],
      });

      expect(transform.doTransform()).toEqual('one two three');
    });

    test('perform with glue', async () => {
      transform = new TransformJoin({
        value: ['one', 'two', 'three'],
        options: {
          glue: ', ',
        },
      });

      expect(transform.doTransform()).toEqual('one, two, three');
    });

    test('perform with wrong value', async () => {
      transform = new TransformJoin({
        value: 'one two',
      });

      expect(transform.doTransform()).toEqual('one two');
    });
  });

  describe('TransformMatch', () => {
    test('perform with default value', async () => {
      transform = new TransformMatch({
        value: 'one/two/three',
        options: {
          re: [
            '^([^/]+)/([^/]+)/([^/]+)$',
          ],
        },
      });

      expect(transform.doTransform()).toEqual('one/two/three');
    });

    test('perform with specified index', async () => {
      transform = new TransformMatch({
        value: 'one/two/three',
        options: {
          re: [
            '^([^/]+)/([^/]+)/([^/]+)$',
          ],
          index: 1,
        },
      });

      expect(transform.doTransform()).toEqual('one');
    });

    test('perform with index=any returning true', async () => {
      transform = new TransformMatch({
        value: 'one/two/three',
        options: {
          re: [
            '^([^/]+)/([^/]+)/([^/]+)$',
          ],
          index: 'any',
        },
      });

      expect(transform.doTransform()).toEqual(true);
    });

    test('perform with index=any returning false', async () => {
      transform = new TransformMatch({
        value: 'one/two/three',
        options: {
          re: [
            '^([^/]+)\\.([^/]+)\\.([^/]+)$',
          ],
          index: 'any',
        },
      });

      expect(transform.doTransform()).toEqual(false);
    });

    test('perform with index=all', async () => {
      transform = new TransformMatch({
        value: 'one',
        options: {
          re: [
            '(.+)',
            'g'
          ],
          index: 'all',
        },
      });
      expect(transform.doTransform()).toEqual(['one']);
    });

    test('perform returning no matches', async () => {
      transform = new TransformMatch({
        value: 'one',
        options: {
          re: [
            'two',
          ],
        },
      });
      expect(transform.doTransform()).toEqual(null);
    });

    test('perform with wrong value', async () => {
      transform = new TransformMatch({
        value: ['one'],
        options: {
          re: [
            'one',
          ],
        },
      });
      expect(transform.doTransform()).toEqual(null);
    });

    test('perform with wrong index', async () => {
      transform = new TransformMatch({
        value: 'one',
        options: {
          re: [
            'one',
          ],
          index: 7,
        },
      });
      expect(transform.doTransform()).toEqual(null);
    });

    test('perform with index as array', async () => {
      transform = new TransformMatch({
        value: 'one',
        options: {
          re: [
            'one',
          ],
          index: [0, 7],
        },
      });
      expect(transform.doTransform()).toEqual('one');
    });
  });

  describe('TransformPick', () => {
    test('perform', async () => {
      transform = new TransformPick({
        value: {
          one: '1',
          two: '2',
          three: '3',
        },
        options: {
          prop: ['one', 'three']
        },
      });

      expect(transform.doTransform()).toEqual({
        one: '1',
        three: '3',
      });
    });
  });

  describe('TransformPluck', () => {
    test('perform', async () => {
      transform = new TransformPluck({
        value: [
          { 'user': 'barney', 'age': 36 },
          { 'user': 'fred', 'age': 40 },
        ],
        options: {
          path: 'user'
        },
      });

      expect(transform.doTransform()).toEqual(['barney', 'fred']);
    });
  });

  describe('TransformReplace', () => {
    test('perform with correct values', async () => {
      transform = new TransformReplace({
        value: 'one/two/three',
        options: {
          re: ['^([^/]+)/([^/]+)/([^/]+)$'],
          to: '$1.four.$3'
        },
      });

      expect(transform.doTransform()).toEqual('one.four.three');
    });

    test('perform with value as non string', async () => {
      transform = new TransformReplace({
        value: ['one/two/three'],
        options: {
          re: ['^([^/]+)/([^/]+)/([^/]+)$'],
          to: '$1.four.$3'
        },
      });

      expect(transform.doTransform()).toEqual('');
    });

    test('perform with incorrect `re`', async () => {
      transform = new TransformReplace({
        value: 'one/two/three',
        options: {
          re: '^([^/]+)/([^/]+)/([^/]+)$',
          to: '$1.four.$3'
        },
      });

      const fn = () => {
        return transform.doTransform();
      };

      expect(fn).toThrowError(/^You must pass an array as `re` to `replace` transform$/);
    });
  });
});
<commit_msg>- added TransformDate test<commit_after>/* eslint-env jest */

const TransformTrim = require('../../../lib/transforms/TransformTrim');
const TransformBase64Decode = require('../../../lib/transforms/TransformBase64Decode');
const TransformSplit = require('../../../lib/transforms/TransformSplit');
const TransformCombine = require('../../../lib/transforms/TransformCombine');
const TransformCompare = require('../../../lib/transforms/TransformCompare');
const TransformDecodeHtml = require('../../../lib/transforms/TransformDecodeHtml');
const TransformDecodeUri = require('../../../lib/transforms/TransformDecodeUri');
const TransformEncodeUri = require('../../../lib/transforms/TransformEncodeUri');
const TransformEqual = require('../../../lib/transforms/TransformEqual');
const TransformGet = require('../../../lib/transforms/TransformGet');
const TransformJoin = require('../../../lib/transforms/TransformJoin');
const TransformMatch = require('../../../lib/transforms/TransformMatch');
const TransformPick = require('../../../lib/transforms/TransformPick');
const TransformPluck = require('../../../lib/transforms/TransformPluck');
const TransformReplace = require('../../../lib/transforms/TransformReplace');
const TransformDate = require('../../../lib/transforms/TransformDate');
const Storage = require('../../../lib/Storage');

jest.mock('../../../lib/Storage');

describe('Transforms', () => {
  let transform;
  let storage;

  beforeAll(async () => {
    storage = new Storage({});
  });

  describe('TransformTrim', () => {
    test('perform with string', async () => {
      transform = new TransformTrim({
        value: '   test   ',
      });

      expect(transform.doTransform()).toEqual('test');
    });

    test('perform with non-string', async () => {
      transform = new TransformTrim({
        value: 12345,
      });

      expect(transform.doTransform()).toEqual(12345);
    });
  });

  describe('TransformBase64Decode', () => {
    test('perform', async () => {
      transform = new TransformBase64Decode({
        value: 'dGVzdA==',
      });

      expect(transform.doTransform()).toEqual('test');
    });
  });

  describe('TransformSplit', () => {
    test('perform with all default values', async () => {
      transform = new TransformSplit({
        value: '123,345,678',
      });

      expect(transform.doTransform()).toEqual('123');
    });

    test('perform with specified index', async () => {
      transform = new TransformSplit({
        value: '123,345,678',
        options: {
          index: 1,
        },
      });

      expect(transform.doTransform()).toEqual('345');
    });

    test('perform with wrong index', async () => {
      transform = new TransformSplit({
        value: '123,345,678',
        options: {
          index: 5,
        },
      });

      expect(transform.doTransform()).toEqual(null);
    });

    test('perform with specified separator', async () => {
      transform = new TransformSplit({
        value: '123:345:678',
        options: {
          separator: ':',
        },
      });

      expect(transform.doTransform()).toEqual('123');
    });

    test('perform with specified separator as regex', async () => {
      transform = new TransformSplit({
        value: '123:345:678',
        options: {
          separator: [':', 'ui'],
        },
      });

      expect(transform.doTransform()).toEqual('123');
    });

    test('perform with incorrect value', async () => {
      transform = new TransformSplit({
        value: ['123'],
      });

      expect(transform.doTransform()).toEqual('');
    });

    test('perform with specified dataType', async () => {
      transform = new TransformSplit({
        value: '123,345,678',
        options: {
          dataType: 'array',
        },
      });

      expect(transform.doTransform()).toEqual([
        '123',
        '345',
        '678',
      ]);
    });
  });

  describe('TransformCombine', () => {
    test('perform with default values', async () => {
      transform = new TransformCombine({});

      expect(transform.doTransform()).toEqual([]);
    });

    test('perform with data', async () => {
      const data = {
        'one': '1',
        'two': '2',
      };
      storage.get.mockClear();
      storage.get.mockImplementation((key) => data[key]);
      transform = new TransformCombine({
        options: {
          fields: [
            'one',
            'two',
          ],
        },
        storage,
      });

      expect(transform.doTransform()).toEqual(['1', '2']);

      expect(storage.get).toHaveBeenCalledTimes(2);
      expect(storage.get).toHaveBeenCalledWith('one');
      expect(storage.get).toHaveBeenCalledWith('two');
    });

    const checkCombineWithDataType = (dataType, result) => {
      const data = {
        'one': '1',
        'two': '2',
      };
      storage.get.mockClear();
      storage.get.mockImplementation((key) => data[key]);
      transform = new TransformCombine({
        options: {
          fields: [
            'one',
            'two',
          ],
          dataType,
        },
        storage,
      });

      expect(transform.doTransform()).toEqual(result);

      expect(storage.get).toHaveBeenCalledTimes(2);
      expect(storage.get).toHaveBeenCalledWith('one');
      expect(storage.get).toHaveBeenCalledWith('two');
    };

    test('perform with data and data dataType=int.integer', async () => {
      checkCombineWithDataType('int', [1, 2]);
      checkCombineWithDataType('integer', [1, 2]);
    });

    test('perform with data and data dataType=float,number,double', async () => {
      checkCombineWithDataType('float', [1.0, 2.0]);
      checkCombineWithDataType('double', [1.0, 2.0]);
      checkCombineWithDataType('number', [1.0, 2.0]);
    });
  });

  describe('TransformCompare', () => {
    test('perform with data returning true value', async () => {
      const data = {
        'one': '1',
      };
      storage.get.mockClear();
      storage.get.mockImplementation((key) => data[key]);
      transform = new TransformCompare({
        options: {
          field: 'one',
        },
        value: '1',
        storage,
      });

      expect(transform.doTransform()).toEqual(true);

      expect(storage.get).toHaveBeenCalledTimes(1);
      expect(storage.get).toHaveBeenCalledWith('one');
    });

    test('perform with data returning false value', async () => {
      const data = {
        'one': '1',
      };
      storage.get.mockClear();
      storage.get.mockImplementation((key) => data[key]);
      transform = new TransformCompare({
        options: {
          field: 'two',
        },
        value: '1',
        storage,
      });

      expect(transform.doTransform()).toEqual(false);

      expect(storage.get).toHaveBeenCalledTimes(1);
      expect(storage.get).toHaveBeenCalledWith('two');
    });
  });

  describe('TransformDecodeHtml', () => {
    test('perform', async () => {
      transform = new TransformDecodeHtml({
        value: '<>"&©®',
      });

      expect(transform.doTransform()).toEqual('<>"&©®');
    });
  });

  describe('TransformDecodeUri', () => {
    test('perform', async () => {
      transform = new TransformDecodeUri({
        value: 'https://www.google.com/?q=goose-parser%20is%20a%20library%20for%20parsing',
      });

      expect(transform.doTransform()).toEqual('https://www.google.com/?q=goose-parser is a library for parsing');
    });
  });

  describe('TransformEncodeUri', () => {
    test('perform', async () => {
      transform = new TransformEncodeUri({
        value: 'https://www.google.com/?q=goose-parser is a library for parsing',
      });

      expect(transform.doTransform()).toEqual('https://www.google.com/?q=goose-parser%20is%20a%20library%20for%20parsing');
    });
  });

  describe('TransformEqual', () => {
    test('perform with returning true', async () => {
      transform = new TransformEqual({
        value: 'one',
        options: {
          value: 'one',
        },
      });

      expect(transform.doTransform()).toEqual(true);
    });

    test('perform returning false', async () => {
      transform = new TransformEqual({
        value: 'one',
        options: {
          value: 'two',
        },
      });

      expect(transform.doTransform()).toEqual(false);
    });
  });

  describe('TransformGet', () => {
    test('perform', async () => {
      transform = new TransformGet({
        value: {
          one: {
            two: 'three',
          },
        },
        options: {
          path: 'one.two',
        },
      });

      expect(transform.doTransform()).toEqual('three');
    });

    test('perform wrong path without default', async () => {
      transform = new TransformGet({
        value: {
          one: {
            two: 'three',
          },
        },
        options: {
          path: 'one.three',
        },
      });

      expect(transform.doTransform()).toEqual('');
    });

    test('perform wrong path with default', async () => {
      transform = new TransformGet({
        value: {
          one: {
            two: 'three',
          },
        },
        options: {
          path: 'one.three',
          default: 'four',
        },
      });

      expect(transform.doTransform()).toEqual('four');
    });
  });

  describe('TransformJoin', () => {
    test('perform without glue', async () => {
      transform = new TransformJoin({
        value: ['one', 'two', 'three'],
      });

      expect(transform.doTransform()).toEqual('one two three');
    });

    test('perform with glue', async () => {
      transform = new TransformJoin({
        value: ['one', 'two', 'three'],
        options: {
          glue: ', ',
        },
      });

      expect(transform.doTransform()).toEqual('one, two, three');
    });

    test('perform with wrong value', async () => {
      transform = new TransformJoin({
        value: 'one two',
      });

      expect(transform.doTransform()).toEqual('one two');
    });
  });

  describe('TransformMatch', () => {
    test('perform with default value', async () => {
      transform = new TransformMatch({
        value: 'one/two/three',
        options: {
          re: [
            '^([^/]+)/([^/]+)/([^/]+)$',
          ],
        },
      });

      expect(transform.doTransform()).toEqual('one/two/three');
    });

    test('perform with specified index', async () => {
      transform = new TransformMatch({
        value: 'one/two/three',
        options: {
          re: [
            '^([^/]+)/([^/]+)/([^/]+)$',
          ],
          index: 1,
        },
      });

      expect(transform.doTransform()).toEqual('one');
    });

    test('perform with index=any returning true', async () => {
      transform = new TransformMatch({
        value: 'one/two/three',
        options: {
          re: [
            '^([^/]+)/([^/]+)/([^/]+)$',
          ],
          index: 'any',
        },
      });

      expect(transform.doTransform()).toEqual(true);
    });

    test('perform with index=any returning false', async () => {
      transform = new TransformMatch({
        value: 'one/two/three',
        options: {
          re: [
            '^([^/]+)\\.([^/]+)\\.([^/]+)$',
          ],
          index: 'any',
        },
      });

      expect(transform.doTransform()).toEqual(false);
    });

    test('perform with index=all', async () => {
      transform = new TransformMatch({
        value: 'one',
        options: {
          re: [
            '(.+)',
            'g'
          ],
          index: 'all',
        },
      });
      expect(transform.doTransform()).toEqual(['one']);
    });

    test('perform returning no matches', async () => {
      transform = new TransformMatch({
        value: 'one',
        options: {
          re: [
            'two',
          ],
        },
      });
      expect(transform.doTransform()).toEqual(null);
    });

    test('perform with wrong value', async () => {
      transform = new TransformMatch({
        value: ['one'],
        options: {
          re: [
            'one',
          ],
        },
      });
      expect(transform.doTransform()).toEqual(null);
    });

    test('perform with wrong index', async () => {
      transform = new TransformMatch({
        value: 'one',
        options: {
          re: [
            'one',
          ],
          index: 7,
        },
      });
      expect(transform.doTransform()).toEqual(null);
    });

    test('perform with index as array', async () => {
      transform = new TransformMatch({
        value: 'one',
        options: {
          re: [
            'one',
          ],
          index: [0, 7],
        },
      });
      expect(transform.doTransform()).toEqual('one');
    });
  });

  describe('TransformPick', () => {
    test('perform', async () => {
      transform = new TransformPick({
        value: {
          one: '1',
          two: '2',
          three: '3',
        },
        options: {
          prop: ['one', 'three']
        },
      });

      expect(transform.doTransform()).toEqual({
        one: '1',
        three: '3',
      });
    });
  });

  describe('TransformPluck', () => {
    test('perform', async () => {
      transform = new TransformPluck({
        value: [
          { 'user': 'barney', 'age': 36 },
          { 'user': 'fred', 'age': 40 },
        ],
        options: {
          path: 'user'
        },
      });

      expect(transform.doTransform()).toEqual(['barney', 'fred']);
    });
  });

  describe('TransformReplace', () => {
    test('perform with correct values', async () => {
      transform = new TransformReplace({
        value: 'one/two/three',
        options: {
          re: ['^([^/]+)/([^/]+)/([^/]+)$'],
          to: '$1.four.$3'
        },
      });

      expect(transform.doTransform()).toEqual('one.four.three');
    });

    test('perform with value as non string', async () => {
      transform = new TransformReplace({
        value: ['one/two/three'],
        options: {
          re: ['^([^/]+)/([^/]+)/([^/]+)$'],
          to: '$1.four.$3'
        },
      });

      expect(transform.doTransform()).toEqual('');
    });

    test('perform with incorrect `re`', async () => {
      transform = new TransformReplace({
        value: 'one/two/three',
        options: {
          re: '^([^/]+)/([^/]+)/([^/]+)$',
          to: '$1.four.$3'
        },
      });

      const fn = () => {
        return transform.doTransform();
      };

      expect(fn).toThrowError(/^You must pass an array as `re` to `replace` transform$/);
    });
  });

  describe('TransformDate', () => {
    test('perform with default locale', async () => {
      transform = new TransformDate({
        value: '01.12.2018',
        options: {
          from: 'DD.MM.YYYY',
          to: 'MM-DD-YYYY',
        },
      });

      expect(transform.doTransform()).toEqual('12-01-2018');
    });

    test('perform with locale=en', async () => {
      transform = new TransformDate({
        value: '01.12.2018',
        options: {
          from: 'DD.MM.YYYY',
          to: 'MM-DD-YYYY',
          locale: 'en',
        },
      });

      expect(transform.doTransform()).toEqual('12-01-2018');
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var expect = chai.expect;
var sinon = require("sinon");

var rewire = require('../../rewire_helper');
var ViewButtonsView = rewire('views/ViewButtonsView');

window.plugPro = {};
var templateLoader = require('../../template_loader');
Backbone.$ = $;

describe("ViewButtonsView", function(){

	var JST;
	var viewButtonsView;
	var fakeToggleSettings;

	beforeEach(function(){
		ViewButtonsView.__set__( "VideoView", Backbone.View.extend() );

		window.plugPro.JST['view_buttons.html'] = function(){
			return "view_buttons";
		};

		viewButtonsView = new ViewButtonsView();

	});

	describe("initialize", function(){

		it("should set buttonsHTML", function(){
			expect( viewButtonsView.buttonsHTML ).to.not.be.undefined;
		});

	});

	describe("render", function(){

		beforeEach(function(){
			sinon.stub( viewButtonsView, "loadView" );
		});

		afterEach(function(){
			viewButtonsView.loadView.restore();
		});

		it("should append buttons", function(){
			viewButtonsView.render();
			expect( viewButtonsView.el.innerHTML ).to.equal( window.plugPro.JST['view_buttons.html']() );
		});

		it("should load initial view", function(){
			viewButtonsView.render();
			expect( viewButtonsView.loadView.calledOnce ).to.be.true;
		});

	});

	describe("handleButtonClick", function(){

		beforeEach(function(){
			sinon.stub( viewButtonsView, "loadView" );
		});

		afterEach(function(){
			viewButtonsView.loadView.restore();
		});

		it("should call loadView if valid view", function(){
			$('body').html("

");
			var fakeEvent = {
				currentTarget: $('#fake-button')[0]
			};
			viewButtonsView.handleButtonClick( fakeEvent );
			expect( viewButtonsView.loadView.calledOnce ).to.be.true;
		});

		it("should not call loadView if not valid view", function(){
			$('body').html("

");
			var fakeEvent = {
				currentTarget: $('#fake-button')[0]
			};
			viewButtonsView.handleButtonClick( fakeEvent );
			expect( viewButtonsView.loadView.called ).to.be.false;
		});

	});

});<commit_msg>Add loadView tests<commit_after>'use strict';

var chai = require('chai');
var expect = chai.expect;
var sinon = require("sinon");

var rewire = require('../../rewire_helper');
var ViewButtonsView = rewire('views/ViewButtonsView');

window.plugPro = {};
var templateLoader = require('../../template_loader');
Backbone.$ = $;

describe("ViewButtonsView", function(){

	var JST;
	var viewButtonsView;
	var fakeToggleSettings;

	beforeEach(function(){
		ViewButtonsView.__set__( "VideoView", Backbone.View.extend() );

		window.plugPro.JST['view_buttons.html'] = function(){
			return "view_buttons";
		};

		viewButtonsView = new ViewButtonsView();

	});

	describe("initialize()", function(){

		it("should set buttonsHTML", function(){
			expect( viewButtonsView.buttonsHTML ).to.not.be.undefined;
		});

	});

	describe("render()", function(){

		beforeEach(function(){
			sinon.stub( viewButtonsView, "loadView" );
		});

		afterEach(function(){
			viewButtonsView.loadView.restore();
		});

		it("should append buttons", function(){
			viewButtonsView.render();
			expect( viewButtonsView.el.innerHTML ).to.equal( window.plugPro.JST['view_buttons.html']() );
		});

		it("should load initial view", function(){
			viewButtonsView.render();
			expect( viewButtonsView.loadView.calledOnce ).to.be.true;
		});

	});

	describe("handleButtonClick()", function(){

		beforeEach(function(){
			sinon.stub( viewButtonsView, "loadView" );
		});

		afterEach(function(){
			viewButtonsView.loadView.restore();
		});

		it("should call loadView if valid view", function(){
			$('body').html("

");
			var fakeEvent = {
				currentTarget: $('#fake-button')[0]
			};
			viewButtonsView.handleButtonClick( fakeEvent );
			expect( viewButtonsView.loadView.calledOnce ).to.be.true;
		});

		it("should not call loadView if not valid view", function(){
			$('body').html("

");
			var fakeEvent = {
				currentTarget: $('#fake-button')[0]
			};
			viewButtonsView.handleButtonClick( fakeEvent );
			expect( viewButtonsView.loadView.called ).to.be.false;
		});

	});

	describe("loadView()", function(){

		var fakeView;

		beforeEach(function(){
			fakeView = {
				render: function(){}
			};
			sinon.stub( fakeView, "render" );
			sinon.stub( viewButtonsView, "removeCurrentView" );
		});

		afterEach(function(){
			viewButtonsView.removeCurrentView.restore();
			fakeView.render.restore();
		});

		it("should remove current view", function(){
			viewButtonsView.loadView( fakeView );
			expect( viewButtonsView.removeCurrentView.calledOnce ).to.be.true;
		});

		it("should set new current view", function(){
			viewButtonsView.loadView( fakeView );
			expect( viewButtonsView.currentView ).to.equal( fakeView );
		});

		it("should render new view", function(){
			viewButtonsView.loadView( fakeView );
			expect( fakeView.render.calledOnce ).to.be.true;
		});

	});

});<|endoftext|>


<commit_before>DDH.'<: $lia_id :>' = DDH.'<: $lia_id :>' || {};

(function(env) {

    console.log("DDH.'<: $lia_id :>'.build");

	// define private variables and functions here

    DDH.'<: $lia_id :>'.build = function(ops) {

        return {
            id: "life",

            meta: {
				sourceName: "Source Domain",
				sourceUrl: "https://source.website.com"
			},

			// data: {
			// already defined in Perl Package
			// you can re-define it here
			// or access/modify 'ops.data'
			// },

			// normalize: function(item){
			// use this to map your 'data'
			// to the properties required for your chosen template
			//
			// 	return {
			// 		title: data.myTitle
			// 		subtitle: data.foo.subtitle
			// 	};
			// },

            templates: {
                group: 'text',

                // options: {
                //
                // },

                // variants: {
                //
                // }
            },

			// Function that executes after template content is displayed
			onShow: function() {

				// define any callbacks or event handlers here
				//
				// var $dom = $(".zci--'<: $lia_id :>'");
				// $dom.find(".my-special-class").click(funtcion(){
				//
				// });

            }
        };
    };
})(DDH);
<commit_msg>Convert tabs to spaces<commit_after>DDH.'<: $lia_id :>' = DDH.'<: $lia_id :>' || {};

(function(env) {

    console.log("DDH.'<: $lia_id :>'.build");

    // define private variables and functions here

    DDH.'<: $lia_id :>'.build = function(ops) {

        return {
            id: "life",

            meta: {
                sourceName: "Source Domain",
                sourceUrl: "https://source.website.com"
            },

            // data: {
            // already defined in Perl Package
            // you can re-define it here
            // or access/modify 'ops.data'
            // },

            // normalize: function(item){
            // use this to map your 'data'
            // to the properties required for your chosen template
            //
            //     return {
            //         title: data.myTitle
            //         subtitle: data.foo.subtitle
            //     };
            // },

            templates: {
                group: 'text',

                // options: {
                //
                // },

                // variants: {
                //
                // }
            },

            // Function that executes after template content is displayed
            onShow: function() {

                // define any callbacks or event handlers here
                //
                // var $dom = $(".zci--'<: $lia_id :>'");
                // $dom.find(".my-special-class").click(funtcion(){
                //
                // });

            }
        };
    };
})(DDH);
<|endoftext|>


<commit_before>import Character from './CharacterClass';

function getCaptainList(characters) {
  let list = [];
  characters.forEach(character => {
    if (character.captainEffect === true) {
      list.push(Character.get(character.no));
    }
  });
  return list;
}

function getSpecialAbilityList(characters) {
  let list = [];
  characters.forEach(character => {
    if (character.specialAbility !== true) {
      return;
    }

    const characterInfo = Character.get(character.no);
    if (characterInfo.specialAbility.magnification !== null) {
      list.push(characterInfo);
    }
  });
  return list;
}

function getTypeMagnification(character, enemy) {
  if (character.type === '力' && enemy.type === '技') return 2;
  if (character.type === '技' && enemy.type === '速') return 2;
  if (character.type === '速' && enemy.type === '力') return 2;
  if (character.type === '心' && enemy.type === '知') return 2;
  if (character.type === '知' && enemy.type === '心') return 2;
  if (character.type === '技' && enemy.type === '力') return 0.5;
  if (character.type === '速' && enemy.type === '技') return 0.5;
  if (character.type === '力' && enemy.type === '速') return 0.5;
  return 1;
}

function getCaptainMagnification(currentCharacterList, captainList) {
  let current = currentCharacterList.slice();   // Array copy
  const character = current.pop();
  const characterInfo = Character.get(character.no);
  const timingHistory = current.map(character => {
    return character.timing;
  });

  const magni = captainList.map(character => {
    return character.captainEffect.magnification;
  })
  .reduce((magni, fn) => {
    return magni * fn({
      character: characterInfo,
      timingHistory,
      characterList: current,
      bead: character.bead
    });
  }, 1);
  return Math.round(magni * 100) / 100;
}

function getSpecialMagnification(currentCharacterList, specialAbilityList) {
  let current = currentCharacterList.slice();   // Array copy
  const character = current.pop();
  const characterInfo = Character.get(character.no);

  const magni = specialAbilityList.map(character => {
    return character.specialAbility.magnification;
  })
  .reduce((magni, fn) => {
    return magni * fn({
      character: characterInfo,
      bead: character.bead
    })
  }, 1);
  return Math.round(magni * 100) / 100;
}

function getBasicAttack(attack, magnification) {
  let basic = attack;
  for (let key in magnification) {
    basic *= magnification[key];
  }
  return Math.round(basic);
}

function getSigalAttack(basicAttack, combo) {
  return Math.round(basicAttack / combo);
}

function getFinalAttack(basicAttack, combo, timing) {
  let magni = 0;
  if (timing === 'good')    magni = 0.3;
  if (timing === 'great')   magni = 0.5939;
  if (timing === 'perfect') magni = 0.8999;

  const final = (basicAttack / combo) * (combo * magni + 1)
  return Math.round(final);
}

function getAttackCombo(combo, timing) {
  if (timing === 'bad')   return combo - 3;
  if (timing === 'good')  return combo - 3;
  if (timing === 'great') return combo - 1;
  return combo;
}

function updateChainMagnification(magni: originalChainMagnification, timing, captainList) {
  // check chain coefficient
  let coefficient = 1;
  captainList.forEach(function (character) {
    coefficient *= character.captainEffect.chainCoefficient;
  });

  switch (timing) {
    case 'good':    magni += 0   * coefficient;  break;
    case 'great':   magni += 0.1 * coefficient;  break;
    case 'perfect': magni += 0.3 * coefficient;  break;
    case 'bad':
    case 'miss':    magni =  1;    break;
  }
  return Math.round(magni * 10) / 10;
}

function getDamage(attack, defense) {
  const damage = attack - defense;
  return damage > 1 ? damage : 1;
}

export default function attackAnalysis({ enemy, boat, characters }) {
  // get captains
  const captains = getCaptainList(characters);
  if (captains.length > 2) {
    throw new Error('It should not have more than 2 captain at the same time');
  }

  const specialAbilities = getSpecialAbilityList(characters);

  let analysis = [];
  let chainMagnification = 1;
  let total = {
    attack: 0,
    combo: 0
  };
  let current = [];
  characters.forEach(function(character) {
    current.push(character);
    const characterInfo = Character.get(character.no);

    const magnification = {
      boat,
      bead: character.bead,
      chain: chainMagnification,
      type: getTypeMagnification(characterInfo, enemy),
      captain: getCaptainMagnification(current, captains),
      special: getSpecialMagnification(current, specialAbilities),
      custom: character.custom
    };

    // Basic Attack
    const basic = getBasicAttack(character.attack, magnification);

    const attack = {
      original: character.attack,
      basic,
      singal: getSigalAttack(basic, characterInfo.combo),
      final: getFinalAttack(basic, characterInfo.combo, character.timing),
      timing: character.timing,
      combo: getAttackCombo(characterInfo.combo, character.timing)
    };

    // update chain magnification
    chainMagnification = updateChainMagnification(chainMagnification, character.timing, captains);

    // Damage
    let damage = {
      singal: getDamage(attack.singal, enemy.defense),
      final: getDamage(attack.final, enemy.defense),
      history: [],
      total: 0
    };

    // Total Damage
    for (let i = 0; i < attack.combo; i++) {
      damage.total += damage.singal;
      damage.history.push(damage.total);
    }
    damage.total += damage.final - damage.singal;

    // Total
    total.attack += damage.total;
    total.combo += attack.combo;

    // add stucture to analysis
    analysis.push({
      character: characterInfo,
      magnification,
      attack,
      damage,
      total: {
        attack: total.attack,
        combo: total.combo
      }
    });
  });

  return { captains, specialAbilities, analysis, total };
}
<commit_msg>[bug fix] timing good reduce 2 combo<commit_after>import Character from './CharacterClass';

function getCaptainList(characters) {
  let list = [];
  characters.forEach(character => {
    if (character.captainEffect === true) {
      list.push(Character.get(character.no));
    }
  });
  return list;
}

function getSpecialAbilityList(characters) {
  let list = [];
  characters.forEach(character => {
    if (character.specialAbility !== true) {
      return;
    }

    const characterInfo = Character.get(character.no);
    if (characterInfo.specialAbility.magnification !== null) {
      list.push(characterInfo);
    }
  });
  return list;
}

function getTypeMagnification(character, enemy) {
  if (character.type === '力' && enemy.type === '技') return 2;
  if (character.type === '技' && enemy.type === '速') return 2;
  if (character.type === '速' && enemy.type === '力') return 2;
  if (character.type === '心' && enemy.type === '知') return 2;
  if (character.type === '知' && enemy.type === '心') return 2;
  if (character.type === '技' && enemy.type === '力') return 0.5;
  if (character.type === '速' && enemy.type === '技') return 0.5;
  if (character.type === '力' && enemy.type === '速') return 0.5;
  return 1;
}

function getCaptainMagnification(currentCharacterList, captainList) {
  let current = currentCharacterList.slice();   // Array copy
  const character = current.pop();
  const characterInfo = Character.get(character.no);
  const timingHistory = current.map(character => {
    return character.timing;
  });

  const magni = captainList.map(character => {
    return character.captainEffect.magnification;
  })
  .reduce((magni, fn) => {
    return magni * fn({
      character: characterInfo,
      timingHistory,
      characterList: current,
      bead: character.bead
    });
  }, 1);
  return Math.round(magni * 100) / 100;
}

function getSpecialMagnification(currentCharacterList, specialAbilityList) {
  let current = currentCharacterList.slice();   // Array copy
  const character = current.pop();
  const characterInfo = Character.get(character.no);

  const magni = specialAbilityList.map(character => {
    return character.specialAbility.magnification;
  })
  .reduce((magni, fn) => {
    return magni * fn({
      character: characterInfo,
      bead: character.bead
    })
  }, 1);
  return Math.round(magni * 100) / 100;
}

function getBasicAttack(attack, magnification) {
  let basic = attack;
  for (let key in magnification) {
    basic *= magnification[key];
  }
  return Math.round(basic);
}

function getSigalAttack(basicAttack, combo) {
  return Math.round(basicAttack / combo);
}

function getFinalAttack(basicAttack, combo, timing) {
  let magni = 0;
  if (timing === 'good')    magni = 0.3;
  if (timing === 'great')   magni = 0.5939;
  if (timing === 'perfect') magni = 0.8999;

  const final = (basicAttack / combo) * (combo * magni + 1)
  return Math.round(final);
}

function getAttackCombo(combo, timing) {
  if (timing === 'bad')   return combo - 3;
  if (timing === 'good')  return combo - 2;
  if (timing === 'great') return combo - 1;
  return combo;
}

function updateChainMagnification(magni: originalChainMagnification, timing, captainList) {
  // check chain coefficient
  let coefficient = 1;
  captainList.forEach(function (character) {
    coefficient *= character.captainEffect.chainCoefficient;
  });

  switch (timing) {
    case 'good':    magni += 0   * coefficient;  break;
    case 'great':   magni += 0.1 * coefficient;  break;
    case 'perfect': magni += 0.3 * coefficient;  break;
    case 'bad':
    case 'miss':    magni =  1;    break;
  }
  return Math.round(magni * 10) / 10;
}

function getDamage(attack, defense) {
  const damage = attack - defense;
  return damage > 1 ? damage : 1;
}

export default function attackAnalysis({ enemy, boat, characters }) {
  // get captains
  const captains = getCaptainList(characters);
  if (captains.length > 2) {
    throw new Error('It should not have more than 2 captain at the same time');
  }

  const specialAbilities = getSpecialAbilityList(characters);

  let analysis = [];
  let chainMagnification = 1;
  let total = {
    attack: 0,
    combo: 0
  };
  let current = [];
  characters.forEach(function(character) {
    current.push(character);
    const characterInfo = Character.get(character.no);

    const magnification = {
      boat,
      bead: character.bead,
      chain: chainMagnification,
      type: getTypeMagnification(characterInfo, enemy),
      captain: getCaptainMagnification(current, captains),
      special: getSpecialMagnification(current, specialAbilities),
      custom: character.custom
    };

    // Basic Attack
    const basic = getBasicAttack(character.attack, magnification);

    const attack = {
      original: character.attack,
      basic,
      singal: getSigalAttack(basic, characterInfo.combo),
      final: getFinalAttack(basic, characterInfo.combo, character.timing),
      timing: character.timing,
      combo: getAttackCombo(characterInfo.combo, character.timing)
    };

    // update chain magnification
    chainMagnification = updateChainMagnification(chainMagnification, character.timing, captains);

    // Damage
    let damage = {
      singal: getDamage(attack.singal, enemy.defense),
      final: getDamage(attack.final, enemy.defense),
      history: [],
      total: 0
    };

    // Total Damage
    for (let i = 0; i < attack.combo; i++) {
      damage.total += damage.singal;
      damage.history.push(damage.total);
    }
    damage.total += damage.final - damage.singal;

    // Total
    total.attack += damage.total;
    total.combo += attack.combo;

    // add stucture to analysis
    analysis.push({
      character: characterInfo,
      magnification,
      attack,
      damage,
      total: {
        attack: total.attack,
        combo: total.combo
      }
    });
  });

  return { captains, specialAbilities, analysis, total };
}
<|endoftext|>


<commit_before>const
  path = require('path'),
  sgUtil = require('./util');

class CollectorStore {

  constructor(settings) {

    this.conf = settings.conf;
    this.TemplateEngine = settings.TemplateEngine;
    this.globOptions = this.conf.get('globOptions');
    this.htmlExt = this.conf.get('htmlExt');
    this.dataExt = this.conf.get('dataExt');

    this.sections = new Map();
    this.files = new Map();
    this.dirty = new Map();
    this.cachedFiles = new Map();

    this.setSection = this.setSection.bind(this);
    this.setFile = this.setFile.bind(this);
    this.unsetFile = this.unsetFile.bind(this);
    this.markFileAsDirty = this.markFileAsDirty.bind(this);
    this.setGroupedFile = this.setGroupedFile.bind(this);
    this.unsetGroupedFile = this.unsetGroupedFile.bind(this);
    this.getSection = this.getSection.bind(this);
    this.getSections = this.getSections.bind(this);
    this.getSectionFilesData = this.getSectionFilesData.bind(this);
    this.getUrls = this.getUrls.bind(this);
    this.getCollectedData = this.getCollectedData.bind(this);
  }

  setSection(section) {
    const
      {sections, files, constructor, getFilesOfSection} = this,
      {destDir} = section;

    section.getFiles = getFilesOfSection.bind({destDir, files, constructor});

    sections.set(destDir, section);
  }

  getSection(destDir) {
    const {sections} = this;

    return sections.get(destDir);
  }

  setFile(file) {
    const {filename} = file;
    this.markFileAsDirty(filename);
    this.files.set(filename, file);
    return file;
  }

  unsetFile(filename) {
    this.files.delete(filename);
  }

  setGroupedFile(file) {
    const
      {urls, files, constructor} = this,
      {getGroupPaths, getPageTitle} = constructor,
      {filename, url, generator, title, destDir, orderValue} = file,
      {base, groupUrl, name, parentName} = getGroupPaths(filename, url),
      pageTitle = file.pageTitle = getPageTitle(filename, title, name, parentName);

    if (name === 'index' || name === parentName || !urls.get(base)) {
      urls.set(base, {url: groupUrl, title: pageTitle, generator, destDir, orderValue});
    }

    if (files.get(groupUrl) === undefined) {
      files.set(groupUrl, new Map());
    }
    files.get(groupUrl).set(name, file);

    return files.get(groupUrl);
  }

  unsetGroupedFile(filename) {
    const
      {constructor, urls, files} = this,
      {base, name} = constructor.getGroupPaths(filename);

    files.get(filename).delete(name);

    const {size = 0} = files.get(filename);

    if (size === 0) {
      urls.delete(base);
      files.delete(filename);
    }
  }

  getSections(asArray = false) {
    const {sections} = this;

    return asArray === true ? [...sections.values()] : sections;
  }

  getFiles() {
    return this.files;
  }

  getUrls() {
    const urls = new Map();

    this.files.forEach(file => urls.set(sgUtil.removeFileExtension(file.url), file));
    return urls;
  }

  getFilesOfSection() {
    const {files, destDir} = this;
    return [...files.values()]
      .filter(file => destDir === file.destDir);
  }

  getCollectedData() {
    const
      {getSections} = this,
      data = getSections(true).map(section => ({
        generator: section.generator,
        route: section.route,
        title: section.title,
        url: section.url,
        files: this.getSectionFilesData(section)
      }));

    this.touchedFiles = new Map();

    return data;
  }

  getSectionFilesData(section) {
    const {getFiles, url} = section;

    return getFiles().map(file => {

      const {filename} = file;

      if (this.dirty.has(path.dirname(filename))) {

        this.cachedFiles.set(filename, {
          title: file.title,
          generator: file.generator,
          orderValue: file.orderValue || path.relative(url, path.dirname(file.url)),
          url: file.url,
          path: path.relative(url, path.dirname(file.url)),
          asyncContentUrls: {
            source: sgUtil.replaceFileExtension(file.url, `source.${this.htmlExt}`),
            locals: sgUtil.replaceFileExtension(file.url, this.dataExt),
            schema: sgUtil.replaceFileExtension(file.url, `schema.${this.dataExt}`)
          }
        });
      }
      return this.cachedFiles.get(filename);
    });
  }

  markFileAsDirty(filename) {
    this.dirty.set(path.dirname(filename), true);
  }

  static getGroupPaths(filename, url = false) {
    const
      {dir, name} = path.parse(filename),
      parentName = path.basename(dir),
      base = `${dir}/${parentName}`,
      groupUrl = url ? `${url.dirname}/${parentName}${url.extname}` : null;

    return {base, groupUrl, name, parentName};
  }

  static getPageTitle(filename, title, name, parentName) {
    return (name === 'index' || name === parentName) ? title : sgUtil.getTitleFromFoldername(filename);
  }
}

module.exports = CollectorStore;<commit_msg>fix: wrong reset map<commit_after>const
  path = require('path'),
  sgUtil = require('./util');

class CollectorStore {

  constructor(settings) {

    this.conf = settings.conf;
    this.TemplateEngine = settings.TemplateEngine;
    this.globOptions = this.conf.get('globOptions');
    this.htmlExt = this.conf.get('htmlExt');
    this.dataExt = this.conf.get('dataExt');

    this.sections = new Map();
    this.files = new Map();
    this.dirty = new Map();
    this.cachedFiles = new Map();

    this.setSection = this.setSection.bind(this);
    this.setFile = this.setFile.bind(this);
    this.unsetFile = this.unsetFile.bind(this);
    this.markFileAsDirty = this.markFileAsDirty.bind(this);
    this.setGroupedFile = this.setGroupedFile.bind(this);
    this.unsetGroupedFile = this.unsetGroupedFile.bind(this);
    this.getSection = this.getSection.bind(this);
    this.getSections = this.getSections.bind(this);
    this.getSectionFilesData = this.getSectionFilesData.bind(this);
    this.getUrls = this.getUrls.bind(this);
    this.getCollectedData = this.getCollectedData.bind(this);
  }

  setSection(section) {
    const
      {sections, files, constructor, getFilesOfSection} = this,
      {destDir} = section;

    section.getFiles = getFilesOfSection.bind({destDir, files, constructor});

    sections.set(destDir, section);
  }

  getSection(destDir) {
    const {sections} = this;

    return sections.get(destDir);
  }

  setFile(file) {
    const {filename} = file;
    this.markFileAsDirty(filename);
    this.files.set(filename, file);
    return file;
  }

  unsetFile(filename) {
    this.files.delete(filename);
  }

  setGroupedFile(file) {
    const
      {urls, files, constructor} = this,
      {getGroupPaths, getPageTitle} = constructor,
      {filename, url, generator, title, destDir, orderValue} = file,
      {base, groupUrl, name, parentName} = getGroupPaths(filename, url),
      pageTitle = file.pageTitle = getPageTitle(filename, title, name, parentName);

    if (name === 'index' || name === parentName || !urls.get(base)) {
      urls.set(base, {url: groupUrl, title: pageTitle, generator, destDir, orderValue});
    }

    if (files.get(groupUrl) === undefined) {
      files.set(groupUrl, new Map());
    }
    files.get(groupUrl).set(name, file);

    return files.get(groupUrl);
  }

  unsetGroupedFile(filename) {
    const
      {constructor, urls, files} = this,
      {base, name} = constructor.getGroupPaths(filename);

    files.get(filename).delete(name);

    const {size = 0} = files.get(filename);

    if (size === 0) {
      urls.delete(base);
      files.delete(filename);
    }
  }

  getSections(asArray = false) {
    const {sections} = this;

    return asArray === true ? [...sections.values()] : sections;
  }

  getFiles() {
    return this.files;
  }

  getUrls() {
    const urls = new Map();

    this.files.forEach(file => urls.set(sgUtil.removeFileExtension(file.url), file));
    return urls;
  }

  getFilesOfSection() {
    const {files, destDir} = this;
    return [...files.values()]
      .filter(file => destDir === file.destDir);
  }

  getCollectedData() {
    const
      {getSections} = this,
      data = getSections(true).map(section => ({
        generator: section.generator,
        route: section.route,
        title: section.title,
        url: section.url,
        files: this.getSectionFilesData(section)
      }));

    this.dirty = new Map();

    return data;
  }

  getSectionFilesData(section) {
    const {getFiles, url} = section;

    return getFiles().map(file => {

      const {filename} = file;

      if (this.dirty.has(path.dirname(filename))) {

        this.cachedFiles.set(filename, {
          title: file.title,
          generator: file.generator,
          orderValue: file.orderValue || path.relative(url, path.dirname(file.url)),
          url: file.url,
          path: path.relative(url, path.dirname(file.url)),
          asyncContentUrls: {
            source: sgUtil.replaceFileExtension(file.url, `source.${this.htmlExt}`),
            locals: sgUtil.replaceFileExtension(file.url, this.dataExt),
            schema: sgUtil.replaceFileExtension(file.url, `schema.${this.dataExt}`)
          }
        });
      }
      return this.cachedFiles.get(filename);
    });
  }

  markFileAsDirty(filename) {
    this.dirty.set(path.dirname(filename), true);
  }

  static getGroupPaths(filename, url = false) {
    const
      {dir, name} = path.parse(filename),
      parentName = path.basename(dir),
      base = `${dir}/${parentName}`,
      groupUrl = url ? `${url.dirname}/${parentName}${url.extname}` : null;

    return {base, groupUrl, name, parentName};
  }

  static getPageTitle(filename, title, name, parentName) {
    return (name === 'index' || name === parentName) ? title : sgUtil.getTitleFromFoldername(filename);
  }
}

module.exports = CollectorStore;<|endoftext|>