<commit_before>var chai = require('chai'),
    expect = chai.expect;

var chaiLike = require('chai-like');
var chaiThings = require('chai-things');
chai.use(chaiLike);
chai.use(chaiThings);

var jenkinsapi = require('../lib/main');
var JENKINS_URL="http://localhost:8080";

var JOB_NAME_TEST = "asrwqersfdzdraser-test";
var JOB_NAME_NEW = "asrwqersfdzdraser-test-new";
var JOB_NAME_COPY = "asrwqersfdzdraser-test-copy";

var DEVELOPMENT_PROJECT_XML_CONFIG = '<?xml version="1.0" encoding="UTF-8"?><project><description>development</description></project>';
var ORIGINAL_CONFIG = 'development';
var REPLACED_CONFIG = 'feature';

describe('Node Jenkins API', function() {

  it('Should exist', function() {
    expect(jenkinsapi).not.to.be.undefined;
    expect(jenkinsapi.init).to.be.a('function');
  });

  // TODO handle this better as a test setup
  var jenkins = jenkinsapi.init(JENKINS_URL);

  it('Should create the connection object', function() {
    expect(jenkins).not.to.be.undefined;
  });

  // TODO handle this better as a test setup
  jenkins.delete_job(JOB_NAME_NEW);
  jenkins.delete_job(JOB_NAME_COPY);

  it('Should show all jobs', function(done) {
    expect(jenkins.all_jobs).to.be.a('function');

    jenkins.all_jobs(function(error, data) {
      expect(error).to.be.null;
      expect(data).to.be.an('array').that.contains.something.like({name: JOB_NAME_TEST});
      done();
    }); // all_jobs
  });

  it('Should read xml of existing job', function(done) {
    expect(jenkins.get_config_xml).to.be.a('function');

    jenkins.get_config_xml(JOB_NAME_TEST, function(error, data) {
      expect(error).to.be.null;
      expect(data).to.be.a('string').that.contains(ORIGINAL_CONFIG);
      done();
    }); // get_config_xml
  });

  it('Should create and delete job', function(done) {
    expect(jenkins.create_job).to.be.a('function');
    expect(jenkins.delete_job).to.be.a('function');

    jenkins.create_job(JOB_NAME_NEW, DEVELOPMENT_PROJECT_XML_CONFIG, function(error, data) {
      expect(error).to.be.null;

      jenkins.all_jobs(function(error, data) {
        expect(error).to.be.null;
        expect(data).to.be.an('array').that.contains.something.like({name: JOB_NAME_NEW});

        jenkins.delete_job(JOB_NAME_NEW, function(error, data) {
          expect(error).to.be.null;

          jenkins.all_jobs(function(error, data) {
            expect(error).to.be.null;
            expect(data).to.be.an('array').that.not.contains.something.like({name: JOB_NAME_NEW});

            done();

          }); // all_jobs
        }); // delete_job
      }); // all_jobs
    }); // create_job
  });

  it('Should copy job', function(done) {
    expect(jenkins.copy_job).to.be.a('function');

    jenkins.copy_job(JOB_NAME_TEST, JOB_NAME_COPY, function(data) {
      return data.replace(ORIGINAL_CONFIG, REPLACED_CONFIG);
    }, function(error, data) {
      expect(error).to.be.null;

      jenkins.get_config_xml(JOB_NAME_COPY, function(error, data) {
        expect(error).to.be.null;
        expect(data).to.be.a('string').that.contains(REPLACED_CONFIG);

        jenkins.delete_job(JOB_NAME_COPY, function(error, data) {
          expect(error).to.be.null;
          done();
        }); // delete_job
      }); // get_config_xml
    }); // copy_job
  });

  it('Should update job config', function(done) {
    expect(jenkins.update_config).to.be.a('function');

    jenkins.copy_job(JOB_NAME_TEST, JOB_NAME_COPY, function(data) {
      return data;
    }, function(error, data) {
      expect(error).to.be.null;

      jenkins.update_config(JOB_NAME_COPY, function(data) {
        return data.replace(ORIGINAL_CONFIG, REPLACED_CONFIG);
      }, function(error, data) {
        expect(error).to.be.null;

        jenkins.get_config_xml(JOB_NAME_COPY, function(error, data) {
          expect(error).to.be.null;
          expect(data).to.be.a('string').that.contains(REPLACED_CONFIG);

          jenkins.delete_job(JOB_NAME_COPY, function(error, data) {
            expect(error).to.be.null;
            done();
          }); // delete_job
        }); // get_config_xml
      }); // update_config
    }); // copy_job
  });

  var TEST_VIEW_NAME = 'ewoiurewlkjr-test-view';
  var TEST_VIEW_MODE = 'ewoiurewlkjr-test-view-mode';
  var TEST_VIEW_CONF = {
    name: "view-in-jenkins",
    "description": "This is the view-in-jenkins View",
    "statusFilter": "",
    "job-in-jenkins": true,
    "useincluderegex": true,
    "includeRegex": "prefix.*",
    "columns": [{"stapler-class": "hudson.views.StatusColumn", "$class": "hudson.views.StatusColumn"}, {"stapler-class": "hudson.views.WeatherColumn", "$class": "hudson.views.WeatherColumn"}, {"stapler-class": "hudson.views.JobColumn", "$class": "hudson.views.JobColumn"}, {"stapler-class": "hudson.views.LastSuccessColumn", "$class": "hudson.views.LastSuccessColumn"}, {"stapler-class": "hudson.views.LastFailureColumn", "$class": "hudson.views.LastFailureColumn"}, {"stapler-class": "hudson.views.LastDurationColumn", "$class": "hudson.views.LastDurationColumn"}, {"stapler-class": "hudson.views.BuildButtonColumn", "$class": "hudson.views.BuildButtonColumn"}]
  };

  // TODO handle this better as a test setup
  jenkins.delete_view(TEST_VIEW_NAME);

  it.only('Should CRUD a view', function(done) {
    expect(jenkins.create_view).to.be.a('function');
    expect(jenkins.update_view).to.be.a('function');
    expect(jenkins.delete_view).to.be.a('function');
    expect(jenkins.all_jobs_in_view).to.be.a('function');

    jenkins.create_view(TEST_VIEW_NAME, function(error, data) {
      expect(error).to.be.null;
      expect(data).to.be.an('object').like({name: TEST_VIEW_NAME});

      jenkins.update_view(TEST_VIEW_NAME, TEST_VIEW_CONF, function(error, data) {
        expect(error).to.be.null;

        jenkins.delete_view(TEST_VIEW_NAME, function(error, data) {
          expect(error).to.be.null;
          expect(data).to.be.an('object').like({name: TEST_VIEW_NAME});
          done();
        }); // delete_view
      }); // update_view
    }); // create_view
  });

});
<commit_msg>Add test for all_views<commit_after>var chai = require('chai'),
    expect = chai.expect;

var chaiLike = require('chai-like');
var chaiThings = require('chai-things');
chai.use(chaiLike);
chai.use(chaiThings);

var jenkinsapi = require('../lib/main');
var JENKINS_URL="http://localhost:8080";

var JOB_NAME_TEST = "asrwqersfdzdraser-test";
var JOB_NAME_NEW = "asrwqersfdzdraser-test-new";
var JOB_NAME_COPY = "asrwqersfdzdraser-test-copy";

var DEVELOPMENT_PROJECT_XML_CONFIG = '<?xml version="1.0" encoding="UTF-8"?><project><description>development</description></project>';
var ORIGINAL_CONFIG = 'development';
var REPLACED_CONFIG = 'feature';

