<commit_before>/* eslint-env node, mocha */
/* eslint-disable no-console */
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const expect = require('chai').expect;
const fs = require('fs');
const sass = require('node-sass');

const selectorImporter = require('../');
const SelectorImporterClass = require('../dist/SelectorImporter.js');

chai.use(chaiAsPromised);

/** @test {index} */
describe('selectorImporter', () => {
  it('should be a function', () => expect(selectorImporter).to.be.a('function'));

  it('should resolve selector import', (done) => {
    const expectedResult = fs.readFileSync('test/files/importer-reference.css', {
      encoding: 'utf8'
    });
    sass.render({
      file: 'test/files/importer.scss',
      importer: selectorImporter
    }, (error, result) => {
      if (!error) {
        expect(result.css.toString()).to.equal(expectedResult);
        done();
      } else {
        console.log(error);
      }
    });
  });
});

/** @test {SelectorImporter} */
describe('SelectorImporterClass', () => {
  it('should be a function', () => expect(SelectorImporterClass).to.be.a('function'));

  /** @test {SelectorImporter#cleanUrl} */
  describe('cleanUrl()', () => {
    it('should return the url unmodified', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'normal/path/without/tilde';
      const expectedResult = url;
      return expect(selectorImporterInstance.cleanUrl(url)).to.equal(expectedResult);
    });

    it('should return the unmodified home path relative url', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = '~/home/path/with/tilde';
      const expectedResult = url;
      return expect(selectorImporterInstance.cleanUrl(url)).to.equal(expectedResult);
    });

    it('should return a cleaned up url without tilde', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = '~path/with/tilde';
      const expectedResult = 'path/with/tilde';
      return expect(selectorImporterInstance.cleanUrl(url)).to.equal(expectedResult);
    });
  });

  /** @test {SelectorImporter#parseUrl} */
  describe('parseUrl()', () => {
    it('should return object with url and empty selector filters', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'path/without/selector/filters.scss';
      const expectedResult = {
        url,
        selectorFilters: undefined
      };
      return expect(selectorImporterInstance.parseUrl(url)).to.deep.equal(expectedResult);
    });

    it('should return object with url and selector filters', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'path/with/selector/filters.scss';
      const selectorFilters = [
        ['.selector1'],
        ['.selector2']
      ];
      const selectorFilterString = selectorFilters.map((x) => x.join(' as ')).join(', ');
      const urlWithSelectorFilters = `{ ${selectorFilterString} } from ${url}`;
      const expectedResult = {
        url,
        selectorFilters
      };
      return expect(selectorImporterInstance.parseUrl(urlWithSelectorFilters))
        .to.deep.equal(expectedResult);
    });

    it('should return object with url and selector filters with replacements', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'path/with/selector/filters/and/replacements.scss';
      const selectorFilters = [
        ['.selector1', '.replacement1'],
        ['.selector2', '.replacement1']
      ];
      const selectorFilterString = selectorFilters.map((x) => x.join(' as ')).join(', ');
      const urlWithSelectorFilters = `{ ${selectorFilterString} } from ${url}`;
      const expectedResult = {
        url,
        selectorFilters
      };
      return expect(selectorImporterInstance.parseUrl(urlWithSelectorFilters))
        .to.deep.equal(expectedResult);
    });
  });

  /** @test {SelectorImporter#resolve} */
  describe('resolve()', () => {
    it('should return null', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'path/without/selector/filters.scss';
      const expectedResult = null;
      return expect(selectorImporterInstance.resolve(url)).to.eventually.equal(expectedResult);
    });

    it('should return selector filtered contents', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = '{ .class1 as .class-1, .class3 as .class-3 } from test/files/resolve.scss';
      const expectedResult = fs.readFileSync('test/files/resolve-reference.css', {
        encoding: 'utf8'
      });
      return expect(selectorImporterInstance.resolve(url)).to.eventually.equal(expectedResult);
    });
  });
});
<commit_msg>Add "should be function" tests and add a new testcase for the resolveSync() method, fixes #7<commit_after>/* eslint-env node, mocha */
/* eslint-disable no-console */
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const expect = require('chai').expect;
const fs = require('fs');
const sass = require('node-sass');

const selectorImporter = require('../');
const SelectorImporterClass = require('../dist/SelectorImporter.js');

chai.use(chaiAsPromised);

/** @test {index} */
describe('selectorImporter', () => {
  it('should be a function', () => expect(selectorImporter).to.be.a('function'));

  it('should resolve selector import', (done) => {
    const expectedResult = fs.readFileSync('test/files/importer-reference.css', {
      encoding: 'utf8'
    });
    sass.render({
      file: 'test/files/importer.scss',
      importer: selectorImporter
    }, (error, result) => {
      if (!error) {
        expect(result.css.toString()).to.equal(expectedResult);
        done();
      } else {
        console.log(error);
      }
    });
  });
});

/** @test {SelectorImporter} */
describe('SelectorImporterClass', () => {
  it('should be a function', () => expect(SelectorImporterClass).to.be.a('function'));

  /** @test {SelectorImporter#cleanUrl} */
  describe('cleanUrl()', () => {
    it('should be a function', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      expect(selectorImporterInstance.cleanUrl).to.be.a('function');
    });

    it('should return the url unmodified', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'normal/path/without/tilde';
      const expectedResult = url;
      return expect(selectorImporterInstance.cleanUrl(url)).to.equal(expectedResult);
    });

    it('should return the unmodified home path relative url', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = '~/home/path/with/tilde';
      const expectedResult = url;
      return expect(selectorImporterInstance.cleanUrl(url)).to.equal(expectedResult);
    });

    it('should return a cleaned up url without tilde', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = '~path/with/tilde';
      const expectedResult = 'path/with/tilde';
      return expect(selectorImporterInstance.cleanUrl(url)).to.equal(expectedResult);
    });
  });

  /** @test {SelectorImporter#parseUrl} */
  describe('parseUrl()', () => {
    it('should be a function', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      expect(selectorImporterInstance.parseUrl).to.be.a('function');
    });

    it('should return object with url and empty selector filters', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'path/without/selector/filters.scss';
      const expectedResult = {
        url,
        selectorFilters: undefined
      };
      return expect(selectorImporterInstance.parseUrl(url)).to.deep.equal(expectedResult);
    });

    it('should return object with url and selector filters', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'path/with/selector/filters.scss';
      const selectorFilters = [
        ['.selector1'],
        ['.selector2']
      ];
      const selectorFilterString = selectorFilters.map((x) => x.join(' as ')).join(', ');
      const urlWithSelectorFilters = `{ ${selectorFilterString} } from ${url}`;
      const expectedResult = {
        url,
        selectorFilters
      };
      return expect(selectorImporterInstance.parseUrl(urlWithSelectorFilters))
        .to.deep.equal(expectedResult);
    });

    it('should return object with url and selector filters with replacements', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'path/with/selector/filters/and/replacements.scss';
      const selectorFilters = [
        ['.selector1', '.replacement1'],
        ['.selector2', '.replacement1']
      ];
      const selectorFilterString = selectorFilters.map((x) => x.join(' as ')).join(', ');
      const urlWithSelectorFilters = `{ ${selectorFilterString} } from ${url}`;
      const expectedResult = {
        url,
        selectorFilters
      };
      return expect(selectorImporterInstance.parseUrl(urlWithSelectorFilters))
        .to.deep.equal(expectedResult);
    });
  });

  /** @test {SelectorImporter#resolveSync} */
  describe('resolveSync()', () => {
    it('should be a function', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      expect(selectorImporterInstance.resolveSync).to.be.a('function');
    });
  });

  /** @test {SelectorImporter#resolve} */
  describe('resolve()', () => {
    it('should be a function', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      expect(selectorImporterInstance.resolve).to.be.a('function');
    });

    it('should return null', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = 'path/without/selector/filters.scss';
      const expectedResult = null;
      return expect(selectorImporterInstance.resolve(url)).to.eventually.equal(expectedResult);
    });

    it('should return selector filtered contents', () => {
      const selectorImporterInstance = new SelectorImporterClass();
      const url = '{ .class1 as .class-1, .class3 as .class-3 } from test/files/resolve.scss';
      const expectedResult = fs.readFileSync('test/files/resolve-reference.css', {
        encoding: 'utf8'
      });
      return expect(selectorImporterInstance.resolve(url)).to.eventually.equal(expectedResult);
    });
  });
});
<|endoftext|>


<commit_before>/* eslint-env mocha */

var sinon = require('sinon');
var chai = require('chai');
chai.use(require('sinon-chai'));
var expect = chai.expect;

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