describe('Node Jenkins API', function() {

  it('Should exist', function() {
    expect(jenkinsapi).not.to.be.undefined;
    expect(jenkinsapi.init).to.be.a('function');
  });

  // TODO handle this better as a test setup
  var jenkins = jenkinsapi.init(JENKINS_URL);

  it('Should create the connection object', function() {
    expect(jenkins).not.to.be.undefined;
  });

  // TODO handle this better as a test setup
  jenkins.delete_job(JOB_NAME_NEW);
  jenkins.delete_job(JOB_NAME_COPY);

  it('Should show all jobs', function(done) {
    expect(jenkins.all_jobs).to.be.a('function');

    jenkins.all_jobs(function(error, data) {
      expect(error).to.be.null;
      expect(data).to.be.an('array').that.contains.something.like({name: JOB_NAME_TEST});
      done();
    }); // all_jobs
  });

  it('Should read xml of existing job', function(done) {
    expect(jenkins.get_config_xml).to.be.a('function');

    jenkins.get_config_xml(JOB_NAME_TEST, function(error, data) {
      expect(error).to.be.null;
      expect(data).to.be.a('string').that.contains(ORIGINAL_CONFIG);
      done();
    }); // get_config_xml
  });

  it('Should create and delete job', function(done) {
    expect(jenkins.create_job).to.be.a('function');
    expect(jenkins.delete_job).to.be.a('function');

    jenkins.create_job(JOB_NAME_NEW, DEVELOPMENT_PROJECT_XML_CONFIG, function(error, data) {
      expect(error).to.be.null;

      jenkins.all_jobs(function(error, data) {
        expect(error).to.be.null;
        expect(data).to.be.an('array').that.contains.something.like({name: JOB_NAME_NEW});

        jenkins.delete_job(JOB_NAME_NEW, function(error, data) {
          expect(error).to.be.null;

          jenkins.all_jobs(function(error, data) {
            expect(error).to.be.null;
            expect(data).to.be.an('array').that.does.not.contain.something.like({name: JOB_NAME_NEW});

            done();

          }); // all_jobs
        }); // delete_job
      }); // all_jobs
    }); // create_job
  });

  it('Should copy job', function(done) {
    expect(jenkins.copy_job).to.be.a('function');

    jenkins.copy_job(JOB_NAME_TEST, JOB_NAME_COPY, function(data) {
      return data.replace(ORIGINAL_CONFIG, REPLACED_CONFIG);
    }, function(error, data) {
      expect(error).to.be.null;

      jenkins.get_config_xml(JOB_NAME_COPY, function(error, data) {
        expect(error).to.be.null;
        expect(data).to.be.a('string').that.contains(REPLACED_CONFIG);

        jenkins.delete_job(JOB_NAME_COPY, function(error, data) {
          expect(error).to.be.null;
          done();
        }); // delete_job
      }); // get_config_xml
    }); // copy_job
  });

  it('Should update job config', function(done) {
    expect(jenkins.update_config).to.be.a('function');

    jenkins.copy_job(JOB_NAME_TEST, JOB_NAME_COPY, function(data) {
      return data;
    }, function(error, data) {
      expect(error).to.be.null;

      jenkins.update_config(JOB_NAME_COPY, function(data) {
        return data.replace(ORIGINAL_CONFIG, REPLACED_CONFIG);
      }, function(error, data) {
        expect(error).to.be.null;

        jenkins.get_config_xml(JOB_NAME_COPY, function(error, data) {
          expect(error).to.be.null;
          expect(data).to.be.a('string').that.contains(REPLACED_CONFIG);

          jenkins.delete_job(JOB_NAME_COPY, function(error, data) {
            expect(error).to.be.null;
            done();
          }); // delete_job
        }); // get_config_xml
      }); // update_config
    }); // copy_job
  });

  var TEST_VIEW_NAME = 'ewoiurewlkjr-test-view';
  var TEST_VIEW_MODE = 'ewoiurewlkjr-test-view-mode';
  var TEST_VIEW_CONF = {
    name: "view-in-jenkins",
    "description": "This is the view-in-jenkins View",
    "statusFilter": "",
    "job-in-jenkins": true,
    "useincluderegex": true,
    "includeRegex": "prefix.*",
    "columns": [{"stapler-class": "hudson.views.StatusColumn", "$class": "hudson.views.StatusColumn"}, {"stapler-class": "hudson.views.WeatherColumn", "$class": "hudson.views.WeatherColumn"}, {"stapler-class": "hudson.views.JobColumn", "$class": "hudson.views.JobColumn"}, {"stapler-class": "hudson.views.LastSuccessColumn", "$class": "hudson.views.LastSuccessColumn"}, {"stapler-class": "hudson.views.LastFailureColumn", "$class": "hudson.views.LastFailureColumn"}, {"stapler-class": "hudson.views.LastDurationColumn", "$class": "hudson.views.LastDurationColumn"}, {"stapler-class": "hudson.views.BuildButtonColumn", "$class": "hudson.views.BuildButtonColumn"}]
  };

  // TODO handle this better as a test setup
  jenkins.delete_view(TEST_VIEW_NAME);

  it('Should CRUD a view', function(done) {
    expect(jenkins.create_view).to.be.a('function');
    expect(jenkins.all_views).to.be.a('function');
    expect(jenkins.update_view).to.be.a('function');
    expect(jenkins.delete_view).to.be.a('function');
    expect(jenkins.all_jobs_in_view).to.be.a('function');

    jenkins.create_view(TEST_VIEW_NAME, function(error, data) {
      expect(error).to.be.null;
      expect(data).to.be.an('object').like({name: TEST_VIEW_NAME});

      jenkins.all_views(function(error, data) {
        expect(error).to.be.null;
        expect(data).to.be.an('array').that.contains.something.like({name: TEST_VIEW_NAME});

        jenkins.update_view(TEST_VIEW_NAME, TEST_VIEW_CONF, function(error, data) {
          expect(error).to.be.null;

          jenkins.delete_view(TEST_VIEW_NAME, function(error, data) {
            expect(error).to.be.null;
            expect(data).to.be.an('object').like({name: TEST_VIEW_NAME});

            jenkins.all_views(function(error, data) {
              expect(error).to.be.null;
              expect(data).to.be.an('array').that.does.not.contain.something.like({name: TEST_VIEW_NAME});

              done();

            }); // all_views
          }); // delete_view
        }); // update_view
      }); // all_views
    }); // create_view
  });

});
<|endoftext|>


<commit_before>import test from 'ava';

import MarkdownProofing from '../src/lib/main';
import AnalyzerResult from '../src/lib/analyzer-result';

const rootDirOverride = __dirname + '/../src/lib';

class TestAnalyzer1 {
  analyze(/* str */) {
    const result = new AnalyzerResult();

    result.addMessage('test-analyzer-1', 'test-analyzer-1 message.');

    return result;
  }
}

class TestAnalyzer2 {
  analyze(/* str */) {
    const result = new AnalyzerResult();

    result.addMessage('test-analyzer-2', 'test-analyzer-2 message.');

    return result;
  }
}

test('Returns empty messages when no analyzers', t => {
  return new MarkdownProofing()
    .proof('a')
    .then(result => t.is(result.messages.length, 0));
});

test('Returns empty messages with one analyzer and no matching configuration', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .proof(text)
    .then(result => t.is(result.messages.length, 0));
});

test('Returns expected single message with one analyzer with matching configuration rule', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);

      t.is(result.messages[0].type, 'test-analyzer-1');
      t.is(result.messages[0].text, 'test-analyzer-1 message.');
    });
});

test('Returns expected single message with one analyzer added twice with matching configuration rule', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);

      t.is(result.messages[0].type, 'test-analyzer-1');
      t.is(result.messages[0].text, 'test-analyzer-1 message.');
    });
});

test('Returns expected one message from two analyzers with one matching configuration rules', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addAnalyzer(TestAnalyzer2)
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);

      t.is(result.messages[0].type, 'test-analyzer-1');
      t.is(result.messages[0].text, 'test-analyzer-1 message.');
    });
});

test('Returns expected two messages from two analyzers with two matching configuration rules', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addAnalyzer(TestAnalyzer2)
    .addRule('test-analyzer-1', 'info')
    .addRule('test-analyzer-2', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 2);

      t.is(result.messages[0].type, 'test-analyzer-1');
      t.is(result.messages[0].text, 'test-analyzer-1 message.');

      t.is(result.messages[1].type, 'test-analyzer-2');
      t.is(result.messages[1].text, 'test-analyzer-2 message.');
    });
});

test('Returns expected error when warning exists applying error first', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'error')
    .addRule('test-analyzer-1', 'warning')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('Returns expected error when warning exists applying warning first', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'warning')
    .addRule('test-analyzer-1', 'error')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('Returns expected error when info rule condition exists', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'error')
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('Returns expected error when warning and info rule conditions exist', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'error')
    .addRule('test-analyzer-1', 'warning')
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('Returns expected warning when info rule condition exists', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'info')
    .addRule('test-analyzer-1', 'warning')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('createUsingConfiguration adds analyzers', t => {
  const configuration = {
    analyzers: [
      'spelling',
      'statistics'
    ]
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.is(proofing.analyzers.length, 2);
});

test('createUsingConfiguration adds rules', t => {
  const configuration = {
    rules: {
      'statistics-word-count': 'info'
    }
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.is(proofing.rules.length, 1);
});

test('createUsingConfiguration presets adds preset analyzers', t => {
  const configuration = {
    presets: [
      'technical-blog'
    ]
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.true(proofing.analyzers.length > 1);
});

test('createUsingConfiguration presets adds preset rules', t => {
  const configuration = {
    presets: [
      'technical-blog'
    ]
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.true(proofing.rules.length > 1);
});

test('createUsingConfiguration removes rules from preset with none', t => {
  const configuration = {
    presets: [
      'technical-blog'
    ],
    rules: {
      'spelling-error': 'none'
    }
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.false(proofing.rules.some(x => x.messageType === 'spelling-error'));
});
<commit_msg>Fix lint errors<commit_after>import test from 'ava';
import path from 'path';

import MarkdownProofing from '../src/lib/main';
import AnalyzerResult from '../src/lib/analyzer-result';

const rootDirOverride = path.join(__dirname, '/../src/lib');

class TestAnalyzer1 {
  analyze(/* str */) {
    const result = new AnalyzerResult();

    result.addMessage('test-analyzer-1', 'test-analyzer-1 message.');

    return result;
  }
}

class TestAnalyzer2 {
  analyze(/* str */) {
    const result = new AnalyzerResult();

    result.addMessage('test-analyzer-2', 'test-analyzer-2 message.');

    return result;
  }
}

test('Returns empty messages when no analyzers', t => {
  return new MarkdownProofing()
    .proof('a')
    .then(result => t.is(result.messages.length, 0));
});

test('Returns empty messages with one analyzer and no matching configuration', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .proof(text)
    .then(result => t.is(result.messages.length, 0));
});

test('Returns expected single message with one analyzer with matching configuration rule', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);

      t.is(result.messages[0].type, 'test-analyzer-1');
      t.is(result.messages[0].text, 'test-analyzer-1 message.');
    });
});

test('Returns expected single message with one analyzer added twice with matching configuration rule', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);

      t.is(result.messages[0].type, 'test-analyzer-1');
      t.is(result.messages[0].text, 'test-analyzer-1 message.');
    });
});

test('Returns expected one message from two analyzers with one matching configuration rules', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addAnalyzer(TestAnalyzer2)
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);

      t.is(result.messages[0].type, 'test-analyzer-1');
      t.is(result.messages[0].text, 'test-analyzer-1 message.');
    });
});

test('Returns expected two messages from two analyzers with two matching configuration rules', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addAnalyzer(TestAnalyzer2)
    .addRule('test-analyzer-1', 'info')
    .addRule('test-analyzer-2', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 2);

      t.is(result.messages[0].type, 'test-analyzer-1');
      t.is(result.messages[0].text, 'test-analyzer-1 message.');

      t.is(result.messages[1].type, 'test-analyzer-2');
      t.is(result.messages[1].text, 'test-analyzer-2 message.');
    });
});

test('Returns expected error when warning exists applying error first', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'error')
    .addRule('test-analyzer-1', 'warning')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('Returns expected error when warning exists applying warning first', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'warning')
    .addRule('test-analyzer-1', 'error')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('Returns expected error when info rule condition exists', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'error')
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('Returns expected error when warning and info rule conditions exist', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'error')
    .addRule('test-analyzer-1', 'warning')
    .addRule('test-analyzer-1', 'info')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('Returns expected warning when info rule condition exists', t => {
  const text = 'a';

  return new MarkdownProofing()
    .addAnalyzer(TestAnalyzer1)
    .addRule('test-analyzer-1', 'info')
    .addRule('test-analyzer-1', 'warning')
    .proof(text)
    .then(result => {
      t.is(result.messages.length, 1);
      t.is(result.messages[0].type, 'test-analyzer-1');
    });
});

test('createUsingConfiguration adds analyzers', t => {
  const configuration = {
    analyzers: [
      'spelling',
      'statistics'
    ]
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.is(proofing.analyzers.length, 2);
});

test('createUsingConfiguration adds rules', t => {
  const configuration = {
    rules: {
      'statistics-word-count': 'info'
    }
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.is(proofing.rules.length, 1);
});

test('createUsingConfiguration presets adds preset analyzers', t => {
  const configuration = {
    presets: [
      'technical-blog'
    ]
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.true(proofing.analyzers.length > 1);
});

test('createUsingConfiguration presets adds preset rules', t => {
  const configuration = {
    presets: [
      'technical-blog'
    ]
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.true(proofing.rules.length > 1);
});

test('createUsingConfiguration removes rules from preset with none', t => {
  const configuration = {
    presets: [
      'technical-blog'
    ],
    rules: {
      'spelling-error': 'none'
    }
  };

  const proofing = MarkdownProofing.createUsingConfiguration(configuration, rootDirOverride);

  t.false(proofing.rules.some(x => x.messageType === 'spelling-error'));
});
<|endoftext|>


<commit_before>require('pbind')

var $ = require('dom')
  , Alert = require('../')
  , test = require('tape')

test('setup', function(t) {
  $(document.body).append('
'+
    '<button type="button" class="close" data-dismiss="alert">x</button>'+
    '
')

  var a = $('.alert')
  t.ok(a.length, '.alert should exist')
  t.end()
})

test('alert', function(t) {
  t.plan(3)
  var a = $('.alert')
  var al = new Alert(a)
  t.ok(al instanceof Alert, 'al should be instanceof Alert')

  a.on('close.bs.alert', function() {
    t.pass('got close.bs.alert event')
  })

  a.on('closed.bs.alert', function() {
    t.pass('got closed.bs.alert event')
  })

  a.find('[data-dismiss="alert"]').first().emit('click', {
    bubbles: true
  })
})
<commit_msg>Fix test<commit_after>require('pbind')

var $ = require('dom')
  , Alert = require('../')
  , test = require('tape')

test('setup', function(t) {
  $(document.body).append('
'+
    '<button type="button" class="close" data-dismiss="alert">x</button>'+
    '
')

  var a = $('.alert')
  t.ok(a.length, '.alert should exist')
  t.end()
})

test('alert', function(t) {
  t.plan(4)
  var a = $('.alert')
  var al = new Alert(a)
  t.ok(al instanceof Alert, 'al should be instanceof Alert')

  al.on('close.bs.alert', function() {
    t.pass('got close.bs.alert event')
  })

  al.on('closed.bs.alert', function() {
    t.pass('got closed.bs.alert event')
    t.notOk($('.alert').length, '.alert should no longer exist')
  })

  var btn = $('.close')
  btn[0].click()
})
<|endoftext|>


<commit_before>/*global describe, it*/
"use strict";

var fs = require("fs"),
	es = require("event-stream"),
	should = require("should"),
	path = require("path"),
    gutil = require("gulp-util"),
    php2html = require("../");

require("mocha");

var getFile = function(filePath) {
    filePath = 'test/'+filePath;
    return new gutil.File({
        path: filePath,
        cwd: 'test/',
        base: path.dirname(filePath),
        contents: fs.readFileSync(filePath)
    });
};

describe("gulp-php2html", function () {

	it("should create html", function (done) {

		var srcFile = getFile('fixtures/index.php'),
            stream = php2html(),
            valid = 0;

        stream.on("error", function(err) {
            should.not.exist(err);
        });

		stream.on("data", function (newFile) {
            should.exist(newFile);
            should.exist(newFile.path);
            should.exist(newFile.relative);
            should.exist(newFile.contents);
            path.extname(newFile.path).should.equal('.html');
            /<\?php/.test(newFile.contents).should.equal(false);
            ++valid;
		});

        stream.once('end',function(){
            valid.should.equal(1);
            done();
        })

		stream.write(srcFile);
		stream.end();
	});

    it("should use correct PHP environment variables", function(done){
        var stream = php2html(),
            docrootfix = process.platform === 'win32' ? '\\' : '',
            file1 = getFile('env/DOCUMENT_ROOT.php'),
            file2 = getFile('env/PHP_SELF.php'),
            file3 = getFile('env/REQUEST_URI.php'),
            file4 = getFile('env/SCRIPT_NAME.php'),
            file5 = getFile('env/SCRIPT_FILENAME.php'),

            results = {
                'DOCUMENT_ROOT': path.resolve('test'),
                'PHP_SELF': '/test/env/PHP_SELF.php',
                'REQUEST_URI': '/test/env/REQUEST_URI.php',
                'SCRIPT_NAME': '/test/env/SCRIPT_NAME.php',
                'SCRIPT_FILENAME': path.resolve('test/env/SCRIPT_FILENAME.php')
            },

            valid = 0;

        stream.on("data", function (newFile) {
            var ext = path.extname(newFile.path),
                key = path.basename(newFile.path, ext);

            should.exist(newFile);
            should.exist(newFile.path);
            should.exist(newFile.relative);
            should.exist(newFile.contents);
            path.extname(newFile.path).should.equal('.html');
            /<\?php/.test(newFile.contents).should.equal(false);
            newFile.contents.should.equal(results[key]);
            ++valid;
        });

        stream.once('end',function(){
            valid.should.equal(5);
            done();
        });

        stream.write(file1);
        stream.write(file2);
        stream.write(file3);
        stream.write(file4);
        stream.write(file5);

        stream.end();
    });

    it("should throw an error", function(done){
        var srcFile = getFile('fixtures/test.txt'),
            stream = php2html();

        stream.on("error", function(err) {
            should.exist(err);
            done();
        });

        stream.on("data", function (newFile) {
            should.not.exist(newFile);
            done();
        });

        stream.write(srcFile);
        stream.end();
    });

});
<commit_msg>added test for php environment variables<commit_after>/*global describe, it*/
"use strict";

var fs = require("fs"),
	es = require("event-stream"),
	should = require("should"),
	path = require("path"),
    gutil = require("gulp-util"),
    php2html = require("../");

require("mocha");

var getFile = function(filePath) {
    filePath = 'test/'+filePath;
    return new gutil.File({
        path: filePath,
        cwd: 'test/',
        base: path.dirname(filePath),
        contents: fs.readFileSync(filePath)
    });
};

describe("gulp-php2html", function () {

	it("should create html", function (done) {

		var srcFile = getFile('fixtures/index.php'),
            stream = php2html(),
            valid = 0;

        stream.on("error", function(err) {
            should.not.exist(err);
        });

		stream.on("data", function (newFile) {
            should.exist(newFile);
            should.exist(newFile.path);
            should.exist(newFile.relative);
            should.exist(newFile.contents);
            path.extname(newFile.path).should.equal('.html');
            /<\?php/.test(newFile.contents).should.equal(false);
            ++valid;
		});

        stream.once('end',function(){
            valid.should.equal(1);
            done();
        })

		stream.write(srcFile);
		stream.end();
	});

    it("should use correct PHP environment variables", function(done){
        var stream = php2html(),
            docrootfix = process.platform === 'win32' ? '\\' : '',
            file1 = getFile('env/DOCUMENT_ROOT.php'),
            file2 = getFile('env/PHP_SELF.php'),
            file3 = getFile('env/REQUEST_URI.php'),
            file4 = getFile('env/SCRIPT_NAME.php'),
            file5 = getFile('env/SCRIPT_FILENAME.php'),

            results = {
                'DOCUMENT_ROOT': path.resolve('test'),
                'PHP_SELF': '/env/PHP_SELF.php',
                'REQUEST_URI': '/env/REQUEST_URI.php',
                'SCRIPT_NAME': '/env/SCRIPT_NAME.php',
                'SCRIPT_FILENAME': path.resolve('test/env/SCRIPT_FILENAME.php')
            },

            valid = 0;

        stream.on("data", function (newFile) {
            var ext = path.extname(newFile.path),
                key = path.basename(newFile.path, ext);

            should.exist(newFile);
            should.exist(newFile.path);
            should.exist(newFile.relative);
            should.exist(newFile.contents);
            path.extname(newFile.path).should.equal('.html');
            /<\?php/.test(newFile.contents.toString('utf8')).should.equal(false);
            newFile.contents.toString('utf8').should.equal(results[key]);
            ++valid;
        });

        stream.once('end',function(){
            valid.should.equal(5);
            done();
        });

        stream.write(file1);
        stream.write(file2);
        stream.write(file3);
        stream.write(file4);
        stream.write(file5);

        stream.end();
    });

    it("should throw an error", function(done){
        var srcFile = getFile('fixtures/test.txt'),
            stream = php2html();

        stream.on("error", function(err) {
            should.exist(err);
            done();
        });

        stream.on("data", function (newFile) {
            should.not.exist(newFile);
            done();
        });

        stream.write(srcFile);
        stream.end();
    });

});
<|endoftext|>


<commit_before>'use strict';

/* global describe, it */

var assert = require('assert');
var exec = require('child_process').exec;
var fsx = require('fs-extra');
var path = require('path');
var shortid = require('shortid');
var _ = require('lodash');

var buildRpm = require('../');

describe('rpm builder', function() {

  describe('rpm init', function() {

    it('should throw an error if options object is missing', function() {
      assert.throws(buildRpm, TypeError);
    });

    it('should throw an error if options is not an object', function() {
      assert.throws(function() {
        buildRpm('');
      }, TypeError);
    });

    it('should throw an error if callback is missing', function() {
      assert.throws(function() {
        buildRpm({});
      }, TypeError);
    });

    it('should throw an error if callback is not a function', function() {
      assert.throws(function() {
        buildRpm({}, '');
      }, TypeError);
    });

  });

  describe('rpm output', function() {

    it('should keep the temp folder when `keepTemp: true`', function(done) {
      var options = {
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: true
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var tmpDir = path.resolve(options.tempDir);
        assert(fsx.existsSync(tmpDir));

        // remove generated rpm
        fsx.removeSync(path.resolve(rpm));

        // remove temp folder
        fsx.removeSync(tmpDir);

        done();
      });
    });

    it('should remove the temp folder when `keepTemp: false`', function(done) {
      var options = {
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: false
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var tmpDir = path.resolve(options.tempDir);
        assert(!fsx.existsSync(tmpDir));

        // remove generated rpm
        fsx.removeSync(path.resolve(rpm));

        done();
      });
    });

    it('should create a proper rpm folder structure inside the temp dir', function(done) {
      var rpmStructure = ['BUILD', 'BUILDROOT', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS'];
      var options = {
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: true
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var tmpDir = path.resolve(options.tempDir);
        fsx.readdir(tmpDir, function(err, dirs) {
          if (err) {
            throw err;
          }

          assert(_.difference(rpmStructure, dirs).length, 0);

          // remove generated rpm
          fsx.removeSync(path.resolve(rpm));

          // remove temp folder
          fsx.removeSync(tmpDir);

          done();
        });

      });
    });

    it('rpm file should be copied to the current working dir', function(done) {
      var options = {
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: false
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        assert(fsx.existsSync(path.resolve(rpm)));

        // remove generated rpm
        fsx.removeSync(path.resolve(rpm));

        done();
      });
    });

    it('rpm file should have correct name', function(done) {
      var options = {
        name: 'test-name',
        version: '23.02.87',
        release: '28',
        buildArch: 'noarch',
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: false
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var expectedName = options.name + '-' + options.version + '-' + options.release + '.' + options.buildArch + '.rpm';
        var expectedPath = path.dirname(rpm);

        assert(fsx.existsSync(path.join(expectedPath, expectedName)));

        // remove generated rpm
        fsx.removeSync(path.resolve(rpm));

        done();
      });
    });

    it('rpm contents should be consistent with the respective spec file', function(done) {
      var options = {
        name: 'test-name',
        version: '23.02.87',
        release: '28',
        buildArch: 'noarch',
        files: [
          {src: 'index.js', dest: '/dist/'},
          {src: './lib/*', dest: '/dist/'},
          {cwd: './test', src: '*.js', dest: '/dist/'}
        ],
        excludeFiles: [
          './test/main.js'
        ],
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: true
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var cmd = 'rpm -qpl ' + rpm;

        exec(cmd, {}, function rpmContents(err, stdout, stderr) {
          if (err || stderr !== '') {
            err = err || new Error(stderr);
            throw err;
          }

          var contents = stdout.split('\n');
          var specFileName = options.name + '-' + options.version + '-' + options.release + '.' + options.buildArch + '.spec';
          var specFilePath = path.join(options.tempDir, 'SPECS', specFileName);

          fsx.readFile(specFilePath, {encoding: 'utf-8'}, function(err, data) {
            contents.forEach(function(file) {
              assert(data.indexOf(file) > -1);
            });

            // remove temp folder
            fsx.removeSync(path.resolve(options.tempDir));

            // remove generated rpm
            fsx.removeSync(path.resolve(rpm));

            done();
          });
        });
      });
    });

  });

});
<commit_msg>Fix issue with the temp folders when testing<commit_after>'use strict';

/* global describe, it, after */

var assert = require('assert');
var exec = require('child_process').exec;
var fsx = require('fs-extra');
var globby = require('globby');
var path = require('path');
var shortid = require('shortid');
var _ = require('lodash');

var buildRpm = require('../');

describe('rpm builder', function() {

  describe('rpm init', function() {

    it('should throw an error if options object is missing', function() {
      assert.throws(buildRpm, TypeError);
    });

    it('should throw an error if options is not an object', function() {
      assert.throws(function() {
        buildRpm('');
      }, TypeError);
    });

    it('should throw an error if callback is missing', function() {
      assert.throws(function() {
        buildRpm({});
      }, TypeError);
    });

    it('should throw an error if callback is not a function', function() {
      assert.throws(function() {
        buildRpm({}, '');
      }, TypeError);
    });

  });

  describe('rpm output', function() {

    after(function() {
      // remove temp folder left overs
      _.forEach(globby.sync('./rpm-builder-test-*'), function(dir) {
        if (fsx.existsSync(dir)) {
          fsx.removeSync(dir);
        }
      });
    });

    it('should keep the temp folder when `keepTemp: true`', function(done) {
      var options = {
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: true
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var tmpDir = path.resolve(options.tempDir);
        assert(fsx.existsSync(tmpDir));

        // remove generated rpm
        fsx.removeSync(path.resolve(rpm));

        // remove temp folder
        fsx.removeSync(tmpDir);

        done();
      });
    });

    it('should remove the temp folder when `keepTemp: false`', function(done) {
      var options = {
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: false
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var tmpDir = path.resolve(options.tempDir);
        assert(!fsx.existsSync(tmpDir));

        // remove generated rpm
        fsx.removeSync(path.resolve(rpm));

        done();
      });
    });

    it('should create a proper rpm folder structure inside the temp dir', function(done) {
      var rpmStructure = ['BUILD', 'BUILDROOT', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS'];
      var options = {
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: true
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var tmpDir = path.resolve(options.tempDir);
        fsx.readdir(tmpDir, function(err, dirs) {
          if (err) {
            throw err;
          }

          assert(_.difference(rpmStructure, dirs).length, 0);

          // remove generated rpm
          fsx.removeSync(path.resolve(rpm));

          // remove temp folder
          fsx.removeSync(tmpDir);

          done();
        });

      });
    });

    it('rpm file should be copied to the current working dir', function(done) {
      var options = {
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: false
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        assert(fsx.existsSync(path.resolve(rpm)));

        // remove generated rpm
        fsx.removeSync(path.resolve(rpm));

        done();
      });
    });

    it('rpm file should have correct name', function(done) {
      var options = {
        name: 'test-name',
        version: '23.02.87',
        release: '28',
        buildArch: 'noarch',
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: false
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var expectedName = options.name + '-' + options.version + '-' + options.release + '.' + options.buildArch + '.rpm';
        var expectedPath = path.dirname(rpm);

        assert(fsx.existsSync(path.join(expectedPath, expectedName)));

        // remove generated rpm
        fsx.removeSync(path.resolve(rpm));

        done();
      });
    });

    it('rpm contents should be consistent with the respective spec file', function(done) {
      var options = {
        name: 'test-name',
        version: '23.02.87',
        release: '28',
        buildArch: 'noarch',
        files: [
          {src: 'index.js', dest: '/dist/'},
          {src: './lib/*', dest: '/dist/'},
          {cwd: './test', src: '*.js', dest: '/dist/'}
        ],
        excludeFiles: [
          './test/main.js'
        ],
        tempDir: 'rpm-builder-test-tmp-' + shortid.generate(),
        keepTemp: true
      };

      buildRpm(options, function(err, rpm) {
        if (err) {
          throw err;
        }

        var cmd = 'rpm -qpl ' + rpm;

        exec(cmd, {}, function rpmContents(err, stdout, stderr) {
          if (err || stderr !== '') {
            err = err || new Error(stderr);
            throw err;
          }

          var contents = stdout.split('\n');
          var specFileName = options.name + '-' + options.version + '-' + options.release + '.' + options.buildArch + '.spec';
          var specFilePath = path.join(options.tempDir, 'SPECS', specFileName);

          fsx.readFile(specFilePath, {encoding: 'utf-8'}, function(err, data) {
            contents.forEach(function(file) {
              assert(data.indexOf(file) > -1);
            });

            // remove temp folder
            fsx.removeSync(path.resolve(options.tempDir));

            // remove generated rpm
            fsx.removeSync(path.resolve(rpm));

            done();
          });
        });
      });
    });

  });

});
<|endoftext|>