describe("fluctuations", function() {
  var flux, listener, s;
  beforeEach(function() {
    s = sinon.sandbox.create();
    listener = s.spy();
    flux = fluctuations.createDispatcher();
    flux.listen('listener', listener);
  });
  afterEach(function() {
    s.restore();
  });

  describe("1 store", function() {
    beforeEach(function() {
      var store = fluctuations.createStore(
        function() { return 0; },
        {
          INC: function(n) { return n + 1; },
          DEC: function(n) { return n - 1; },
          ADD: function(n, i) { return n + i; }
        }
      );
      flux.addStore('store', store);
      s.stub(console, 'warn');
    });

    it("should begin on initial value", function() {
      expect(flux.get().store).to.eql(0);
    });

    it("should merge state from the previous store", function() {
      flux.dispatch("INC");
      var store2 = fluctuations.createStore(
        function() {
          return 0;
        }, {});
      flux.addStore('store', store2);
      expect(flux.get().store).to.eq(1);
    });

    it("should use the merge strategy", function() {
      flux.dispatch("ADD", 4);
      var store2 = fluctuations.createStore(
        function() {
          return 3;
        }, {}, function(x, y){
          return x + y;
        });
      flux.addStore('store', store2);
      expect(flux.get().store).to.eq(7);
    });

    it("should call listener after dispatch", function() {
      flux.dispatch("INC");
      expect(listener).to.have.callCount(1);
    });

    it("should call listener after every dispatch", function() {
      flux.dispatch("INC");
      flux.dispatch("INC");
      expect(listener).to.have.callCount(2);
      flux.dispatch("INC");
      expect(listener).to.have.callCount(3);
    });

    it("should have updated state when calling listener", function(done) {
      flux.listen('listener', function() {
        expect(flux.get().store).to.eql(1);
        done();
      });
      flux.dispatch("INC");
    });

    it("should update store's state after each dispatch", function() {
      flux.dispatch("INC");
      expect(flux.get().store).to.eql(1);
      flux.dispatch("INC");
      expect(flux.get().store).to.eql(2);
      flux.dispatch("DEC");
      expect(flux.get().store).to.eql(1);
      flux.dispatch("INC");
      expect(flux.get().store).to.eql(2);
    });

    it("should pass action payload along to handler", function() {
      flux.dispatch("ADD", 3);
      expect(flux.get().store).to.eql(3);
    });

    it("should not warn on a matching action", function() {
      flux.dispatch("INC");
      expect(console.warn).to.have.callCount(0);
    });

    it("should warn if dispatching an unknown action", function() {
      flux.dispatch("NOTHING");
      expect(console.warn).to.have.callCount(1);
    });

    it("should not call listener if unknown action", function() {
      flux.dispatch("NOTHING");
      expect(listener).to.have.callCount(0);
    });
  });

  describe("multiple overlapping stores", function() {
    beforeEach(function() {
      flux.addStore('a', fluctuations.createStore(
        function() { return -10; },
        {
          BUMP: function(n) { return n + 1; },
          JUMP: function(n) { return n + 10; }
        }
      ));
      flux.addStore('b', fluctuations.createStore(
        function() { return 10; },
        {
          BUMP: function(n) { return n - 1; },
          LUMP: function(n) { return n - 10; }
        }
      ));
      s.stub(console, 'warn');
    });

    it("should begin on initial values", function() {
      expect(flux.get().a).to.eql(-10);
      expect(flux.get().b).to.eql(10);
    });

    it("should call listener if one matches", function() {
      flux.dispatch("JUMP");
      expect(listener).to.have.callCount(1);
    });
    it("should call listener if another matches", function() {
      flux.dispatch("LUMP");
      expect(listener).to.have.callCount(1);
    });
    it("should call listener once if both match", function() {
      flux.dispatch("BUMP");
      expect(listener).to.have.callCount(1);
    });
    it("should update state of one if matching", function() {
      flux.dispatch("JUMP");
      expect(flux.get().a).to.eql(0);
      expect(flux.get().b).to.eql(10);
      flux.dispatch("LUMP");
      expect(flux.get().a).to.eql(0);
      expect(flux.get().b).to.eql(0);
    });
    it("should update state of all matching", function() {
      flux.dispatch("BUMP");
      expect(flux.get().a).to.eql(-9);
      expect(flux.get().b).to.eql(9);
    });

    it("should not warn on a single matching action", function() {
      flux.dispatch("LUMP");
      expect(console.warn).to.have.callCount(0);
    });

    it("should not warn on a multiple matching action", function() {
      flux.dispatch("BUMP");
      expect(console.warn).to.have.callCount(0);
    });

    it("should warn if dispatching an unknown action", function() {
      flux.dispatch("NOTHING");
      expect(console.warn).to.have.callCount(1);
    });

    it("should not call listener if unknown action", function() {
      flux.dispatch("NOTHING");
      expect(listener).to.have.callCount(0);
    });
  });

  describe("1 store with interceptor", function() {
    var storeInc, interceptions;
    beforeEach(function() {
      interceptions = [];
      storeInc = s.spy(function(n) { return n + 1; });
      flux.addStore('n', fluctuations.createStore(
        function() { return 0; },
        {
          QUICK_INC: function(n) { return n + 1; },
          INC: storeInc,
          SUB: function(n, i) { return n - i; },
          START_INC: function(n) { return n + 0.1; },
          END_INC: function(n) { return n + 0.9; }
        }
      ));
      flux.addInterceptor('slow', fluctuations.createInterceptor({
        INC: function(dispatch) {
          dispatch("START_INC");
        },
        ADD: function(dispatch, n) {
          while (n--) dispatch("INC");
        },
        SUB5: function(dispatch) {
          dispatch("SUB", 5);
        },
        AT_LEAST: function(dispatcher, n) {
          if (n > dispatcher.state.n) {
            var i = n - dispatcher.state.n;
            while (i--) dispatcher.dispatch("INC");
          }
        },
        HIJACK: function(dispatch) {
          interceptions.push(dispatch);
        }
      }));
      s.stub(console, 'warn');
    });

    it("should send non-intercepted actions to store", function() {
      flux.dispatch("QUICK_INC");
      expect(listener).to.have.callCount(1);
      expect(flux.get().n).to.eql(1);
    });

    it("should not send intercepted actions to store", function() {
      flux.dispatch("HIJACK");
      expect(storeInc).to.have.callCount(0);
    });

    it("should dispatch from interceptor to store", function() {
      flux.dispatch("INC");
      expect(listener).to.have.callCount(1);
      expect(flux.get().n).to.eql(0.1);
    });

    it("should not dispatch from interceptor to interceptor", function() {
      flux.dispatch("HIJACK");
      expect(interceptions).to.have.length(1); // captured interception
      interceptions[0]("HIJACK");
      expect(console.warn).to.have.callCount(1);
    });

    it("should allow redispatch from interceptor to interceptor", function() {
      flux.dispatch("HIJACK");
      expect(interceptions).to.have.length(1); // captured interception
      interceptions[0].redispatch("HIJACK");
      expect(interceptions).to.have.length(2);
    });

    it("should allow async stuff via interceptors", function(done) {
      flux.dispatch("HIJACK");
      expect(interceptions).to.have.length(1); // captured interception
      setTimeout(function() {
        interceptions[0]("END_INC");
      }, 0);

      flux.listen('listener', function() {
        expect(flux.get().n).to.eql(0.9);
        done();
      });
    });

    it("should receive payloads in interceptors", function() {
      flux.dispatch("ADD", 5);
      expect(flux.get().n).to.eql(5);
      expect(storeInc).to.have.callCount(5);
    });

    it("should allow interceptors to dispatch payloads to stores", function() {
      flux.dispatch("SUB5");
      expect(flux.get().n).to.eql(-5);
    });

    it("should allow interceptors to read state", function() {
      flux.dispatch("AT_LEAST", 3);
      expect(flux.get().n).to.eql(3);
      expect(storeInc).to.have.callCount(3);
      flux.dispatch("SUB5");
      flux.dispatch("AT_LEAST", 3);
      expect(flux.get().n).to.eql(3);
      expect(storeInc).to.have.callCount(8);
    });
  });

  describe("multiple overlapping interceptors", function() {
    it("should only call first matching interceptor");
    it("should do everything else the same");
  });

  describe("rehydration", function() {
    var store;
    beforeEach(function() {
      store = fluctuations.createStore(
        function() { return 0; },
        { INC: function(n) { return n + 1; } }
      );
      flux.addStore('store', store);
      s.stub(console, 'warn');
    });

    it("should begin with state if told to", function() {
      flux.dispatch("INC");
      var newFlux = fluctuations.createDispatcher({ state: flux.get() });
      newFlux.addStore('store', store);
      expect(newFlux.get()).to.deep.eql(flux.get());
    });
  });
});
<commit_msg>Add test for the intercepting behaviour of interceptors<commit_after>/* eslint-env mocha */

var sinon = require('sinon');
var chai = require('chai');
chai.use(require('sinon-chai'));
var expect = chai.expect;

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