<commit_before>
import '../filter-widget/filter-widget.test';
import '../list-table/list-table.test';
import '../property-table/property-table.test';
import '../data-admin/components/paginate-footer/paginate-footer.test';
import '../data-admin/components/search-control/search-control.test';
import '../data-admin/components/manage-toolbar/manage-toolbar.test';
import '../data-admin/ViewMap.test';
import '../util/string/string.test';
import '../util/field/field.test';
import '../paginate-widget/paginate-widget.test';
import '../form-widget/form-widget.test';
import '../dropdown-menu/dropdown-menu.test';
import '../form-widget/field-components/date-field/date-field.test';
import '../form-widget/field-components/file-field/file-field.test';
import '../form-widget/field-components/json-field/json-field.test';
import '../form-widget/field-components/select-field/select-field.test';
import '../form-widget/field-components/text-field/text-field.test';
import '../modal-dialog/confirm-dialog.test';
import '../modal-dialog/modal-dialog.test';
import '../nav-container/nav-container.test';
<commit_msg>FIX: removes other data-admin component test<commit_after>
import '../filter-widget/filter-widget.test';
import '../list-table/list-table.test';
import '../property-table/property-table.test';
import '../util/string/string.test';
import '../util/field/field.test';
import '../paginate-widget/paginate-widget.test';
import '../form-widget/form-widget.test';
import '../dropdown-menu/dropdown-menu.test';
import '../form-widget/field-components/date-field/date-field.test';
import '../form-widget/field-components/file-field/file-field.test';
import '../form-widget/field-components/json-field/json-field.test';
import '../form-widget/field-components/select-field/select-field.test';
import '../form-widget/field-components/text-field/text-field.test';
import '../modal-dialog/confirm-dialog.test';
import '../modal-dialog/modal-dialog.test';
import '../nav-container/nav-container.test';
<|endoftext|>


<commit_before>"use strict";

describe("path", function () {

    var path = gpf.path;

    function generateTests (separator) {

        var escapedSeparator;
        if (separator === "/") {
            escapedSeparator = separator;
        } else {
            escapedSeparator = "\\\\";
        }

        describe("gpf.path.join (" + separator + ")", function () {

            var join;
            if (separator === "/") {
                join = path.join;
            } else {
                join = function () {
                    var args = Array.from(arguments, function (value) {
                        return value.split("/").join(separator);
                    });
                    return path.join.apply(path, args);
                };
            }

            it("concatenates paths", function () {
                assert(join("abc/def", "ghi/jkl") === "abc/def/ghi/jkl");
            });

            it("handles trailing separator", function () {
                assert(join("abc/def/", "ghi/jkl/") === "abc/def/ghi/jkl");
            });

            it("handles relative paths", function () {
                assert(join("abc/def", "../ghi") === "abc/ghi");
            });

            it("handles multiple joins", function () {
                assert(join("abc", "def", "../ghi", "../jkl") === "abc/jkl");
            });

            it("resolves on known parent", function () {
                assert(join("abc", "../ghi") === "ghi");
            });

            it("goes up with ..", function () {
                assert(join("abc/def", "..") === "abc");
            });

            it("does not resolve on unknown parent", function () {
                assert(join("abc", "../../ghi") === "");
            });

        });

        describe("gpf.path.parent (" + separator + ")", function () {

            it("retrieves the parent path", function () {
                assert(path.parent("abc" + separator + "def") === "abc");
            });

            it("returns empty on a root", function () {
                assert(path.parent(separator + "abc") === "");
            });

            it("returns empty when no parent", function () {
                assert(path.parent("abc") === "");
            });

            it("returns empty when empty", function () {
                assert(path.parent("") === "");
            });

        });

        var Func = Function, // Workaround for W054
            tests = [{
                label: "considers the last name of path",
                path: "abc" + escapedSeparator + "def.ghi",
                name: "def.ghi",
                nameOnly: "def",
                extension: ".ghi"
            }, {
                label: "handles trailing separator",
                path: "abc" + escapedSeparator + "def.ghi" + escapedSeparator,
                name: "def.ghi",
                nameOnly: "def",
                extension: ".ghi"
            }, {
                label: "handles trailing separator (no extension)",
                path: "abc" + escapedSeparator + "def" + escapedSeparator,
                name: "def",
                nameOnly: "def",
                extension: ""
            }, {
                label: "handles name only",
                path: "abc.defgh",
                name: "abc.defgh",
                nameOnly: "abc",
                extension: ".defgh"
            }, {
                label: "handles name only (no extension)",
                path: "abc",
                name: "abc",
                nameOnly: "abc",
                extension: ""
            }, {
                label: "handles root",
                path: "/",
                name: "",
                nameOnly: "",
                extension: ""
            }];

        function buildTestFunc (source) {
            return new Func("assert(gpf.path." + source + ");");
        }

        describe("gpf.path.name (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("name(\"" + item.path + "\") === \"" + item.name + "\""));
            });

        });

        describe("gpf.path.nameOnly (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("nameOnly(\"" + item.path + "\") === \"" + item.nameOnly + "\""));
            });

        });

        describe("gpf.path.extension (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("extension(\"" + item.path + "\") === \"" + item.extension + "\""));
            });

        });

        describe("gpf.path.relative (" + separator + ")", function () {

            var relative;
            if (separator === "/") {
                relative = path.relative;
            } else {
                relative = function () {
                    var args = Array.from(arguments, function (value) {
                        return value.split("/").join(separator);
                    });
                    return path.relative.apply(path, args);
                };
            }

            it("solves the relative path", function () {
                assert(relative("abc/def", "abc/ghi") === "../ghi");
            });

            it("handles trailing separator", function () {
                assert(relative("abc/def/", "abc/ghi") === "../ghi");
            });

            it("works on non matching roots", function () {
                assert(relative("abc/def", "ghi/jkl") === "../../ghi/jkl");
            });

            it("works on non matching roots (any level)", function () {
                assert(relative("a/bc/def", "g/h/i/jkl") === "../../../g/h/i/jkl");
            });

            it("handles edge cases (left empty)", function () {
                assert(relative("", "abc/ghi") === "abc/ghi");
            });

            it("handles edge cases (right empty)", function () {
                assert(relative("abc/ghi", "") === "../..");
            });

            it("handles edge cases (both empty)", function () {
                assert(relative("", "") === "");
            });

        });

    }

    generateTests("/");
    generateTests("\\");

    if (gpf.internals) {

        describe("(internal)", function () {

            describe("_gpfPathNormalize", function () {

                var tests = {
                    "a/": "a",
                    "/a/": "/a",
                    "a/b": "a/b",
                    "a\\b": "a/b",
                    "a\\": "a",
                    "\\a\\": "/a"
                };

                gpf.internals._gpfObjectForEach(tests, function (expected, value) {

                    it("transforms \"" + value + "\" into \"" + expected + "\"", function () {
                        assert(expected === gpf.internals._gpfPathNormalize(value));
                    });

                });

            });

        });

    }

});
<commit_msg>Handles unreachable path error<commit_after>"use strict";

describe("path", function () {

    var path = gpf.path;

    function generateTests (separator) {

        var escapedSeparator;
        if (separator === "/") {
            escapedSeparator = separator;
        } else {
            escapedSeparator = "\\\\";
        }

        describe("gpf.path.join (" + separator + ")", function () {

            var join;
            if (separator === "/") {
                join = path.join;
            } else {
                join = function () {
                    var args = Array.from(arguments, function (value) {
                        return value.split("/").join(separator);
                    });
                    return path.join.apply(path, args);
                };
            }

            it("concatenates paths", function () {
                assert(join("abc/def", "ghi/jkl") === "abc/def/ghi/jkl");
            });

            it("handles trailing separator", function () {
                assert(join("abc/def/", "ghi/jkl/") === "abc/def/ghi/jkl");
            });

            it("handles relative paths", function () {
                assert(join("abc/def", "../ghi") === "abc/ghi");
            });

            it("handles multiple joins", function () {
                assert(join("abc", "def", "../ghi/jkl", "../jkl") === "abc/ghi/jkl");
            });

            it("resolves on known parent", function () {
                assert(join("abc", "../ghi") === "ghi");
            });

            it("goes up with ..", function () {
                assert(join("abc/def", "..") === "abc");
            });

            it("does not resolve on unknown parent", function () {
                var exceptionCaught;
                try {
                    join("abc", "../../ghi");
                } catch (e) {
                    exceptionCaught = e;
                }
                assert(exceptionCaught instanceof gpf.Error.UnreachablePath);
            });

        });

        describe("gpf.path.parent (" + separator + ")", function () {

            it("retrieves the parent path", function () {
                assert(path.parent("abc" + separator + "def") === "abc");
            });

            it("returns empty on a root", function () {
                assert(path.parent(separator + "abc") === "");
            });

            it("returns empty when no parent", function () {
                assert(path.parent("abc") === "");
            });

            it("fails when empty", function () {
                it("does not resolve on unknown parent", function () {
                    var exceptionCaught;
                    try {
                        path.parent("");
                    } catch (e) {
                        exceptionCaught = e;
                    }
                    assert(exceptionCaught instanceof gpf.Error.UnreachablePath);
                });
            });

        });

        var Func = Function, // Workaround for W054
            tests = [{
                label: "considers the last name of path",
                path: "abc" + escapedSeparator + "def.ghi",
                name: "def.ghi",
                nameOnly: "def",
                extension: ".ghi"
            }, {
                label: "handles trailing separator",
                path: "abc" + escapedSeparator + "def.ghi" + escapedSeparator,
                name: "def.ghi",
                nameOnly: "def",
                extension: ".ghi"
            }, {
                label: "handles trailing separator (no extension)",
                path: "abc" + escapedSeparator + "def" + escapedSeparator,
                name: "def",
                nameOnly: "def",
                extension: ""
            }, {
                label: "handles name only",
                path: "abc.defgh",
                name: "abc.defgh",
                nameOnly: "abc",
                extension: ".defgh"
            }, {
                label: "handles name only (no extension)",
                path: "abc",
                name: "abc",
                nameOnly: "abc",
                extension: ""
            }, {
                label: "handles root",
                path: "/",
                name: "",
                nameOnly: "",
                extension: ""
            }];

        function buildTestFunc (source) {
            return new Func("assert(gpf.path." + source + ");");
        }

        describe("gpf.path.name (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("name(\"" + item.path + "\") === \"" + item.name + "\""));
            });

        });

        describe("gpf.path.nameOnly (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("nameOnly(\"" + item.path + "\") === \"" + item.nameOnly + "\""));
            });

        });

        describe("gpf.path.extension (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("extension(\"" + item.path + "\") === \"" + item.extension + "\""));
            });

        });

        describe("gpf.path.relative (" + separator + ")", function () {

            var relative;
            if (separator === "/") {
                relative = path.relative;
            } else {
                relative = function () {
                    var args = Array.from(arguments, function (value) {
                        return value.split("/").join(separator);
                    });
                    return path.relative.apply(path, args);
                };
            }

            it("solves the relative path", function () {
                assert(relative("abc/def", "abc/ghi") === "../ghi");
            });

            it("handles trailing separator", function () {
                assert(relative("abc/def/", "abc/ghi") === "../ghi");
            });

            it("works on non matching roots", function () {
                assert(relative("abc/def", "ghi/jkl") === "../../ghi/jkl");
            });

            it("works on non matching roots (any level)", function () {
                assert(relative("a/bc/def", "g/h/i/jkl") === "../../../g/h/i/jkl");
            });

            it("handles edge cases (left empty)", function () {
                assert(relative("", "abc/ghi") === "abc/ghi");
            });

            it("handles edge cases (right empty)", function () {
                assert(relative("abc/ghi", "") === "../..");
            });

            it("handles edge cases (both empty)", function () {
                assert(relative("", "") === "");
            });

        });

    }

    generateTests("/");
    generateTests("\\");

    if (gpf.internals) {

        describe("(internal)", function () {

            describe("_gpfPathNormalize", function () {

                var tests = {
                    "a/": "a",
                    "/a/": "/a",
                    "a/b": "a/b",
                    "a\\b": "a/b",
                    "a\\": "a",
                    "\\a\\": "/a"
                };

                gpf.internals._gpfObjectForEach(tests, function (expected, value) {

                    it("transforms \"" + value + "\" into \"" + expected + "\"", function () {
                        assert(expected === gpf.internals._gpfPathNormalize(value));
                    });

                });

            });

        });

    }

});
<|endoftext|>