describe("fluctuations", function() {
  var flux, listener, s;
  beforeEach(function() {
    s = sinon.sandbox.create();
    listener = s.spy();
    flux = fluctuations.createDispatcher();
    flux.listen('listener', listener);
  });
  afterEach(function() {
    s.restore();
  });

  describe("1 store", function() {
    beforeEach(function() {
      var store = fluctuations.createStore(
        function() { return 0; },
        {
          INC: function(n) { return n + 1; },
          DEC: function(n) { return n - 1; },
          ADD: function(n, i) { return n + i; }
        }
      );
      flux.addStore('store', store);
      s.stub(console, 'warn');
    });

    it("should begin on initial value", function() {
      expect(flux.get().store).to.eql(0);
    });

    it("should merge state from the previous store", function() {
      flux.dispatch("INC");
      var store2 = fluctuations.createStore(
        function() {
          return 0;
        }, {});
      flux.addStore('store', store2);
      expect(flux.get().store).to.eq(1);
    });

    it("should use the merge strategy", function() {
      flux.dispatch("ADD", 4);
      var store2 = fluctuations.createStore(
        function() {
          return 3;
        }, {}, function(x, y){
          return x + y;
        });
      flux.addStore('store', store2);
      expect(flux.get().store).to.eq(7);
    });

    it("should call listener after dispatch", function() {
      flux.dispatch("INC");
      expect(listener).to.have.callCount(1);
    });

    it("should call listener after every dispatch", function() {
      flux.dispatch("INC");
      flux.dispatch("INC");
      expect(listener).to.have.callCount(2);
      flux.dispatch("INC");
      expect(listener).to.have.callCount(3);
    });

    it("should have updated state when calling listener", function(done) {
      flux.listen('listener', function() {
        expect(flux.get().store).to.eql(1);
        done();
      });
      flux.dispatch("INC");
    });

    it("should update store's state after each dispatch", function() {
      flux.dispatch("INC");
      expect(flux.get().store).to.eql(1);
      flux.dispatch("INC");
      expect(flux.get().store).to.eql(2);
      flux.dispatch("DEC");
      expect(flux.get().store).to.eql(1);
      flux.dispatch("INC");
      expect(flux.get().store).to.eql(2);
    });

    it("should pass action payload along to handler", function() {
      flux.dispatch("ADD", 3);
      expect(flux.get().store).to.eql(3);
    });

    it("should not warn on a matching action", function() {
      flux.dispatch("INC");
      expect(console.warn).to.have.callCount(0);
    });

    it("should warn if dispatching an unknown action", function() {
      flux.dispatch("NOTHING");
      expect(console.warn).to.have.callCount(1);
    });

    it("should not call listener if unknown action", function() {
      flux.dispatch("NOTHING");
      expect(listener).to.have.callCount(0);
    });
  });

  describe("multiple overlapping stores", function() {
    beforeEach(function() {
      flux.addStore('a', fluctuations.createStore(
        function() { return -10; },
        {
          BUMP: function(n) { return n + 1; },
          JUMP: function(n) { return n + 10; }
        }
      ));
      flux.addStore('b', fluctuations.createStore(
        function() { return 10; },
        {
          BUMP: function(n) { return n - 1; },
          LUMP: function(n) { return n - 10; }
        }
      ));
      s.stub(console, 'warn');
    });

    it("should begin on initial values", function() {
      expect(flux.get().a).to.eql(-10);
      expect(flux.get().b).to.eql(10);
    });

    it("should call listener if one matches", function() {
      flux.dispatch("JUMP");
      expect(listener).to.have.callCount(1);
    });
    it("should call listener if another matches", function() {
      flux.dispatch("LUMP");
      expect(listener).to.have.callCount(1);
    });
    it("should call listener once if both match", function() {
      flux.dispatch("BUMP");
      expect(listener).to.have.callCount(1);
    });
    it("should update state of one if matching", function() {
      flux.dispatch("JUMP");
      expect(flux.get().a).to.eql(0);
      expect(flux.get().b).to.eql(10);
      flux.dispatch("LUMP");
      expect(flux.get().a).to.eql(0);
      expect(flux.get().b).to.eql(0);
    });
    it("should update state of all matching", function() {
      flux.dispatch("BUMP");
      expect(flux.get().a).to.eql(-9);
      expect(flux.get().b).to.eql(9);
    });

    it("should not warn on a single matching action", function() {
      flux.dispatch("LUMP");
      expect(console.warn).to.have.callCount(0);
    });

    it("should not warn on a multiple matching action", function() {
      flux.dispatch("BUMP");
      expect(console.warn).to.have.callCount(0);
    });

    it("should warn if dispatching an unknown action", function() {
      flux.dispatch("NOTHING");
      expect(console.warn).to.have.callCount(1);
    });

    it("should not call listener if unknown action", function() {
      flux.dispatch("NOTHING");
      expect(listener).to.have.callCount(0);
    });
  });

  describe("1 store with interceptor", function() {
    var storeInc, interceptions;
    beforeEach(function() {
      interceptions = [];
      storeInc = s.spy(function(n) { return n + 1; });
      flux.addStore('n', fluctuations.createStore(
        function() { return 0; },
        {
          QUICK_INC: function(n) { return n + 1; },
          INC: storeInc,
          SUB: function(n, i) { return n - i; },
          START_INC: function(n) { return n + 0.1; },
          END_INC: function(n) { return n + 0.9; }
        }
      ));
      flux.addInterceptor('slow', fluctuations.createInterceptor({
        INC: function(dispatch) {
          dispatch("START_INC");
        },
        ADD: function(dispatch, n) {
          while (n--) dispatch("INC");
        },
        SUB5: function(dispatch) {
          dispatch("SUB", 5);
        },
        AT_LEAST: function(dispatcher, n) {
          if (n > dispatcher.state.n) {
            var i = n - dispatcher.state.n;
            while (i--) dispatcher.dispatch("INC");
          }
        },
        HIJACK: function(dispatch) {
          interceptions.push(dispatch);
        }
      }));
      s.stub(console, 'warn');
    });

    it("should send non-intercepted actions to store", function() {
      flux.dispatch("QUICK_INC");
      expect(listener).to.have.callCount(1);
      expect(flux.get().n).to.eql(1);
    });

    it("should not send intercepted actions to store", function() {
      flux.dispatch("HIJACK");
      expect(storeInc).to.have.callCount(0);
    });

    it("should dispatch from interceptor to store", function() {
      flux.dispatch("INC");
      expect(listener).to.have.callCount(1);
      expect(flux.get().n).to.eql(0.1);
    });

    it("should not dispatch from interceptor to interceptor", function() {
      flux.dispatch("HIJACK");
      expect(interceptions).to.have.length(1); // captured interception
      interceptions[0]("HIJACK");
      expect(console.warn).to.have.callCount(1);
    });

    it("should allow redispatch from interceptor to interceptor", function() {
      flux.dispatch("HIJACK");
      expect(interceptions).to.have.length(1); // captured interception
      interceptions[0].redispatch("HIJACK");
      expect(interceptions).to.have.length(2);
    });

    it("should allow async stuff via interceptors", function(done) {
      flux.dispatch("HIJACK");
      expect(interceptions).to.have.length(1); // captured interception
      setTimeout(function() {
        interceptions[0]("END_INC");
      }, 0);

      flux.listen('listener', function() {
        expect(flux.get().n).to.eql(0.9);
        done();
      });
    });

    it("should receive payloads in interceptors", function() {
      flux.dispatch("ADD", 5);
      expect(flux.get().n).to.eql(5);
      expect(storeInc).to.have.callCount(5);
    });

    it("should allow interceptors to dispatch payloads to stores", function() {
      flux.dispatch("SUB5");
      expect(flux.get().n).to.eql(-5);
    });

    it("should allow interceptors to read state", function() {
      flux.dispatch("AT_LEAST", 3);
      expect(flux.get().n).to.eql(3);
      expect(storeInc).to.have.callCount(3);
      flux.dispatch("SUB5");
      flux.dispatch("AT_LEAST", 3);
      expect(flux.get().n).to.eql(3);
      expect(storeInc).to.have.callCount(8);
    });
  });

  describe("multiple overlapping interceptors", function() {
    beforeEach(function() {
      flux.addStore('n', fluctuations.createStore(
        function() { return 0; },
        {
          INC: function(n) { return n + 1; },
          DEC: function(n) { return n - 1; },
        }
      ));
      flux.addInterceptor('one', fluctuations.createInterceptor({
        DO_INC: function(dispatch) {
          dispatch("INC");
        }
      }));
      flux.addInterceptor('two', fluctuations.createInterceptor({
        DO_INC: function(dispatch) {
          dispatch("DEC");
        }
      }));
    });
    it("should only call first matching interceptor", function() {
      flux.dispatch("DO_INC");
      expect(flux.get().n).to.eql(1);
    });
  });

  describe("rehydration", function() {
    var store;
    beforeEach(function() {
      store = fluctuations.createStore(
        function() { return 0; },
        { INC: function(n) { return n + 1; } }
      );
      flux.addStore('store', store);
      s.stub(console, 'warn');
    });

    it("should begin with state if told to", function() {
      flux.dispatch("INC");
      var newFlux = fluctuations.createDispatcher({ state: flux.get() });
      newFlux.addStore('store', store);
      expect(newFlux.get()).to.deep.eql(flux.get());
    });
  });
});
<|endoftext|>


<commit_before>if (!process.browser) {
  require('rimraf').sync('./test/db')
} else {
  require('level-js').destroy('./test/db', function () {})
}

var test = require('tape')

var levi = require('../')
var similarity = require('../lib/util/similarity')
var group = require('../lib/util/group')
// var jsondown = require('jsondown')
var H = require('highland')

var lv = levi('./test/db')
.use(levi.tokenizer())
.use(levi.stemmer())
.use(levi.stopword())

test('pipeline', function (t) {
  t.plan(5)

  lv.pipeline('including a foo !a!b!c! of instanceof constructor.', function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      '@includ', '@foo', '@abc', '@instanceof', '@constructor'
    ], 'stemmer, stopwords, js reserved words')
  })

  lv.pipeline({
    a: 'foo bar',
    c: ['hello'],
    d: { asdf: { ghjk: 'world' } },
    e: 167,
    f: null
  }, function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      '@foo', '@bar', '@hello', '@world'
    ], 'text extraction from object')
  })

  var cyclic = { a: 'foo', b: { asdf: 'bar' } }
  cyclic.b.boom = cyclic
  lv.pipeline(cyclic, function (err) {
    t.equal(err.message, 'Cycle detected')
  })
})

test('grouping', function (t) {
  H([{key: 1}, {key: 1}, {key: 2}, {key: 3}, {key: 3}])
  .through(group)
  .toArray(function (arr) {
    t.deepEqual(arr, [
      [ { key: 1 }, { key: 1 } ],
      [ { key: 2 } ],
      [ { key: 3 }, { key: 3 } ]
    ], 'grouping')
    t.end()
  })
})

test('similarity', function (t) {
  t.equal(Math.round(similarity(
    {x: 1, y: 3, z: -5, foo: 0},
    {x: 4, y: -2, z: -1}
  ) * 1000) / 1000, 0.111, 'cosine similarity')

  t.equal(similarity(
    {x: 1, y: 3, z: -5},
    {x: 0, y: 0, z: 0}
  ), 0, 'zero magitude vector')

  t.end()
})

test('CRUD', function (t) {
  var aObj = {
    a: 'hello world'
  }
  lv.put('a', aObj, function () {
    lv.get('a', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, aObj, 'put object')
    })
  })

  var ar = ['hello', 'printing', 'a']
  lv.put('ar', ar, function () {
    lv.get('ar', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, ar, 'put array')
    })
  })

  var bText = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
  lv.put('b', new Buffer(bText), function () {
    lv.get('b', function (err, value) {
      t.notOk(err)
      t.equal(value, bText, 'put buffer')
      t.equal(typeof value, 'string', 'buffer converted to string')
    })
  })

  var cText = 'Aldus PageMaker including versions of Lorem Ipsum.'
  lv.put('c', cText, function () {
    lv.get('c', function (err, value) {
      t.notOk(err)
      t.equal(value, cText, 'put string')
    })
  })

  lv.put('d', 'Rick rolling', function (err) {
    t.notOk(err)
    lv.searchStream('rolling and hatin').toArray(function (arr) {
      t.equal(arr.length, 1, 'correct put')
      t.equal(arr[0].key, 'd', 'correct put')
      t.equal(arr[0].value, 'Rick rolling', 'correct put')
      lv.put('d', 'Rick Ashley', function (err) {
        t.notOk(err)
        lv.searchStream('rolling').toArray(function (arr) {
          t.equal(arr.length, 0, 'correct clean up')
          lv.searchStream('ashley').toArray(function (arr) {
            t.equal(arr.length, 1, 'correct upsert')
            t.equal(arr[0].key, 'd', 'correct upsert')
            t.equal(arr[0].value, 'Rick Ashley', 'correct upsert')

            lv.meta.get('size', function (err, size) {
              t.notOk(err)
              t.equal(size, 5, 'size correct')

              lv.del('a')
              lv.del('ar')
              lv.del('b')
              lv.del('c')
              lv.del('d', function (err) {
                t.notOk(err)
                lv.meta.get('size', function (err, size) {
                  t.notOk(err && !err.notFound)
                  t.notOk(size, 'empty after delete all')
                  t.end()
                })
              })
            })

          })
        })
      })
    })
  })
})

test('Search options', function (t) {
  t.plan(19)

  var live = lv.liveStream('green plant')
  var live2 = lv.searchStream('watering plant', { fields: { title: 1, body: 10 } })
  var live3 = lv.searchStream({
    title: 'Professor Plumb loves plant',
    message: 'He has a green plant in his study'
  })

  var list = [{
    id: 'a',
    title: 'Mr. Green kills Colonel Mustard',
    body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. ' +
      'Mr. Green is not a very nice fellow.'
  }, {
    id: 'b',
    title: 'Plumb waters plant',
    body: 'Professor Plumb has a green plant in his study'
  }, {
    id: 'c',
    title: 'Scarlett helps Professor',
    body: 'Miss Scarlett watered Professor Plumbs green plant while he was away ' +
      'from his office last week.'
  }, {
    id: 'd',
    title: 'foo',
    body: 'bar'
  }]

  H(list)
  .map(H.wrapCallback(function (doc, cb) {
    lv.put(doc.id, doc, cb)
  }))
  .series()
  .done(function () {
    lv.readStream({gt: 'a'}).pluck('value').toArray(function (arr) {
      t.deepEqual(arr, list.slice(1), 'readStream')
    })

    lv.searchStream('green plant').toArray(function (arr) {
      t.equal(arr.length, 3, 'search: correct number of results')
      t.equal(arr[0].key, 'b', 'search: correct score')

      lv.searchStream(['green', 'plant']).toArray(function (arr2) {
        t.deepEqual(arr2, arr, 'tokenized query')
      })

      lv.searchStream('green plant', { values: false }).toArray(function (arr) {
        t.notOk(arr[0].value, 'values: false')
      })

      lv.searchStream('green plant', { offset: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(1), 'query offset')
      })

      lv.searchStream('green plant', { limit: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(0, 1), 'limit')
      })

      live.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })

    lv.searchStream('green', { fields: { title: true } }).toArray(function (arr) {
      t.equal(arr.length, 1, 'fielded: correct number of results')
      t.equal(arr[0].key, 'a', 'fielded: correct result')
    })

    lv.searchStream('watering plant', { fields: { title: 1, body: 10 } }).toArray(function (arr) {
      t.equal(arr.length, 2, 'field boosting: correct number of results')
      t.equal(arr[0].key, 'c', 'field boosting: correct boosted result')

      live2.take(2).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[1].score,
          'live: last score identical to search score')
      })
    })

    lv.searchStream({
      title: 'Professor Plumb loves plant',
      message: 'He has a green plant in his study'
    }).toArray(function (arr) {
      t.equal(arr.length, 3, 'object search: correct number of results')
      H(arr).pluck('key').toArray(function (arr) {
        t.deepEqual(arr, ['b', 'c', 'a'], 'object search: correct order')
      })
      live3.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })
  })
})
<commit_msg>fix standard<commit_after>if (!process.browser) {
  require('rimraf').sync('./test/db')
} else {
  require('level-js').destroy('./test/db', function () {})
}