<commit_before>"use strict";
/*jshint mocha: true*/
/*eslint-env mocha*/
/*global assert*/

/*eslint-disable max-nested-callbacks*/

describe("path", function () {

    var path = gpf.path;

    describe("gpf.path.join", function () {

        it("concatenates paths", function () {
            assert(path.join("abc/def", "ghi/jkl") === "abc/def/ghi/jkl");
        });

        it("handles trailing separator", function () {
            assert(path.join("abc/def/", "ghi/jkl/") === "abc/def/ghi/jkl");
        });

        it("handles relative paths", function () {
            assert(path.join("abc/def", "../ghi") === "abc/ghi");
        });

        it("handles multiple joins", function () {
            assert(path.join("abc", "def", "../ghi", "../jkl") === "abc/jkl");
        });

        it("resolves on known parent", function () {
            assert(path.join("abc", "../ghi") === "ghi");
        });

        it("does not resolve on unknown parent", function () {
            assert(path.join("abc", "../../ghi") === "");
        });

    });

    describe("gpf.path.parent", function () {

        it("retrieves the parent path", function () {
            assert(path.parent("abc/def") === "abc");
        });

        it("returns empty on a root", function () {
            assert(path.parent("/abc") === "");
        });

        it("returns empty when no parent", function () {
            assert(path.parent("abc") === "");
        });

    });

    var Func = Function, // Workaround for W054
        tests = [{
            label: "considers the last name of path",
            path: "abc/def.ghi",
            name: "def.ghi",
            nameOnly: "def",
            extension: ".ghi"
        }, {
            label: "handles trailing separator",
            path: "abc/def.ghi/",
            name: "def.ghi",
            nameOnly: "def",
            extension: ".ghi"
        }, {
            label: "handles trailing separator (no extension)",
            path: "abc/def/",
            name: "def",
            nameOnly: "def",
            extension: ""
        }, {
            label: "handles name only",
            path: "abc.defgh",
            name: "abc.defgh",
            nameOnly: "abc",
            extension: ".defgh"
        }, {
            label: "handles name only (no extension)",
            path: "abc",
            name: "abc",
            nameOnly: "abc",
            extension: ""
        }, {
            label: "handles root",
            path: "/",
            name: "",
            nameOnly: "",
            extension: ""
        }];

    function buildTestFunc (source) {
        return new Func("assert(gpf.path." + source + ");");
    }

    describe("gpf.path.name", function () {

        tests.forEach(function (item) {
            it(item.label, buildTestFunc("name(\"" + item.path + "\") === \"" + item.name + "\""));
        });

    });

    describe("gpf.path.nameOnly", function () {

        tests.forEach(function (item) {
            it(item.label, buildTestFunc("nameOnly(\"" + item.path + "\") === \"" + item.nameOnly + "\""));
        });

    });

    describe("gpf.path.extension", function () {

        tests.forEach(function (item) {
            it(item.label, buildTestFunc("extension(\"" + item.path + "\") === \"" + item.extension + "\""));
        });

    });

    describe("gpf.path.relative", function () {

        it("solves the relative path", function () {
            assert(path.relative("abc/def", "abc/ghi") === "../ghi");
        });

        it("handles trailing separator", function () {
            assert(path.relative("abc/def/", "abc/ghi") === "../ghi");
        });

        it("works on non matching roots", function () {
            assert(path.relative("abc/def", "ghi/jkl") === "../../ghi/jkl");
        });

        it("works on non matching roots (any level)", function () {
            assert(path.relative("a/bc/def", "g/h/i/jkl") === "../../../g/h/i/jkl");
        });

    });

});
<commit_msg>Improved coverage<commit_after>"use strict";
/*jshint mocha: true*/
/*eslint-env mocha*/
/*global assert*/

/*eslint-disable max-nested-callbacks*/

describe("path", function () {

    var path = gpf.path;

    function generateTests (separator) {

        var escapedSeparator;
        if (separator === "/") {
            escapedSeparator = separator;
        } else {
            escapedSeparator = "\\\\";
        }

        describe("gpf.path.join (" + separator + ")", function () {

            var join;
            if (separator === "/") {
                join = path.join;
            } else {
                join = function () {
                    var args = [].slice.apply(arguments, [0]).map(function (value) {
                        return value.split("/").join(separator);
                    });
                    return path.join.apply(path, args);
                };
            }

            it("concatenates paths", function () {
                assert(join("abc/def", "ghi/jkl") === "abc/def/ghi/jkl");
            });

            it("handles trailing separator", function () {
                assert(join("abc/def/", "ghi/jkl/") === "abc/def/ghi/jkl");
            });

            it("handles relative paths", function () {
                assert(join("abc/def", "../ghi") === "abc/ghi");
            });

            it("handles multiple joins", function () {
                assert(join("abc", "def", "../ghi", "../jkl") === "abc/jkl");
            });

            it("resolves on known parent", function () {
                assert(join("abc", "../ghi") === "ghi");
            });

            it("goes up with ..", function () {
                assert(join("abc/def", "..") === "abc");
            });

            it("does not resolve on unknown parent", function () {
                assert(join("abc", "../../ghi") === "");
            });

        });

        describe("gpf.path.parent (" + separator + ")", function () {

            it("retrieves the parent path", function () {
                assert(path.parent("abc" + separator + "def") === "abc");
            });

            it("returns empty on a root", function () {
                assert(path.parent(separator + "abc") === "");
            });

            it("returns empty when no parent", function () {
                assert(path.parent("abc") === "");
            });

            it("returns empty when empty", function () {
                assert(path.parent("") === "");
            });

        });

        var Func = Function, // Workaround for W054
            tests = [{
                label: "considers the last name of path",
                path: "abc" + escapedSeparator + "def.ghi",
                name: "def.ghi",
                nameOnly: "def",
                extension: ".ghi"
            }, {
                label: "handles trailing separator",
                path: "abc" + escapedSeparator + "def.ghi" + escapedSeparator,
                name: "def.ghi",
                nameOnly: "def",
                extension: ".ghi"
            }, {
                label: "handles trailing separator (no extension)",
                path: "abc" + escapedSeparator + "def" + escapedSeparator,
                name: "def",
                nameOnly: "def",
                extension: ""
            }, {
                label: "handles name only",
                path: "abc.defgh",
                name: "abc.defgh",
                nameOnly: "abc",
                extension: ".defgh"
            }, {
                label: "handles name only (no extension)",
                path: "abc",
                name: "abc",
                nameOnly: "abc",
                extension: ""
            }, {
                label: "handles root",
                path: "/",
                name: "",
                nameOnly: "",
                extension: ""
            }];

        function buildTestFunc (source) {
            return new Func("assert(gpf.path." + source + ");");
        }

        describe("gpf.path.name (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("name(\"" + item.path + "\") === \"" + item.name + "\""));
            });

        });

        describe("gpf.path.nameOnly (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("nameOnly(\"" + item.path + "\") === \"" + item.nameOnly + "\""));
            });

        });

        describe("gpf.path.extension (" + separator + ")", function () {

            tests.forEach(function (item) {
                it(item.label, buildTestFunc("extension(\"" + item.path + "\") === \"" + item.extension + "\""));
            });

        });

        describe("gpf.path.relative (" + separator + ")", function () {

            var relative;
            if (separator === "/") {
                relative = path.relative;
            } else {
                relative = function () {
                    var args = [].slice.apply(arguments, [0]).map(function (value) {
                        return value.split("/").join(separator);
                    });
                    return path.relative.apply(path, args);
                };
            }

            it("solves the relative path", function () {
                assert(relative("abc/def", "abc/ghi") === "../ghi");
            });

            it("handles trailing separator", function () {
                assert(relative("abc/def/", "abc/ghi") === "../ghi");
            });

            it("works on non matching roots", function () {
                assert(relative("abc/def", "ghi/jkl") === "../../ghi/jkl");
            });

            it("works on non matching roots (any level)", function () {
                assert(relative("a/bc/def", "g/h/i/jkl") === "../../../g/h/i/jkl");
            });

        });

    }

    generateTests("/");
    generateTests("\\");

});
<|endoftext|>