var test = require('tape')

var levi = require('../')
var similarity = require('../lib/util/similarity')
var group = require('../lib/util/group')
// var jsondown = require('jsondown')
var H = require('highland')

var lv = levi('./test/db')
.use(levi.tokenizer())
.use(levi.stemmer())
.use(levi.stopword())

test('pipeline', function (t) {
  t.plan(5)

  lv.pipeline('including a foo !a!b!c! of instanceof constructor.', function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      '@includ', '@foo', '@abc', '@instanceof', '@constructor'
    ], 'stemmer, stopwords, js reserved words')
  })

  lv.pipeline({
    a: 'foo bar',
    c: ['hello'],
    d: { asdf: { ghjk: 'world' } },
    e: 167,
    f: null
  }, function (err, tokens) {
    t.notOk(err)
    t.deepEqual(tokens, [
      '@foo', '@bar', '@hello', '@world'
    ], 'text extraction from object')
  })

  var cyclic = { a: 'foo', b: { asdf: 'bar' } }
  cyclic.b.boom = cyclic
  lv.pipeline(cyclic, function (err) {
    t.equal(err.message, 'Cycle detected')
  })
})

test('grouping', function (t) {
  H([{key: 1}, {key: 1}, {key: 2}, {key: 3}, {key: 3}])
  .through(group)
  .toArray(function (arr) {
    t.deepEqual(arr, [
      [ { key: 1 }, { key: 1 } ],
      [ { key: 2 } ],
      [ { key: 3 }, { key: 3 } ]
    ], 'grouping')
    t.end()
  })
})

test('similarity', function (t) {
  t.equal(Math.round(similarity(
    {x: 1, y: 3, z: -5, foo: 0},
    {x: 4, y: -2, z: -1}
  ) * 1000) / 1000, 0.111, 'cosine similarity')

  t.equal(similarity(
    {x: 1, y: 3, z: -5},
    {x: 0, y: 0, z: 0}
  ), 0, 'zero magitude vector')

  t.end()
})

test('CRUD', function (t) {
  var aObj = {
    a: 'hello world'
  }
  lv.put('a', aObj, function () {
    lv.get('a', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, aObj, 'put object')
    })
  })

  var ar = ['hello', 'printing', 'a']
  lv.put('ar', ar, function () {
    lv.get('ar', function (err, value) {
      t.notOk(err)
      t.deepEqual(value, ar, 'put array')
    })
  })

  var bText = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
  lv.put('b', new Buffer(bText), function () {
    lv.get('b', function (err, value) {
      t.notOk(err)
      t.equal(value, bText, 'put buffer')
      t.equal(typeof value, 'string', 'buffer converted to string')
    })
  })

  var cText = 'Aldus PageMaker including versions of Lorem Ipsum.'
  lv.put('c', cText, function () {
    lv.get('c', function (err, value) {
      t.notOk(err)
      t.equal(value, cText, 'put string')
    })
  })

  lv.put('d', 'Rick rolling', function (err) {
    t.notOk(err)
    lv.searchStream('rolling and hatin').toArray(function (arr) {
      t.equal(arr.length, 1, 'correct put')
      t.equal(arr[0].key, 'd', 'correct put')
      t.equal(arr[0].value, 'Rick rolling', 'correct put')
      lv.put('d', 'Rick Ashley', function (err) {
        t.notOk(err)
        lv.searchStream('rolling').toArray(function (arr) {
          t.equal(arr.length, 0, 'correct clean up')
          lv.searchStream('ashley').toArray(function (arr) {
            t.equal(arr.length, 1, 'correct upsert')
            t.equal(arr[0].key, 'd', 'correct upsert')
            t.equal(arr[0].value, 'Rick Ashley', 'correct upsert')

            lv.meta.get('size', function (err, size) {
              t.notOk(err)
              t.equal(size, 5, 'size correct')

              lv.del('a')
              lv.del('ar')
              lv.del('b')
              lv.del('c')
              lv.del('d', function (err) {
                t.notOk(err)
                lv.meta.get('size', function (err, size) {
                  t.notOk(err && !err.notFound)
                  t.notOk(size, 'empty after delete all')
                  t.end()
                })
              })
            })
          })
        })
      })
    })
  })
})

test('Search options', function (t) {
  t.plan(19)

  var live = lv.liveStream('green plant')
  var live2 = lv.searchStream('watering plant', { fields: { title: 1, body: 10 } })
  var live3 = lv.searchStream({
    title: 'Professor Plumb loves plant',
    message: 'He has a green plant in his study'
  })

  var list = [{
    id: 'a',
    title: 'Mr. Green kills Colonel Mustard',
    body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. ' +
      'Mr. Green is not a very nice fellow.'
  }, {
    id: 'b',
    title: 'Plumb waters plant',
    body: 'Professor Plumb has a green plant in his study'
  }, {
    id: 'c',
    title: 'Scarlett helps Professor',
    body: 'Miss Scarlett watered Professor Plumbs green plant while he was away ' +
      'from his office last week.'
  }, {
    id: 'd',
    title: 'foo',
    body: 'bar'
  }]

  H(list)
  .map(H.wrapCallback(function (doc, cb) {
    lv.put(doc.id, doc, cb)
  }))
  .series()
  .done(function () {
    lv.readStream({gt: 'a'}).pluck('value').toArray(function (arr) {
      t.deepEqual(arr, list.slice(1), 'readStream')
    })

    lv.searchStream('green plant').toArray(function (arr) {
      t.equal(arr.length, 3, 'search: correct number of results')
      t.equal(arr[0].key, 'b', 'search: correct score')

      lv.searchStream(['green', 'plant']).toArray(function (arr2) {
        t.deepEqual(arr2, arr, 'tokenized query')
      })

      lv.searchStream('green plant', { values: false }).toArray(function (arr) {
        t.notOk(arr[0].value, 'values: false')
      })

      lv.searchStream('green plant', { offset: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(1), 'query offset')
      })

      lv.searchStream('green plant', { limit: 1 }).toArray(function (arr2) {
        t.deepEqual(arr2, arr.slice(0, 1), 'limit')
      })

      live.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })

    lv.searchStream('green', { fields: { title: true } }).toArray(function (arr) {
      t.equal(arr.length, 1, 'fielded: correct number of results')
      t.equal(arr[0].key, 'a', 'fielded: correct result')
    })

    lv.searchStream('watering plant', { fields: { title: 1, body: 10 } }).toArray(function (arr) {
      t.equal(arr.length, 2, 'field boosting: correct number of results')
      t.equal(arr[0].key, 'c', 'field boosting: correct boosted result')

      live2.take(2).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[1].score,
          'live: last score identical to search score')
      })
    })

    lv.searchStream({
      title: 'Professor Plumb loves plant',
      message: 'He has a green plant in his study'
    }).toArray(function (arr) {
      t.equal(arr.length, 3, 'object search: correct number of results')
      H(arr).pluck('key').toArray(function (arr) {
        t.deepEqual(arr, ['b', 'c', 'a'], 'object search: correct order')
      })
      live3.take(3).last().pull(function (err, res) {
        t.notOk(err)
        t.equal(res.score, arr[2].score,
          'live: last score identical to search score')
      })
    })
  })
})
<|endoftext|>


<commit_before>const assert = require('assert');
const h = require('hyperscript');
const helpers = require('../dist/index')(h);
const div = helpers.div;
const jsc = require('jsverify');
const _ = require('lodash')

describe('div', function(){
  jsc.property('div() ≡ h("div")', function(){
    return _.isEqual(h('div').nodeName, div().nodeName);
  });

  jsc.property('div(attrs) ≡ h("div", attrs)', "dict string", function(attrs){
    const hr = h('div', attrs);
    const divr = div(attrs);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(children) ≡ h("div", children)', "array string", function (children) {
    const hr = h('div', children);
    const divr = div(children);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(attrs, children) ≡ h("div", attrs, children)', "dict string", "array string", function(attrs, children) {
    const hr = h('div', attrs, children);
    const divr = div(attrs, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });
});

var tagArb = jsc.elements(helpers.TAG_NAMES);

describe('arbitrary tag', function(){
  jsc.property('tag() ≡ h("tag")', tagArb, function(tag){
    return _.isEqual(h(tag).nodeName, helpers[tag]().nodeName);
  });

  jsc.property('div(attrs) ≡ h("div", attrs)', tagArb, "dict string", function(tag, attrs){
    const hr = h(tag, attrs);
    const divr = helpers[tag](attrs);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(children) ≡ h("div", children)', tagArb, "array string", function (tag, children) {
    const hr = h(tag, children);
    const divr = helpers[tag](children);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(attrs, children) ≡ h("div", attrs, children)', tagArb, "dict string", "array string", function(tag, attrs, children) {
    const hr = h(tag, attrs, children);
    const divr = helpers[tag](attrs, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });
});

describe('isSelector', function() {
  jsc.property('isSelector(".<any>") ≡ true', "string", function(string) {
    return helpers.isSelector('.' + string);
  });

  jsc.property('isSelector("#<any>") ≡ true', "string", function(string) {
    return helpers.isSelector('#' + string);
  });

  jsc.property('isSelector("^[.#]<any>") ≡ false', "nestring", function(string) {
    const startingWith =
      string.indexOf('.') === 0
      || string.indexOf('#') === 0;
    return startingWith || !helpers.isSelector(string);
  });
});

var selChars = jsc.elements(['.', '#']);

describe('arbitrary selector', function() {
  jsc.property('div(".class") ≡ h("div.class")', "nestring", function(className) {
    const selector = '.' + className;
    const hr = h('div' + selector);
    const divr = div(selector);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div("#id") ≡ h("div#id")', "nestring", function(id) {
    const selector = '#' + id;
    const hr = h('div' + selector);
    const divr = div(selector);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div("[.#]foo", children) ≡ h("div[.#]id", children)', selChars, "nestring", "array string", function(selChar, id, children) {
    const selector = selChar + id;
    const hr = h('div' + selector, children);
    const divr = div(selector, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div("[.#]foo", attrs, children) ≡ h("div[.#]id", attrs, children)', selChars, "nestring", "dict string", "array string", function(selChar, id, attrs, children) {
    const selector = selChar + id;
    const hr = h('div' + selector, attrs, children);
    const divr = div(selector, attrs, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });
});

// TODO: in jsverify 0.7.x there will be helpers to do recursive definitions (easily)
<commit_msg>Add tests for custom tag<commit_after>const assert = require('assert');
const h = require('hyperscript');
const helpers = require('../dist/index')(h);
const div = helpers.div;
const jsc = require('jsverify');
const _ = require('lodash');

describe('div', function(){
  jsc.property('div() ≡ h("div")', function(){
    return _.isEqual(h('div').nodeName, div().nodeName);
  });

  jsc.property('div(attrs) ≡ h("div", attrs)', "dict string", function(attrs){
    const hr = h('div', attrs);
    const divr = div(attrs);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(children) ≡ h("div", children)', "array string", function (children) {
    const hr = h('div', children);
    const divr = div(children);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(attrs, children) ≡ h("div", attrs, children)', "dict string", "array string", function(attrs, children) {
    const hr = h('div', attrs, children);
    const divr = div(attrs, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });
});

var tagArb = jsc.elements(helpers.TAG_NAMES);

describe('arbitrary tag', function(){
  jsc.property('tag() ≡ h("tag")', tagArb, function(tag){
    return _.isEqual(h(tag).nodeName, helpers[tag]().nodeName);
  });

  jsc.property('div(attrs) ≡ h("div", attrs)', tagArb, "dict string", function(tag, attrs){
    const hr = h(tag, attrs);
    const divr = helpers[tag](attrs);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(children) ≡ h("div", children)', tagArb, "array string", function (tag, children) {
    const hr = h(tag, children);
    const divr = helpers[tag](children);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(attrs, children) ≡ h("div", attrs, children)', tagArb, "dict string", "array string", function(tag, attrs, children) {
    const hr = h(tag, attrs, children);
    const divr = helpers[tag](attrs, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });
});

var strRandom = function(size) {
  return _.times(size, () => 'abcdefghijklmnopqrstuvwxyz'[_.random(25)]).join('');
};

var tagCustom = jsc.number(1, 20).smap(function(size) {
  return strRandom(size) + '-' + strRandom(size);
});

describe('custom tag', function(){
  jsc.property('tag() ≡ h("tag")', tagCustom, function(tagName){
    return _.isEqual(h(tagName).nodeName, helpers.createTag(tagName)().nodeName);
  });

  jsc.property('div(attrs) ≡ h("div", attrs)', tagCustom, "dict string", function(tagName, attrs){
    const hr = h(tagName, attrs);
    const divr = helpers.createTag(tagName)(attrs);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(children) ≡ h("div", children)', tagCustom, "array string", function (tagName, children){
    const hr = h(tagName, children);
    const divr = helpers.createTag(tagName)(children);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div(attrs, children) ≡ h("div", attrs, children)', tagCustom, "dict string", "array string", function(tagName, attrs, children) {
    const hr = h(tagName, attrs, children);
    const divr = helpers.createTag(tagName)(attrs, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });
});

describe('isSelector', function() {
  jsc.property('isSelector(".<any>") ≡ true', "string", function(string) {
    return helpers.isSelector('.' + string);
  });

  jsc.property('isSelector("#<any>") ≡ true', "string", function(string) {
    return helpers.isSelector('#' + string);
  });

  jsc.property('isSelector("^[.#]<any>") ≡ false', "nestring", function(string) {
    const startingWith =
      string.indexOf('.') === 0
      || string.indexOf('#') === 0;
    return startingWith || !helpers.isSelector(string);
  });
});

var selChars = jsc.elements(['.', '#']);

describe('arbitrary selector', function() {
  jsc.property('div(".class") ≡ h("div.class")', "nestring", function(className) {
    const selector = '.' + className;
    const hr = h('div' + selector);
    const divr = div(selector);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div("#id") ≡ h("div#id")', "nestring", function(id) {
    const selector = '#' + id;
    const hr = h('div' + selector);
    const divr = div(selector);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div("[.#]foo", children) ≡ h("div[.#]id", children)', selChars, "nestring", "array string", function(selChar, id, children) {
    const selector = selChar + id;
    const hr = h('div' + selector, children);
    const divr = div(selector, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });

  jsc.property('div("[.#]foo", attrs, children) ≡ h("div[.#]id", attrs, children)', selChars, "nestring", "dict string", "array string", function(selChar, id, attrs, children) {
    const selector = selChar + id;
    const hr = h('div' + selector, attrs, children);
    const divr = div(selector, attrs, children);
    return jsc.utils.isApproxEqual(hr, divr);
  });
});

// TODO: in jsverify 0.7.x there will be helpers to do recursive definitions (easily)
<|endoftext|>


<commit_before>import postcss from 'postcss';
import test    from 'ava';
import fs      from 'fs';

import plugin from '../';

function run(t, input, output, opts = { }) {
  	return postcss([ plugin(opts) ]).process(input)
        .then( result => {
            t.same(result.css, output);
            t.same(result.warnings().length, 0);
        });
}

function filename(name) {
  return "./" + name + ".css"
}
function read(name) {
  return fs.readFileSync(name, "utf8")
}

// Gently "borrowed" from https://github.com/postcss/postcss-custom-media/blob/master/test/index.js#L15
function compareFixtures(t, name, msg, opts, postcssOpts) {
  postcssOpts = postcssOpts || {}
  postcssOpts.from = filename("fixtures/" + name)
  opts = opts || {}
  var result = postcss().use(plugin(opts))
    .process(read(postcssOpts.from), postcssOpts)
  var actual = result.css
  var expected = read(filename("fixtures/" + name + ".expected"))
  fs.writeFile(filename("fixtures/" + name + ".actual"), actual)
  t.same(actual.trim(), expected.trim(), msg)

  return result
}

/* Write tests here

test('does something', t => {
    return run(t, 'a{ }', 'a{ }', { });
});

*/

test('@mediator', t => {
  return compareFixtures(t, 'mediator-modes', 'should create specific media queries')
});

test('feedback_widget', t => {
  return compareFixtures(t, 'feedback_widget/css/style.mediator', 'should generate final CSS file')
});
<commit_msg>Fix linting errors<commit_after>import postcss from 'postcss';
import test    from 'ava';
import fs      from 'fs';

import plugin from '../';

function run(t, input, output, opts = { }) {
    return postcss([ plugin(opts) ]).process(input)
        .then( result => {
            t.same(result.css, output);
            t.same(result.warnings().length, 0);
        });
}

function filename(name) {
    return './' + name + '.css';
}
function read(name) {
    return fs.readFileSync(name, 'utf8');
}

// Gently "borrowed" from https://github.com/postcss/
// postcss-custom-media/blob/master/test/index.js#L15
function compareFixtures(t, name, msg, opts, postcssOpts) {
    postcssOpts = postcssOpts || {};
    postcssOpts.from = filename('fixtures/' + name);
    opts = opts || {};
    let result = postcss().use(plugin(opts))
      .process(read(postcssOpts.from), postcssOpts);
    let actual = result.css;
    let expected = read(filename('fixtures/' + name + '.expected'));
    fs.writeFile(filename('fixtures/' + name + '.actual'), actual);
    t.same(actual.trim(), expected.trim(), msg);

    return result;
}

test('@mediator', t => {
    return compareFixtures(t,
      'mediator-modes',
      'should create specific media queries');
});

test('feedback_widget', t => {
    return compareFixtures(t,
      'feedback_widget/css/style.mediator',
      'should generate final CSS file');
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Comment from './components/Comment'

class Comments extends Component {
  render () {
    if (this.props.commentIds.length === 0) {
      // Prevent empty content to display
      // when no comments are loaded
      return null
    }

    return (
      <div>
        {this.props.commentIds.map(id => (
          <Comment
            key={id}
            id={id}
          />
        ))}
      </div>
    )
  }
}

export default Comments
<commit_msg>Comment section styling<commit_after>import React, { Component } from 'react'
import styled from 'styled-components'
import Comment from './components/Comment'
import { BOX_SHADOW_1, RESPONSIVE_BREAKPOINT } from 'Util/constants'

const Outer = styled.div`
  max-width: ${RESPONSIVE_BREAKPOINT};
  box-sizing: border-box;
  margin: 24px auto;
  padding: 16px;
  border-radius: 4px;
  overflow: hidden;

  background: #fff;
  box-shadow: ${BOX_SHADOW_1};
`

class Comments extends Component {
  render () {
    if (this.props.commentIds.length === 0) {
      // Prevent empty content to display
      // when no comments are loaded
      return null
    }

    return (
      <Outer>
        {this.props.commentIds.map(id => (
          <Comment
            key={id}
            id={id}
          />
        ))}
      </Outer>
    )
  }
}

export default Comments
<|endoftext|>


<commit_before>"use strict";

var chai = require('chai');
var expect = chai.expect;
var systat = require('../lib/systat');

describe('systat', function () {

    describe('checkChip()', function () {
        it('should return true if the chip is supported', function (done) {
            var result = systat.checkChip();
            expect(result).to.be.a.boolean;
            done();
        });
    });

    describe('getFanSpeeds()', function () {
        it('shoudl return the system fans speed(rpm) as array', function (done) {
            var result = systat.getFanSpeeds();
            expect(result).to.be.an.array;
            done();
        });
    });

    describe('getSystemTemperatures()', function () {
        it('shoudl return the system tempertures(C) as array', function (done) {
            var result = systat.getSystemTemperatures();
            expect(result).to.be.an.array;
            done();
        });
    });

    describe('getCPUTTemperatures()', function () {
        it('shoudl return the CPU tempertures(C) as array', function (done) {
            var result = systat.getCPUTemperatures();
            expect(result).to.be.an.array;
            done();
        });
    });

    describe('getVoltages()', function () {
        it('shoudl return the system voltages(mV) as array', function (done) {
            var result = systat.getVoltages();
            expect(result).to.be.an.array;
            done();
        });
    });

    describe('getNICStat(nic)', function () {
        it('shoudl return the mac stats info as object', function (done) {
            var result = systat.getNICStat("em0");
            console.log(result);
            expect(result).to.be.an.object;
            done();
        });
    });

});<commit_msg>add a new unit test for fetching temperature data from hard drive<commit_after>"use strict";

var chai = require('chai');
var expect = chai.expect;
var systat = require('../lib/systat');

describe('systat', function () {

    describe('checkChip()', function () {
        it('should return true if the chip is supported', function (done) {
            var result = systat.checkChip();
            expect(result).to.be.a.boolean;
            done();
        });
    });

    describe('getFanSpeeds()', function () {
        it('shoudl return the system fans speed(rpm) as array', function (done) {
            var result = systat.getFanSpeeds();
            expect(result).to.be.an.array;
            done();
        });
    });

    describe('getSystemTemperatures()', function () {
        it('shoudl return the system temperature(C) as array', function (done) {
            var result = systat.getSystemTemperatures();
            expect(result).to.be.an.array;
            done();
        });
    });

    describe('getCPUTTemperatures()', function () {
        it('shoudl return the CPU temperature(C) as array', function (done) {
            var result = systat.getCPUTemperatures();
            expect(result).to.be.an.array;
            done();
        });
    });

    describe('getVoltages()', function () {
        it('shoudl return the system voltages(mV) as array', function (done) {
            var result = systat.getVoltages();
            expect(result).to.be.an.array;
            done();
        });
    });

    describe('getNICStat(nic)', function () {
        it('shoudl return the mac stats info as object', function (done) {
            var result = systat.getNICStat("em0");
            expect(result).to.be.an.object;
            done();
        });
    });

    describe('getDiskTemperatures(device)', function () {
        it('shoudl return the disk temperature(c) as int', function (done) {
            var result = systat.getNICStat("em0");
            expect(result).to.be.an.int;
            done();
        });
    });

});<|endoftext|>


<commit_before>/*
 *     Copyright (c) 2012-2015 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global gettext, LayoutManagerFactory, StyledElements, Wirecloud*/

(function () {

    "use strict";

    var WirecloudHeader = function WirecloudHeader() {
        this.wrapperElement = document.getElementById('wirecloud_header');
        this.app_bar = this.wrapperElement.querySelector('.wirecloud_app_bar');
        this.breadcrum = document.getElementById('wirecloud_breadcrum');
        this.oil_header = this.wrapperElement.getElementsByTagName('header')[0];

        this.backButton = new StyledElements.StyledButton({'class': 'btn-large', 'iconClass': 'icon-caret-left'});
        this.backButton.addEventListener('click', function () {
            this.currentView.goUp();
        }.bind(this));
        this.backButton.disable();
        this.backButton.insertInto(this.breadcrum.parentNode, this.breadcrum);

        this.menuButton = new StyledElements.PopupButton({'class': 'btn-large', 'iconClass': 'icon-reorder'});
        this.menuButton.disable();
        this.menuButton.insertInto(this.breadcrum.parentNode);

        this.toolbar = document.createElement('div');
        this.toolbar.className = 'btn-group wirecloud_toolbar';
        this.app_bar.appendChild(this.toolbar);

        this.currentView = null;
        this.close_cookie_banner_button = null;
    };

    WirecloudHeader.prototype._initUserMenu = function _initUserMenu() {
        var user_menu, wrapper, login_button, item;

        var username = Wirecloud.contextManager.get('username');
        var full_name = Wirecloud.contextManager.get('fullname').trim();

        wrapper = document.createElement('div');
        wrapper.className = 'nav pull-right';
        this.oil_header.insertBefore(wrapper, this.oil_header.firstChild);

        var li = document.createElement('li');
        wrapper.appendChild(li);
        var anchor = document.createElement('a');
        anchor.setAttribute('href', Wirecloud.constants.FIWARE_IDM_SERVER + '/users/' + username);
        anchor.setAttribute('target', '_blank');
        li.appendChild(anchor);
        var img = document.createElement('img');
        img.setAttribute('src', '/static/images/user.png');
        anchor.appendChild(img);
        anchor.appendChild(document.createTextNode(' '));
        var username_element = document.createElement('span');
        username_element.className = 'name';
        if (full_name === '') {
            full_name = username;
        }
        username_element.textContent = full_name;
        anchor.appendChild(username_element);

        this.user_button = new StyledElements.PopupButton({
            'class': 'arrow-down-settings',
            'plain': true
        });
        this.user_button.insertInto(wrapper);

        user_menu = this.user_button.getPopupMenu();
        item = new StyledElements.MenuItem(gettext('Settings'), function () {
            var dialog = new Wirecloud.ui.PreferencesWindowMenu('platform', Wirecloud.preferences);
            dialog.show();
        });
        user_menu.append(item);
        item.setDisabled(username === 'anonymous');

        if (Wirecloud.contextManager.get('isstaff') === true && 'DJANGO_ADMIN' in Wirecloud.URLs) {
            user_menu.append(new StyledElements.MenuItem(gettext('DJango Admin panel'), function () {
                window.open(Wirecloud.URLs.DJANGO_ADMIN, '_blank');
            }));
        }
        item = new Wirecloud.ui.TutorialSubMenu();
        user_menu.append(item);
        item.setDisabled(username === 'anonymous');
        user_menu.append(new StyledElements.Separator());
        if (username === 'anonymous') {
            user_menu.append(new StyledElements.MenuItem(gettext('Sign in'), function () {
                window.location = Wirecloud.URLs.LOGIN_VIEW + '?next=' + encodeURIComponent(window.location.pathname + window.location.search + window.location.hash);
            }));
        } else {
            user_menu.append(new StyledElements.MenuItem(gettext('Sign out'), function () {
                var portal_logout_urls, i, portal;

                portal_logout_urls = [];
                for (i = 0; i < Wirecloud.constants.FIWARE_PORTALS.length; i++) {
                    portal = Wirecloud.constants.FIWARE_PORTALS[i];
                    if ('logout_path' in portal) {
                        portal_logout_urls.push(portal.url + portal.logout_path);
                    }
                };
                for (i = 0; i < portal_logout_urls.length; i += 1) {
                    try {
                        Wirecloud.io.makeRequest(portal_logout_urls[i], {
                            method: 'GET',
                            supportsAccessControl: true,
                            withCredentials: true,
                            requestHeaders: {
                                'X-Requested-With': null
                            }
                        });
                    } catch (error) {}
                }
                setTimeout(Wirecloud.logout, 1000);
            }));
        }
    };

    var paint_breadcrum_entry = function paint_breadcrum_entry(i, breadcrum_entry) {
        var breadcrum_part, breadcrum_levels = ['first_level', 'second_level', 'third_level'];

        if (typeof breadcrum_entry === 'string') {
            breadcrum_entry = {label: breadcrum_entry};
        }

        breadcrum_part = document.createElement('span');
        breadcrum_part.textContent = breadcrum_entry.label;
        breadcrum_part.className = breadcrum_levels[i];
        if ('class' in breadcrum_entry) {
            breadcrum_part.classList.add(breadcrum_entry['class']);
        }

        this.breadcrum.appendChild(breadcrum_part);
    };

    WirecloudHeader.prototype._paintBreadcrum = function _paintBreadcrum(newView) {
        var i, breadcrum, breadcrum_entry;

        this.breadcrum.innerHTML = '';

        if (newView != null && 'getBreadcrum' in newView) {
            breadcrum = newView.getBreadcrum();
        } else {
            return;
        }

        if (breadcrum.length === 0) {
            return;
        }

        paint_breadcrum_entry.call(this, 0, breadcrum[0]);

        for (i = 1; i < breadcrum.length; i += 1) {
            this.breadcrum.appendChild(document.createTextNode('/'));

            paint_breadcrum_entry.call(this, i, breadcrum[i]);
        }
    };

    WirecloudHeader.prototype._refreshTitle = function _refreshTitle(newView) {
        if (newView != null) {
            document.title = newView.getTitle();
        }
    };

    WirecloudHeader.prototype._paintToolbar = function _paintToolbar(newView) {
        var buttons, i;

        this.toolbar.innerHTML = '';

        if (newView == null || !('getToolbarButtons' in newView)) {
            return;
        }

        buttons = newView.getToolbarButtons();
        for (i = 0; i < buttons.length; i++) {
            buttons[i].addClassName('btn-large');
            buttons[i].addClassName('btn-primary');
            buttons[i].insertInto(this.toolbar);
        }
    };

    WirecloudHeader.prototype._replaceMenu = function _replaceMenu(newView) {
        var menu;

        if (newView != null && ('getToolbarMenu' in newView)) {
            menu = newView.getToolbarMenu();
        }

        this.menuButton.replacePopupMenu(menu);
        this.menuButton.setDisabled(menu == null);
    };

    WirecloudHeader.prototype._notifyViewChange = function _notifyViewChange(newView) {
        if (newView == null) {
            this.backButton.disable();
            this.menuButton.disable();
        } else {
            this.currentView = newView;

            this.refresh();
        }
    };

    var cookies;
    var fiware_cookie_policy_cookie = 'policy_cookie';
    var fiware_cookie_policy_days = 10;

    var readCookie = function readCookie(name) {
        var parts, cookie, i;

        if (cookies == null) {
            parts = document.cookie.split('; ');
            cookies = {};

            for (i = parts.length - 1; i >= 0; i--) {
                cookie = parts[i].split('=');
                cookies[cookie[0]] = cookie[1];
            }
        }

        return cookies[name];
    };

    WirecloudHeader.prototype._notifyWorkspaceLoaded = function _notifyWorkspaceLoaded(workspace) {
        var msg, environment, cookie_banner, expiration_date;

        if (Wirecloud.constants.FIWARE_OFFICIAL_PORTAL && this.footer == null) {
            this.footer = document.createElement('footer');

            msg = '
2015 © FIWARE. The use of FIWARE %(environment)s services is subject to the acceptance of the Terms and Conditions, Personal Data Protection Policy and Cookies Policy
';
            if (Wirecloud.constants.FIWARE_IDM_SERVER === 'https://account.lab.fiware.org') {
                environment = 'Lab';
            } else {
                environment = 'Testbed';
            }
            msg = interpolate(msg, {environment: environment}, true);
            this.footer.innerHTML = msg;

            if (readCookie(fiware_cookie_policy_cookie) !== 'on') {
                cookie_banner = document.createElement('div');
                cookie_banner.setAttribute('id', 'cookie-law');
                cookie_banner.innerHTML = '
We use first and third-party’s cookies to improve your experience and our services, identifying your Internet browsing preferences on our website. If you keep browsing, you accept its use. You can get more information on our Cookie Policy.
';
                document.body.appendChild(cookie_banner);

                this.close_cookie_banner_button = new StyledElements.StyledButton({text: 'X', plain: true, id: 'close-cookie-banner'});
                this.close_cookie_banner_button.insertInto(cookie_banner);
                this.close_cookie_banner_button.addEventListener('click', function () {
                    document.body.removeChild(cookie_banner);
                }.bind(this));

                var expiration_date = new Date();
                expiration_date.setTime(expiration_date.getTime() + (fiware_cookie_policy_days * 24 * 60 * 60 * 1000));
                document.cookie = fiware_cookie_policy_cookie + "=on; expires=" + expiration_date.toGMTString() + "; path=/";
            }

            LayoutManagerFactory.getInstance().mainLayout.getSouthContainer().appendChild(this.footer);
            LayoutManagerFactory.getInstance().mainLayout.repaint();
        }

        this._paintBreadcrum(LayoutManagerFactory.getInstance().viewsByName['workspace']);
    };

    WirecloudHeader.prototype.refresh = function refresh() {
        this._paintBreadcrum(this.currentView);
        this._refreshTitle(this.currentView);
        this._paintToolbar(this.currentView);
        this._replaceMenu(this.currentView);
        this.backButton.setDisabled(this.currentView == null || !('goUp' in this.currentView));
    };

    Wirecloud.ui.WirecloudHeader = WirecloudHeader;

})();
<commit_msg>Update FIWARE Lab terms and conditions link<commit_after>/*
 *     Copyright (c) 2012-2015 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global gettext, LayoutManagerFactory, StyledElements, Wirecloud*/

(function () {

    "use strict";

    var WirecloudHeader = function WirecloudHeader() {
        this.wrapperElement = document.getElementById('wirecloud_header');
        this.app_bar = this.wrapperElement.querySelector('.wirecloud_app_bar');
        this.breadcrum = document.getElementById('wirecloud_breadcrum');
        this.oil_header = this.wrapperElement.getElementsByTagName('header')[0];

        this.backButton = new StyledElements.StyledButton({'class': 'btn-large', 'iconClass': 'icon-caret-left'});
        this.backButton.addEventListener('click', function () {
            this.currentView.goUp();
        }.bind(this));
        this.backButton.disable();
        this.backButton.insertInto(this.breadcrum.parentNode, this.breadcrum);

        this.menuButton = new StyledElements.PopupButton({'class': 'btn-large', 'iconClass': 'icon-reorder'});
        this.menuButton.disable();
        this.menuButton.insertInto(this.breadcrum.parentNode);

        this.toolbar = document.createElement('div');
        this.toolbar.className = 'btn-group wirecloud_toolbar';
        this.app_bar.appendChild(this.toolbar);

        this.currentView = null;
        this.close_cookie_banner_button = null;
    };

    WirecloudHeader.prototype._initUserMenu = function _initUserMenu() {
        var user_menu, wrapper, login_button, item;

        var username = Wirecloud.contextManager.get('username');
        var full_name = Wirecloud.contextManager.get('fullname').trim();

        wrapper = document.createElement('div');
        wrapper.className = 'nav pull-right';
        this.oil_header.insertBefore(wrapper, this.oil_header.firstChild);

        var li = document.createElement('li');
        wrapper.appendChild(li);
        var anchor = document.createElement('a');
        anchor.setAttribute('href', Wirecloud.constants.FIWARE_IDM_SERVER + '/users/' + username);
        anchor.setAttribute('target', '_blank');
        li.appendChild(anchor);
        var img = document.createElement('img');
        img.setAttribute('src', '/static/images/user.png');
        anchor.appendChild(img);
        anchor.appendChild(document.createTextNode(' '));
        var username_element = document.createElement('span');
        username_element.className = 'name';
        if (full_name === '') {
            full_name = username;
        }
        username_element.textContent = full_name;
        anchor.appendChild(username_element);

        this.user_button = new StyledElements.PopupButton({
            'class': 'arrow-down-settings',
            'plain': true
        });
        this.user_button.insertInto(wrapper);

        user_menu = this.user_button.getPopupMenu();
        item = new StyledElements.MenuItem(gettext('Settings'), function () {
            var dialog = new Wirecloud.ui.PreferencesWindowMenu('platform', Wirecloud.preferences);
            dialog.show();
        });
        user_menu.append(item);
        item.setDisabled(username === 'anonymous');

        if (Wirecloud.contextManager.get('isstaff') === true && 'DJANGO_ADMIN' in Wirecloud.URLs) {
            user_menu.append(new StyledElements.MenuItem(gettext('DJango Admin panel'), function () {
                window.open(Wirecloud.URLs.DJANGO_ADMIN, '_blank');
            }));
        }
        item = new Wirecloud.ui.TutorialSubMenu();
        user_menu.append(item);
        item.setDisabled(username === 'anonymous');
        user_menu.append(new StyledElements.Separator());
        if (username === 'anonymous') {
            user_menu.append(new StyledElements.MenuItem(gettext('Sign in'), function () {
                window.location = Wirecloud.URLs.LOGIN_VIEW + '?next=' + encodeURIComponent(window.location.pathname + window.location.search + window.location.hash);
            }));
        } else {
            user_menu.append(new StyledElements.MenuItem(gettext('Sign out'), function () {
                var portal_logout_urls, i, portal;

                portal_logout_urls = [];
                for (i = 0; i < Wirecloud.constants.FIWARE_PORTALS.length; i++) {
                    portal = Wirecloud.constants.FIWARE_PORTALS[i];
                    if ('logout_path' in portal) {
                        portal_logout_urls.push(portal.url + portal.logout_path);
                    }
                };
                for (i = 0; i < portal_logout_urls.length; i += 1) {
                    try {
                        Wirecloud.io.makeRequest(portal_logout_urls[i], {
                            method: 'GET',
                            supportsAccessControl: true,
                            withCredentials: true,
                            requestHeaders: {
                                'X-Requested-With': null
                            }
                        });
                    } catch (error) {}
                }
                setTimeout(Wirecloud.logout, 1000);
            }));
        }
    };

    var paint_breadcrum_entry = function paint_breadcrum_entry(i, breadcrum_entry) {
        var breadcrum_part, breadcrum_levels = ['first_level', 'second_level', 'third_level'];

        if (typeof breadcrum_entry === 'string') {
            breadcrum_entry = {label: breadcrum_entry};
        }

        breadcrum_part = document.createElement('span');
        breadcrum_part.textContent = breadcrum_entry.label;
        breadcrum_part.className = breadcrum_levels[i];
        if ('class' in breadcrum_entry) {
            breadcrum_part.classList.add(breadcrum_entry['class']);
        }

        this.breadcrum.appendChild(breadcrum_part);
    };

    WirecloudHeader.prototype._paintBreadcrum = function _paintBreadcrum(newView) {
        var i, breadcrum, breadcrum_entry;

        this.breadcrum.innerHTML = '';

        if (newView != null && 'getBreadcrum' in newView) {
            breadcrum = newView.getBreadcrum();
        } else {
            return;
        }

        if (breadcrum.length === 0) {
            return;
        }

        paint_breadcrum_entry.call(this, 0, breadcrum[0]);

        for (i = 1; i < breadcrum.length; i += 1) {
            this.breadcrum.appendChild(document.createTextNode('/'));

            paint_breadcrum_entry.call(this, i, breadcrum[i]);
        }
    };

    WirecloudHeader.prototype._refreshTitle = function _refreshTitle(newView) {
        if (newView != null) {
            document.title = newView.getTitle();
        }
    };

    WirecloudHeader.prototype._paintToolbar = function _paintToolbar(newView) {
        var buttons, i;

        this.toolbar.innerHTML = '';

        if (newView == null || !('getToolbarButtons' in newView)) {
            return;
        }

        buttons = newView.getToolbarButtons();
        for (i = 0; i < buttons.length; i++) {
            buttons[i].addClassName('btn-large');
            buttons[i].addClassName('btn-primary');
            buttons[i].insertInto(this.toolbar);
        }
    };

    WirecloudHeader.prototype._replaceMenu = function _replaceMenu(newView) {
        var menu;

        if (newView != null && ('getToolbarMenu' in newView)) {
            menu = newView.getToolbarMenu();
        }

        this.menuButton.replacePopupMenu(menu);
        this.menuButton.setDisabled(menu == null);
    };

    WirecloudHeader.prototype._notifyViewChange = function _notifyViewChange(newView) {
        if (newView == null) {
            this.backButton.disable();
            this.menuButton.disable();
        } else {
            this.currentView = newView;

            this.refresh();
        }
    };

    var cookies;
    var fiware_cookie_policy_cookie = 'policy_cookie';
    var fiware_cookie_policy_days = 10;

    var readCookie = function readCookie(name) {
        var parts, cookie, i;

        if (cookies == null) {
            parts = document.cookie.split('; ');
            cookies = {};

            for (i = parts.length - 1; i >= 0; i--) {
                cookie = parts[i].split('=');
                cookies[cookie[0]] = cookie[1];
            }
        }

        return cookies[name];
    };

    WirecloudHeader.prototype._notifyWorkspaceLoaded = function _notifyWorkspaceLoaded(workspace) {
        var msg, environment, cookie_banner, expiration_date;

        if (Wirecloud.constants.FIWARE_OFFICIAL_PORTAL && this.footer == null) {
            this.footer = document.createElement('footer');

            msg = '
2015 © FIWARE. The use of FIWARE %(environment)s services is subject to the acceptance of the Terms and Conditions, Personal Data Protection Policy and Cookies Policy
';
            if (Wirecloud.constants.FIWARE_IDM_SERVER === 'https://account.lab.fiware.org') {
                environment = 'Lab';
            } else {
                environment = 'Testbed';
            }
            msg = interpolate(msg, {environment: environment}, true);
            this.footer.innerHTML = msg;

            if (readCookie(fiware_cookie_policy_cookie) !== 'on') {
                cookie_banner = document.createElement('div');
                cookie_banner.setAttribute('id', 'cookie-law');
                cookie_banner.innerHTML = '
We use first and third-party’s cookies to improve your experience and our services, identifying your Internet browsing preferences on our website. If you keep browsing, you accept its use. You can get more information on our Cookie Policy.
';
                document.body.appendChild(cookie_banner);

                this.close_cookie_banner_button = new StyledElements.StyledButton({text: 'X', plain: true, id: 'close-cookie-banner'});
                this.close_cookie_banner_button.insertInto(cookie_banner);
                this.close_cookie_banner_button.addEventListener('click', function () {
                    document.body.removeChild(cookie_banner);
                }.bind(this));

                var expiration_date = new Date();
                expiration_date.setTime(expiration_date.getTime() + (fiware_cookie_policy_days * 24 * 60 * 60 * 1000));
                document.cookie = fiware_cookie_policy_cookie + "=on; expires=" + expiration_date.toGMTString() + "; path=/";
            }

            LayoutManagerFactory.getInstance().mainLayout.getSouthContainer().appendChild(this.footer);
            LayoutManagerFactory.getInstance().mainLayout.repaint();
        }

        this._paintBreadcrum(LayoutManagerFactory.getInstance().viewsByName['workspace']);
    };

    WirecloudHeader.prototype.refresh = function refresh() {
        this._paintBreadcrum(this.currentView);
        this._refreshTitle(this.currentView);
        this._paintToolbar(this.currentView);
        this._replaceMenu(this.currentView);
        this.backButton.setDisabled(this.currentView == null || !('goUp' in this.currentView));
    };

    Wirecloud.ui.WirecloudHeader = WirecloudHeader;

})();
<|endoftext|>


<commit_before>module("steal via system import");

(function(){

	var writeIframe = function(html){
		var iframe = document.createElement('iframe');
		window.removeMyself = function(){
			delete window.removeMyself;
			document.body.removeChild(iframe);
		};
		document.body.appendChild(iframe);
		iframe.contentWindow.document.open();
		iframe.contentWindow.document.write(html);
		iframe.contentWindow.document.close();
	};
	var makePassQUnitHTML = function(){
		return "";

	};
	var makeStealHTML = function(url, src, code){
		return "<!doctype html>\
			\
				" + makePassQUnitHTML() +"\n"+
					"<base href='"+url+"'/>"+
				"\
				\
					"+
					(code ? "" :"") +
				"";

	};
	var makeIframe = function(src){
		var iframe = document.createElement('iframe');
		window.removeMyself = function(){
			delete window.removeMyself;
			document.body.removeChild(iframe);
		};
		document.body.appendChild(iframe);
		iframe.src = src;
	};

	asyncTest('steal basics', function(){
		System['import']('tests/module').then(function(m){
		  equal(m.name,"module.js", "module returned" );
		  equal(m.bar.name, "bar", "module.js was not able to get bar");
	      start();
		}, function(err){
			console.log(err)
			ok(false, "steal not loaded");
			start()
		});
	});

	asyncTest("steal's normalize", function(){
		System['import']('tests/mod/mod').then(function(m){
		  equal(m.name,"mod", "mod returned" );
		  equal(m.module.bar.name, "bar", "module.js was able to get bar");
		  equal(m.widget(), "widget", "got a function");
	      start();
		}, function(){
			ok(false, "steal not loaded");
			start()
		});
	});

	asyncTest("steal's normalize with a plugin", function(){
		var stealFormat = System.format.steal;
		stealFormat.normalize("foo/bar!foo/bar", "foo", "http://foo", System.normalize)
			.then(function(result){
				equal(result, "foo/bar/bar!foo/bar", "normalize fixed part before !");
				start();
			});
	});

	asyncTest("steal's normalize with plugin only the bang", function(){
		var stealFormat = System.format.steal;
		stealFormat.normalize("./rdfa.stache!", "foo", "http://foo", System.normalize)
			.then(function(result){
				equal(result, "rdfa.stache!stache", "normalize added the extension as plugin name");
				start();
			});
	});

module("steal via html");

	asyncTest("basics", function(){
		makeIframe("basics/basics.html");

	});

	asyncTest("basics with generated html", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../../steal.js?basics" data-config="../config.js"'));
	});

	asyncTest("default config path", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../steal.js?basics"'));
	});

	asyncTest("default config path", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../steal/steal.js?basics"'));
	});

	asyncTest("inline", function(){
		makeIframe("basics/inline_basics.html");

	});

	asyncTest("default bower_components config path", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../bower_components/steal/steal.js?basics"'));
	});

	asyncTest("default bower_components without config still works", function(){
		makeIframe("basics/noconfig.html");
	});

	asyncTest("map works", function(){
		makeIframe("map/map.html");
	});

	asyncTest("read config", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../../steal.js?configed" data-config="../config.js"'));
	});

	asyncTest("compat - product bundle works", function(){
		makeIframe("production/prod.html");
	});

	asyncTest("product bundle specifying main works", function(){
		makeIframe("production/prod-main.html");
	});

	asyncTest("automatic loading of css plugin", function(){
		makeIframe("plugins/site.html");
	});

	asyncTest("product bundle with css", function(){
		makeIframe("production/prod-bar.html");
	});

	asyncTest("automatic loading of less plugin", function(){
		makeIframe("dep_plugins/site.html");
	});

	asyncTest("Using path's * qualifier", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../steal.js?../paths" data-config="../paths/config.js"'));
	});

	asyncTest("url paths in css work", function(){
		makeIframe("css_paths/site.html");
	});

	asyncTest("ext extension", function(){
		makeIframe("extensions/site.html");
	});

	asyncTest("forward slash extension", function(){
		makeIframe("forward_slash/site.html");
	});

})();
<commit_msg>Adds a timeout for qunit tests<commit_after>module("steal via system import");

QUnit.config.testTimeout = 30000;

(function(){

	var writeIframe = function(html){
		var iframe = document.createElement('iframe');
		window.removeMyself = function(){
			delete window.removeMyself;
			document.body.removeChild(iframe);
		};
		document.body.appendChild(iframe);
		iframe.contentWindow.document.open();
		iframe.contentWindow.document.write(html);
		iframe.contentWindow.document.close();
	};
	var makePassQUnitHTML = function(){
		return "";

	};
	var makeStealHTML = function(url, src, code){
		return "<!doctype html>\
			\
				" + makePassQUnitHTML() +"\n"+
					"<base href='"+url+"'/>"+
				"\
				\
					"+
					(code ? "" :"") +
				"";

	};
	var makeIframe = function(src){
		var iframe = document.createElement('iframe');
		window.removeMyself = function(){
			delete window.removeMyself;
			document.body.removeChild(iframe);
		};
		document.body.appendChild(iframe);
		iframe.src = src;
	};

	asyncTest('steal basics', function(){
		System['import']('tests/module').then(function(m){
		  equal(m.name,"module.js", "module returned" );
		  equal(m.bar.name, "bar", "module.js was not able to get bar");
	      start();
		}, function(err){
			console.log(err)
			ok(false, "steal not loaded");
			start()
		});
	});

	asyncTest("steal's normalize", function(){
		System['import']('tests/mod/mod').then(function(m){
		  equal(m.name,"mod", "mod returned" );
		  equal(m.module.bar.name, "bar", "module.js was able to get bar");
		  equal(m.widget(), "widget", "got a function");
	      start();
		}, function(){
			ok(false, "steal not loaded");
			start()
		});
	});

	asyncTest("steal's normalize with a plugin", function(){
		var stealFormat = System.format.steal;
		stealFormat.normalize("foo/bar!foo/bar", "foo", "http://foo", System.normalize)
			.then(function(result){
				equal(result, "foo/bar/bar!foo/bar", "normalize fixed part before !");
				start();
			});
	});

	asyncTest("steal's normalize with plugin only the bang", function(){
		var stealFormat = System.format.steal;
		stealFormat.normalize("./rdfa.stache!", "foo", "http://foo", System.normalize)
			.then(function(result){
				equal(result, "rdfa.stache!stache", "normalize added the extension as plugin name");
				start();
			});
	});

module("steal via html");

	asyncTest("basics", function(){
		makeIframe("basics/basics.html");

	});

	asyncTest("basics with generated html", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../../steal.js?basics" data-config="../config.js"'));
	});

	asyncTest("default config path", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../steal.js?basics"'));
	});

	asyncTest("default config path", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../steal/steal.js?basics"'));
	});

	asyncTest("inline", function(){
		makeIframe("basics/inline_basics.html");

	});

	asyncTest("default bower_components config path", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../bower_components/steal/steal.js?basics"'));
	});

	asyncTest("default bower_components without config still works", function(){
		makeIframe("basics/noconfig.html");
	});

	asyncTest("map works", function(){
		makeIframe("map/map.html");
	});

	asyncTest("read config", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../../steal.js?configed" data-config="../config.js"'));
	});

	asyncTest("compat - product bundle works", function(){
		makeIframe("production/prod.html");
	});

	asyncTest("product bundle specifying main works", function(){
		makeIframe("production/prod-main.html");
	});

	asyncTest("automatic loading of css plugin", function(){
		makeIframe("plugins/site.html");
	});

	asyncTest("product bundle with css", function(){
		makeIframe("production/prod-bar.html");
	});

	asyncTest("automatic loading of less plugin", function(){
		makeIframe("dep_plugins/site.html");
	});

	asyncTest("Using path's * qualifier", function(){
		writeIframe(makeStealHTML(
			"basics/basics.html",
			'src="../steal.js?../paths" data-config="../paths/config.js"'));
	});

	asyncTest("url paths in css work", function(){
		makeIframe("css_paths/site.html");
	});

	asyncTest("ext extension", function(){
		makeIframe("extensions/site.html");
	});

	asyncTest("forward slash extension", function(){
		makeIframe("forward_slash/site.html");
	});

})();
<|endoftext|>