<commit_before>import * as Weights from "./Weights.js";

export { Params, Layer };

/**
 * Embedding (2D) layer parameters.
 */
class Params extends Weights.Params {

  /**
   * @param {number} channelMultiplier
   *   Every input channel will be expanded into so many embedding channels. This is also vocabulary count
   * per input channel (or, vocabulary count per vocabulary table). Every input channel will have a
   * vocabulary table. If channelMultiplier is null, it will be extracted from inputFloat32Array
   * (i.e. by evolution). The outChannels (output channel count) is always depending on channelMultiplier
   * and equal to ( inChannels * channelMultiplier ).
   *
   * @return {boolean} Return false, if initialization failed.
   *
   * @override
   */
  init( inputFloat32Array, byteOffsetBegin, inChannels, channelMultiplier = null ) {

    // Except channelMultiplier, no parameter needs to be extract and convert (to positive integer).
    let parameterCountAtLeast = 0;

    // For an embedding layer, its output channel count is always depeding on channelMultiplier.
    let outChannels = Number.POSITIVE_INFINITY;

    return super.init( inputFloat32Array, byteOffsetBegin, parameterCountAtLeast, inChannels, channelMultiplier, outChannels );
  }

}

/**
 * An embedding layer contains one params (this.params) and inChannels embedding vocabulary tables.
 * Every input channel uses one embedding vocabulary table. Every embedding vocabulary table has
 * vocabularyCountPerInputChannel vocabularies. Every vocabulary has outChannels embedding channels.
 */
class Layer {

  /**
   * @param {Float32Array} inputFloat32Array
   *   A Float32Array whose values will be interpret as weights.
   *
   * @param {number}       byteOffsetBegin
   *   The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
   * (not to the inputFloat32Array.byteOffset).
   *
   * @param {number}       inChannels
   *   The input channel count.
   *
   * @param {number} outChannels
   *   If not null, this is the output channel count. Otherwise (i.e. null), the last element of this.weightsModified[]
   * which are extracted from inputFloat32Array (or fixedWeights) will be the output channel count.
   *
   * @param {number} vocabularyCountPerInputChannel
   *
   *
   *
   * @param {number} channelMultiplier
   *
   *
   *
   * @param {Array} fixedParams
   *   If null, extract 1 parameter from inputFloat32Array. If not null, extract 1 parameter from it instead of
   * inputFloat32Array. If not null, it should have 1 elements: [ channelMultiplier ].
   */
  init( inputFloat32Array, byteOffsetBegin, inChannels, vocabularyCountPerInputChannel, channelMultiplier = null ) {

    let outChannels = null;
    let fixedParams = null;
    if ( channelMultiplier ) {
      outChannels = inChannels * channelMultiplier;
      fixedParams = [ channelMultiplier ];
    }

    this.params = new Params( inputFloat32Array, byteOffsetBegin, inChannels, outChannels, fixedParams );
    if ( !this.params.isValid() )
      return;

//!!!
//  get vocabularyCountPerInputChannel()   { return this.weightsModified[ 0 ]; }

    this.depthwise = new Weights.Base(
      inputFloat32Array, this.params.defaultByteOffsetEnd, null, 0,
      [this.params.filterHeight, this.params.filterWidth, inChannels, this.params.channelMultiplier] );

    if ( !this.depthwise.isValid() )
      return;

    this.depthwiseBias = new Weights.Base(
      inputFloat32Array, this.depthwise.defaultByteOffsetEnd, null, 0,
      [1, 1, inChannels, this.params.channelMultiplier] );

    if ( !this.depthwiseBias.isValid() )
      return;

    this.pointwise = new Weights.Base(
      inputFloat32Array, this.depthwiseBias.defaultByteOffsetEnd, null, 0,
      [1, 1, inChannels * this.params.channelMultiplier, this.params.outChannels] );

    if ( !this.pointwise.isValid() )
      return;

    this.pointwiseBias = new Weights.Base(
      inputFloat32Array, this.pointwise.defaultByteOffsetEnd, null, 0,
      [1, 1, this.params.outChannels] );
  }

  isValid() {
    if ( this.pointwiseBias )
      if ( this.pointwiseBias.isValid() )
        return true;
    return false;
  }

  get byteOffsetBegin() { return this.params.byteOffsetBegin; }
  get byteOffsetEnd()   { return this.pointwiseBias.byteOffsetEnd; }
}
<commit_msg>Update Embedding2D.js<commit_after>import * as Weights from "./Weights.js";

export { Params, Layer };

/**
 * Embedding (2D) layer parameters.
 */
class Params extends Weights.Params {

  /**
   * @param {number} channelMultiplier
   *   Every input channel will be expanded into so many embedding channels. This is also vocabulary count
   * per input channel (or, vocabulary count per vocabulary table). Every input channel will have a
   * vocabulary table. If channelMultiplier is null, it will be extracted from inputFloat32Array
   * (i.e. by evolution). The outChannels (output channel count) is always depending on channelMultiplier
   * and equal to ( inChannels * channelMultiplier ).
   *
   * @return {boolean} Return false, if initialization failed.
   *
   * @override
   */
  init( inputFloat32Array, byteOffsetBegin, inChannels, channelMultiplier = null ) {

//!!! inverted residual connection (by concatenate) ?

    // Except channelMultiplier, no parameter needs to be extract and convert (to positive integer).
    let parameterCountAtLeast = 0;

    // For an embedding layer, its output channel count is always depeding on channelMultiplier.
    let outChannels = Number.POSITIVE_INFINITY;

    return super.init( inputFloat32Array, byteOffsetBegin, parameterCountAtLeast, inChannels, channelMultiplier, outChannels );
  }

}

/**
 * An embedding layer contains one params (this.params) and inChannels embedding vocabulary tables.
 * Every input channel uses one embedding vocabulary table. Every embedding vocabulary table has
 * vocabularyCountPerInputChannel vocabularies. Every vocabulary has outChannels embedding channels.
 */
class Layer {

  /**
   * @param {Float32Array} inputFloat32Array
   *   A Float32Array whose values will be interpret as weights.
   *
   * @param {number}       byteOffsetBegin
   *   The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
   * (not to the inputFloat32Array.byteOffset).
   *
   * @param {number}       inChannels
   *   The input channel count.
   *
   * @param {number} outChannels
   *   If not null, this is the output channel count. Otherwise (i.e. null), the last element of this.weightsModified[]
   * which are extracted from inputFloat32Array (or fixedWeights) will be the output channel count.
   *
   * @param {number} vocabularyCountPerInputChannel
   *
   *
   *
   * @param {number} channelMultiplier
   *
   *
   *
   * @param {Array} fixedParams
   *   If null, extract 1 parameter from inputFloat32Array. If not null, extract 1 parameter from it instead of
   * inputFloat32Array. If not null, it should have 1 elements: [ channelMultiplier ].
   */
  init( inputFloat32Array, byteOffsetBegin, inChannels, vocabularyCountPerInputChannel, channelMultiplier = null ) {

    let outChannels = null;
    let fixedParams = null;
    if ( channelMultiplier ) {
      outChannels = inChannels * channelMultiplier;
      fixedParams = [ channelMultiplier ];
    }

    this.params = new Params( inputFloat32Array, byteOffsetBegin, inChannels, outChannels, fixedParams );
    if ( !this.params.isValid() )
      return;

//!!!
//  get vocabularyCountPerInputChannel()   { return this.weightsModified[ 0 ]; }

    this.depthwise = new Weights.Base(
      inputFloat32Array, this.params.defaultByteOffsetEnd, null, 0,
      [this.params.filterHeight, this.params.filterWidth, inChannels, this.params.channelMultiplier] );

    if ( !this.depthwise.isValid() )
      return;

    this.depthwiseBias = new Weights.Base(
      inputFloat32Array, this.depthwise.defaultByteOffsetEnd, null, 0,
      [1, 1, inChannels, this.params.channelMultiplier] );

    if ( !this.depthwiseBias.isValid() )
      return;

    this.pointwise = new Weights.Base(
      inputFloat32Array, this.depthwiseBias.defaultByteOffsetEnd, null, 0,
      [1, 1, inChannels * this.params.channelMultiplier, this.params.outChannels] );

    if ( !this.pointwise.isValid() )
      return;

    this.pointwiseBias = new Weights.Base(
      inputFloat32Array, this.pointwise.defaultByteOffsetEnd, null, 0,
      [1, 1, this.params.outChannels] );
  }

  isValid() {
    if ( this.pointwiseBias )
      if ( this.pointwiseBias.isValid() )
        return true;
    return false;
  }

  get byteOffsetBegin() { return this.params.byteOffsetBegin; }
  get byteOffsetEnd()   { return this.pointwiseBias.byteOffsetEnd; }
}
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert')
  , lib = require('../lib/hashmap.js')
  , hashmap;

beforeEach(function(done){
  hashmap = new lib.Hashmap();
  done();
});