<commit_before>/*jslint node: true */
/*global describe, it */
(function () {
    "use strict";

    var assert = require("assert"),
        uglifyJS = require("uglifyjs"),
        unbrowserify = require("../unbrowserify");

    function parseString(code, filename) {
        var ast = uglifyJS.parse(code, {filename: filename});
        ast.figure_out_scope();
        return ast;
    }

    describe("unbrowserify", function () {
        describe("findMainFunction", function () {
            it("should find the main function", function () {
                var ast = parseString("var foo; !function e(){ }(foo);"),
                    f = unbrowserify.findMainFunction(ast);

                assert.equal(true, f instanceof uglifyJS.AST_Call);
                assert.equal("e", f.expression.name.name);
            });

            it("should find the first function if multiple defined", function () {
                var ast = parseString("var foo; !function e(){ }(foo); !function f(){ }(foo);"),
                    f = unbrowserify.findMainFunction(ast);

                assert.equal(true, f instanceof uglifyJS.AST_Call);
                assert.equal("e", f.expression.name.name);
            });

            it("should return undefined if no functions are defined", function () {
                var ast = parseString("var foo;"),
                    f = unbrowserify.findMainFunction(ast);

                assert.equal(undefined, f);
            });
        });

        describe("extractModuleNames", function () {
            it("should find the module names");
        });

        describe("extractModules", function () {
            it("should find the modules");
        });
    });

}());
<commit_msg>fix argument order for assert.equal calls<commit_after>/*jslint node: true */
/*global describe, it */
(function () {
    "use strict";

    var assert = require("assert"),
        uglifyJS = require("uglifyjs"),
        unbrowserify = require("../unbrowserify");

    function parseString(code, filename) {
        var ast = uglifyJS.parse(code, {filename: filename});
        ast.figure_out_scope();
        return ast;
    }

    describe("unbrowserify", function () {
        describe("findMainFunction", function () {
            it("should find the main function", function () {
                var ast = parseString("var foo; !function e(){ }(foo);"),
                    f = unbrowserify.findMainFunction(ast);

                assert.equal(f instanceof uglifyJS.AST_Call, true);
                assert.equal(f.expression.name.name, "e");
            });

            it("should find the first function if multiple defined", function () {
                var ast = parseString("var foo; !function e(){ }(foo); !function f(){ }(foo);"),
                    f = unbrowserify.findMainFunction(ast);

                assert.equal(f instanceof uglifyJS.AST_Call, true);
                assert.equal(f.expression.name.name, "e");
            });

            it("should return undefined if no functions are defined", function () {
                var ast = parseString("var foo;"),
                    f = unbrowserify.findMainFunction(ast);

                assert.equal(f, undefined);
            });
        });

        describe("extractModuleNames", function () {
            it("should find the module names");
        });

        describe("extractModules", function () {
            it("should find the modules");
        });
    });

}());
<|endoftext|>