describe('Hashmap implementation', function () {

  it('should return how many items are present with computed property', function () {
    assert.equal(hashmap.size, 0);
  });

  it('should be illegal to set hashmap size', function () {
    var throws = false;
    try {
      hashmap.size = 42;
    } catch (e) {
      throws = true;
    }

    assert.equal(throws, true);
  });

  it('should return undefined if key is not present', function () {
    var item = hashmap.get('Hello');
    assert.equal(item, undefined);
  });

  // Numeric type
  // ------------

  it('should set a number as a key and increase stored objects', function () {
    hashmap.put(0, 'Hello world');
    assert.equal(hashmap.size, 1);
  });

  it('should delete a number key and decrease stored objects', function () {
    hashmap.put(0, 'Hello world');
    assert.equal(hashmap.size, 1);
    hashmap.remove(0);
    assert.equal(hashmap.size, 0);
  });

  it('should return an item with number key', function () {
    hashmap.put(0, 'Hello world');
    var item = hashmap.get(0);
    assert.equal(item, 'Hello world');
  });

  it('should update an item with number key', function () {
    var item;
    hashmap.put(0, [1, 2, 3]);
    item = hashmap.get(0);
    assert.deepEqual(item, [1, 2, 3]);

    hashmap.put(0, {answer: '42'});
    item = hashmap.get(0);
    assert.deepEqual(item, {answer: '42'});
  });

  // String type
  // -----------

  it('should set a string as a key and increase stored objects', function () {
    hashmap.put('Hello', 'World');
    assert.equal(hashmap.size, 1);
  });

  it('should delete a string key and decrease stored objects', function () {
    hashmap.put('Hello', 'World');
    assert.equal(hashmap.size, 1);
    hashmap.remove('Hello');
    assert.equal(hashmap.size, 0);
  });

  it('should return an item with string key', function () {
    hashmap.put('Hello', 'World');
    var item = hashmap.get('Hello');
    assert.equal(item, 'World');
  });

  it('should update an item with string key', function () {
    var item;
    hashmap.put('answer', 0);
    item = hashmap.get('answer');
    assert.equal(item, 0);

    hashmap.put('answer', 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
    item = hashmap.get('answer');
    assert.equal(item, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
  });

  // Array type
  // ----------

  it('should set an array as a key and increase stored objects', function () {
    var array = [1, 2, 3];
    hashmap.put(array, 'This is a plain array');
    assert.equal(hashmap.size, 1);
  });

  it('should delete an array key and decrease stored objects', function () {
    var array = [1, 2, 3];
    hashmap.put(array, 'This is a plain array');
    assert.equal(hashmap.size, 1);

    hashmap.remove(array);
    assert.equal(hashmap.size, 0);
  });

  it('should return an item with array key', function () {
    var array = [1, 2, 3];
    hashmap.put(array, 'This is a plain array');
    var item = hashmap.get(array);
    assert.equal(item, 'This is a plain array');
  });

  it('should update an item with array key', function () {
    var item;
    var array = [1, 2, 3];
    hashmap.put(array, 'This is a plain array');

    item = hashmap.get(array);
    assert.equal(item, 'This is a plain array');

    hashmap.put(array, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
    item = hashmap.get(array);
    assert.equal(item, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
  });

  // Object
  // ------

  it('should set an object as a key and increase stored objects', function () {
    var object = {hello: 'Hello world!'};
    hashmap.put(object, 'This is a plain object');
    assert.equal(hashmap.size, 1);
  });

  it('should delete an object key and decrease stored objects', function () {
    var object = {hello: 'Hello world!'};
    hashmap.put(object, 'This is a plain object');
    assert.equal(hashmap.size, 1);

    hashmap.remove(object);
    assert.equal(hashmap.size, 0);
  });

  it('should return an item with object key', function () {
    var object = {hello: 'Hello world!'};
    hashmap.put(object, 'This is a plain object');
    var item = hashmap.get(object);
    assert.equal(item, 'This is a plain object');
  });

  it('should update an item with object key', function () {
    var item;
    var object = {hello: 'Hello world!'};
    hashmap.put(object, 'This is a plain object');

    item = hashmap.get(object);
    assert.equal(item, 'This is a plain object');

    hashmap.put(object, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
    item = hashmap.get(object);
    assert.equal(item, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
  });

  it('should store two objects even if they are \'similiar\'', function () {
    var firstObject = {hello: 'Hello world!'};
    var secondObject = {hello: 'Hello world!'};

    hashmap.put(firstObject, 'First object');
    hashmap.put(secondObject, 'Second object');
    assert.equal(hashmap.size, 2);
    assert.equal(hashmap.get(firstObject), 'First object');
    assert.equal(hashmap.get(secondObject), 'Second object');
  });
});
<commit_msg>minor edit on tests<commit_after>'use strict';

var assert = require('assert')
  , Hashmap = require('../lib/hashmap.js').Hashmap
  , hashmap;

beforeEach(function(done){
  hashmap = new Hashmap();
  done();
});

describe('Hashmap implementation', function () {

  it('should return how many items are present with computed property', function () {
    assert.equal(hashmap.size, 0);
  });

  it('should be illegal to set hashmap size', function () {
    var throws = false;
    try {
      hashmap.size = 42;
    } catch (e) {
      throws = true;
    }

    assert.equal(throws, true);
  });

  it('should return undefined if key is not present', function () {
    var item = hashmap.get('Hello');
    assert.equal(item, undefined);
  });

  // Numeric type
  // ------------

  it('should set a number as a key and increase stored objects', function () {
    hashmap.put(0, 'Hello world');
    assert.equal(hashmap.size, 1);
  });

  it('should delete a number key and decrease stored objects', function () {
    hashmap.put(0, 'Hello world');
    assert.equal(hashmap.size, 1);
    hashmap.remove(0);
    assert.equal(hashmap.size, 0);
  });

  it('should return an item with number key', function () {
    hashmap.put(0, 'Hello world');
    var item = hashmap.get(0);
    assert.equal(item, 'Hello world');
  });

  it('should update an item with number key', function () {
    var item;
    hashmap.put(0, [1, 2, 3]);
    item = hashmap.get(0);
    assert.deepEqual(item, [1, 2, 3]);

    hashmap.put(0, {answer: '42'});
    item = hashmap.get(0);
    assert.deepEqual(item, {answer: '42'});
  });

  // String type
  // -----------

  it('should set a string as a key and increase stored objects', function () {
    hashmap.put('Hello', 'World');
    assert.equal(hashmap.size, 1);
  });

  it('should delete a string key and decrease stored objects', function () {
    hashmap.put('Hello', 'World');
    assert.equal(hashmap.size, 1);
    hashmap.remove('Hello');
    assert.equal(hashmap.size, 0);
  });

  it('should return an item with string key', function () {
    hashmap.put('Hello', 'World');
    var item = hashmap.get('Hello');
    assert.equal(item, 'World');
  });

  it('should update an item with string key', function () {
    var item;
    hashmap.put('answer', 0);
    item = hashmap.get('answer');
    assert.equal(item, 0);

    hashmap.put('answer', 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
    item = hashmap.get('answer');
    assert.equal(item, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
  });

  // Array type
  // ----------

  it('should set an array as a key and increase stored objects', function () {
    var array = [1, 2, 3];
    hashmap.put(array, 'This is a plain array');
    assert.equal(hashmap.size, 1);
  });

  it('should delete an array key and decrease stored objects', function () {
    var array = [1, 2, 3];
    hashmap.put(array, 'This is a plain array');
    assert.equal(hashmap.size, 1);

    hashmap.remove(array);
    assert.equal(hashmap.size, 0);
  });

  it('should return an item with array key', function () {
    var array = [1, 2, 3];
    hashmap.put(array, 'This is a plain array');
    var item = hashmap.get(array);
    assert.equal(item, 'This is a plain array');
  });

  it('should update an item with array key', function () {
    var item;
    var array = [1, 2, 3];
    hashmap.put(array, 'This is a plain array');

    item = hashmap.get(array);
    assert.equal(item, 'This is a plain array');

    hashmap.put(array, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
    item = hashmap.get(array);
    assert.equal(item, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
  });

  // Object
  // ------

  it('should set an object as a key and increase stored objects', function () {
    var object = {hello: 'Hello world!'};
    hashmap.put(object, 'This is a plain object');
    assert.equal(hashmap.size, 1);
  });

  it('should delete an object key and decrease stored objects', function () {
    var object = {hello: 'Hello world!'};
    hashmap.put(object, 'This is a plain object');
    assert.equal(hashmap.size, 1);

    hashmap.remove(object);
    assert.equal(hashmap.size, 0);
  });

  it('should return an item with object key', function () {
    var object = {hello: 'Hello world!'};
    hashmap.put(object, 'This is a plain object');
    var item = hashmap.get(object);
    assert.equal(item, 'This is a plain object');
  });

  it('should update an item with object key', function () {
    var item;
    var object = {hello: 'Hello world!'};
    hashmap.put(object, 'This is a plain object');

    item = hashmap.get(object);
    assert.equal(item, 'This is a plain object');

    hashmap.put(object, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
    item = hashmap.get(object);
    assert.equal(item, 'The Answer to the Ultimate Question of Life, The Universe, and Everything');
  });

  it('should store two objects even if they are \'similiar\'', function () {
    var firstObject = {hello: 'Hello world!'};
    var secondObject = {hello: 'Hello world!'};

    hashmap.put(firstObject, 'First object');
    hashmap.put(secondObject, 'Second object');
    assert.equal(hashmap.size, 2);
    assert.equal(hashmap.get(firstObject), 'First object');
    assert.equal(hashmap.get(secondObject), 'Second object');
  });
});
<|endoftext|>


<commit_before>/*jshint node:true, mocha:true */

'use strict';

require('should');

var adapter = require('floating-adapter');
var Decimal = require('core-arbitrary-precision')(adapter);

Decimal = require('../src/')(Decimal);

describe('plus', function() {
  it('should add a given number', function() {
    new Decimal('3').minus(new Decimal('2')).toString().should.be.exactly('1');
  });
});
<commit_msg>tes: fix descriptions<commit_after>/*jshint node:true, mocha:true */

'use strict';

require('should');

var adapter = require('floating-adapter');
var Decimal = require('core-arbitrary-precision')(adapter);

Decimal = require('../src/')(Decimal);

describe('minus', function() {
  it('should subtract a given number', function() {
    new Decimal('3').minus(new Decimal('2')).toString().should.be.exactly('1');
  });
});
<|endoftext|>