<commit_before>var WEBRTC = require('../');

var config = {
  iceServers: [
    {
      url: 'stun:stun.l.google.com:19302',
    },
  ],
};

var constraints = {
  audio: true,
  video: true,
  optional: [
    {
      DtlsSrtpKeyAgreement: false,
    },
  ],
  mandatory: {
    OfferToReceiveAudio: true,
    OfferToReceiveVideo: true,
  },
};

function P2P(alice, bob) {
  function showState() {
    console.log('Alice State:', alice.signalingState);
    console.log('Bob State:', bob.signalingState);
  }

  alice.onicecandidate = function(event) {
    var candidate = event.candidate || event;
    bob.addIceCandidate(candidate);
  };

  bob.onicecandidate = function(event) {
    var candidate = event.candidate || event;
    alice.addIceCandidate(candidate);
  };

  alice.onnegotiationneeded = function() {
    showState();

    alice.createOffer(function(sdp) {
      showState();

      alice.setLocalDescription(sdp, function() {
        showState();

        bob.setRemoteDescription(sdp, function() {
          showState();

          bob.createAnswer(function(sdp) {
            showState();

            bob.setLocalDescription(sdp, function() {
              showState();

              alice.setRemoteDescription(sdp, function() {
                showState();
              });
            });
          });
        });
      });
    });
  };

  bob.onnegotiationneeded = function() {
    showState();

    bob.createOffer(function(sdp) {
      showState();

      bob.setLocalDescription(sdp, function() {
        showState();

        alice.setRemoteDescription(sdp, function() {
          showState();

          alice.createAnswer(function(sdp) {
            showState();

            alice.setLocalDescription(sdp, function() {
              showState();

              bob.setRemoteDescription(sdp, function() {
                showState();
              });
            });
          });
        });
      });
    });
  };

  alice.onaddstream = function(stream) {
    if (stream) {
      console.log('Alice got mediaStream');
    }
  };

  bob.onaddstream = function(stream) {
    if (stream) {
      console.log('Bob got mediaStream');
    }
  };
}

var alice = new WEBRTC.RTCPeerConnection(config, constraints);
var bob = new WEBRTC.RTCPeerConnection(config, constraints);

P2P(alice, bob);

function onSuccess(stream) {
  if (stream) {
    console.log('Alice: new mediaStream');
    alice.addStream(stream);

    setTimeout(function () {
      alice.close();
      bob.close();
    }, 10000);
  }
}

function onError(error) {
  throw error;
}

WEBRTC.getUserMedia({
  audio: true,
  video: true,
}, onSuccess, onError);
<commit_msg>Disable DtlsSrtpKeyAgreement<commit_after>var WEBRTC = require('../');

var config = {
  iceServers: [
    {
      url: 'stun:stun.l.google.com:19302',
    },
  ],
};

var constraints = {
  audio: true,
  video: true,
  optional: [
    {
      DtlsSrtpKeyAgreement: true,
    },
  ],
  mandatory: {
    OfferToReceiveAudio: true,
    OfferToReceiveVideo: true,
  },
};

function P2P(alice, bob) {
  function showState() {
    console.log('Alice State:', alice.signalingState);
    console.log('Bob State:', bob.signalingState);
  }

  alice.onicecandidate = function(event) {
    var candidate = event.candidate || event;
    bob.addIceCandidate(candidate);
  };

  bob.onicecandidate = function(event) {
    var candidate = event.candidate || event;
    alice.addIceCandidate(candidate);
  };

  alice.onnegotiationneeded = function() {
    showState();

    alice.createOffer(function(sdp) {
      showState();

      alice.setLocalDescription(sdp, function() {
        showState();

        bob.setRemoteDescription(sdp, function() {
          showState();

          bob.createAnswer(function(sdp) {
            showState();

            bob.setLocalDescription(sdp, function() {
              showState();

              alice.setRemoteDescription(sdp, function() {
                showState();
              });
            });
          });
        });
      });
    });
  };

  bob.onnegotiationneeded = function() {
    showState();

    bob.createOffer(function(sdp) {
      showState();

      bob.setLocalDescription(sdp, function() {
        showState();

        alice.setRemoteDescription(sdp, function() {
          showState();

          alice.createAnswer(function(sdp) {
            showState();

            alice.setLocalDescription(sdp, function() {
              showState();

              bob.setRemoteDescription(sdp, function() {
                showState();
              });
            });
          });
        });
      });
    });
  };

  alice.onaddstream = function(stream) {
    if (stream) {
      console.log('Alice got mediaStream');
    }
  };

  bob.onaddstream = function(stream) {
    if (stream) {
      console.log('Bob got mediaStream');
    }
  };
}

var alice = new WEBRTC.RTCPeerConnection(config, constraints);
var bob = new WEBRTC.RTCPeerConnection(config, constraints);

P2P(alice, bob);

function onSuccess(stream) {
  if (stream) {
    console.log('Alice: new mediaStream');
    alice.addStream(stream);

    setTimeout(function () {
      alice.close();
      bob.close();
    }, 10000);
  }
}

function onError(error) {
  throw error;
}

WEBRTC.getUserMedia({
  audio: true,
  video: true,
}, onSuccess, onError);
<|endoftext|>


<commit_before>'use strict';

var random = require('../').random;
var tape = require('tape');
var Handlebars = require('handlebars');

Handlebars.registerHelper(random.name, random);

tape('random', function (test) {
  var template = Handlebars.compile('{{random items}}');
  var items;
  var result;

  test.plan(2);

  items = ['a', 'b', 'c'];
  result = template({ items: items });
  test.ok(items.indexOf(result) !== -1, 'Works');

  try {
    result = template({ items: 'not an array' });
  } catch (err) {
    test.pass('Errors when passed a non-array');
  }
});
<commit_msg>Update random helper assertion to use t.thows() for exception checking<commit_after>'use strict';

var random = require('../').random;
var tape = require('tape');
var Handlebars = require('handlebars');

Handlebars.registerHelper(random.name, random);

tape('random', function (test) {
  var template = Handlebars.compile('{{random items}}');
  var items;
  var result;

  test.plan(2);

  items = ['a', 'b', 'c'];
  result = template({ items: items });
  test.ok(items.indexOf(result) !== -1, 'Works');

  test.throws(
    function () {
      template({ items: 'not an array' })
    },
    /passed an Array\.$/,
    'Errors when passed a non-array'
  );
});
<|endoftext|>


<commit_before>import {expect} from 'chai';
import {fromJS, Map} from 'immutable';
import reduce from '../src/reduce';

describe('reduce', () => {
  it('reduces to a default state', () => {
    const action = {type: 'LOAD_MOVIES', movies: ['Trainspotting']};
    const nextState = reduce(undefined, action);

    expect(nextState).to.equal(fromJS({
      movies: ['Trainspotting']
    }));
  });

  it('reduces LOAD_MOVIES', () => {
    const state = Map();
    const action = {type: 'LOAD_MOVIES', movies: ['trainspotting']};
    const nextState = reduce(state, action);

    expect(nextState).to.equal(
      fromJS({movies: ['trainspotting']})
    );
  });

  it('reduces NEXT', () => {
    const state = fromJS({movies: ['trainspotting', '28 days later']});
    const action = {type: 'NEXT'};
    const nextState = reduce(state, action);

    expect(nextState).to.equal(
      fromJS({
        vote: {pair: ['trainspotting', '28 days later']},
        movies: []
      })
    );
  });

  it('reduces VOTE', () => {
    const state = fromJS({
      vote: {pair: ['trainspotting', '28 days later']},
      movies: []
    });

    const action = {type: 'VOTE', movie: 'trainspotting'};
    const nextState = reduce(state, action);

    expect(nextState).to.equal(
      fromJS({
        vote: {
          pair: ['trainspotting', '28 days later'],
          tally: {'trainspotting': 1}
        },
        movies: []
      })
    );
  });
});
<commit_msg>use reduce as “reducer”<commit_after>import {expect} from 'chai';
import {fromJS, Map} from 'immutable';
import reduce from '../src/reduce';

describe('reduce', () => {
  it('reduces to a default state', () => {
    const action = {type: 'LOAD_MOVIES', movies: ['Trainspotting']};
    const nextState = reduce(undefined, action);

    expect(nextState).to.equal(fromJS({
      movies: ['Trainspotting']
    }));
  });

  it('reduces LOAD_MOVIES', () => {
    const state = Map();
    const action = {type: 'LOAD_MOVIES', movies: ['trainspotting']};
    const nextState = reduce(state, action);

    expect(nextState).to.equal(
      fromJS({movies: ['trainspotting']})
    );
  });

  it('reduces NEXT', () => {
    const state = fromJS({movies: ['trainspotting', '28 days later']});
    const action = {type: 'NEXT'};
    const nextState = reduce(state, action);

    expect(nextState).to.equal(
      fromJS({
        vote: {pair: ['trainspotting', '28 days later']},
        movies: []
      })
    );
  });

  it('reduces VOTE', () => {
    const state = fromJS({
      vote: {pair: ['trainspotting', '28 days later']},
      movies: []
    });

    const action = {type: 'VOTE', movie: 'trainspotting'};
    const nextState = reduce(state, action);

    expect(nextState).to.equal(
      fromJS({
        vote: {
          pair: ['trainspotting', '28 days later'],
          tally: {'trainspotting': 1}
        },
        movies: []
      })
    );
  });

  it('can be used as reducer', () => {
    const actions = [
      {type: 'LOAD_MOVIES', movies: ['trainspotting', '28 days later']},
      {type: 'NEXT'},
      {type: 'VOTE', movie: 'trainspotting'},
      {type: 'VOTE', movie: '28 Days Later'},
      {type: 'VOTE', movie: 'trainspotting'},
      {type: 'NEXT'}
    ];

    const finalState = actions.reduce(reduce, Map());

    expect(finalState).to.equal(fromJS({
      winner: 'trainspotting'
    }));
  });
});
<|endoftext|>


<commit_before>"use strict";
/*global describe:false, it:false, before: false, after: false, beforeEach: false, afterEach: false, expect:false */

var request = require("supertest");
var expect = require("chai").expect;
var app = require("../app");
var db = require("../db-connector");
var pageFactory = require("./factories/page");
var Page = require("../models/page");
var async = require("async");

describe.only("Search", function () {
    before(db.connect);
    beforeEach(function (cb) {
        async.parallel([
            function (cb) {
                var newPage = pageFactory();
                var page = new Page(newPage);
                page.path = "/foobar";
                page.save(cb);
            },
            function (cb) {
                var newPage = pageFactory();
                var page = new Page(newPage);
                page.path = "/foobaz";
                page.title = "Baz";
                page.content = "content baz";
                page.tags = "foo, baz";
                page.save(cb);
            }
        ], cb);
    });
    afterEach(db.wipe);
    after(db.close);

    it("should return search results", function (done) {
        request(app)
            .get("/search?q=foo")
            .expect(200)
            .end(function (err, res) {
            expect(res.text).to.include("Foo Title");
            expect(res.text).to.include("Baz");
            expect(res.text).to.include("/foobar");
            expect(res.text).to.include("/foobaz");

            done(err);
        });
    });

    it("should order the results correctly", function (done) {
        request(app)
            .get("/search?q=foo")
            .expect(200)
            .end(function (err, res) {
                expect(res.text).to.match(/Search Results.*Foo Title.*Baz/);
                expect(res.text).to.not.match(/Search Results.*Baz.*Foo Title/);

                done();
            });
    });
});
<commit_msg>add test for not matching search<commit_after>"use strict";
/*global describe:false, it:false, before: false, after: false, beforeEach: false, afterEach: false, expect:false */

var request = require("supertest");
var expect = require("chai").expect;
var app = require("../app");
var db = require("../db-connector");
var pageFactory = require("./factories/page");
var Page = require("../models/page");
var async = require("async");

describe("Search", function () {
    before(db.connect);
    beforeEach(function (cb) {
        async.parallel([
            function (cb) {
                var newPage = pageFactory();
                var page = new Page(newPage);
                page.path = "/foobar";
                page.save(cb);
            },
            function (cb) {
                var newPage = pageFactory();
                var page = new Page(newPage);
                page.path = "/foobaz";
                page.title = "Baz";
                page.content = "content baz";
                page.tags = "foo, baz";
                page.save(cb);
            }
        ], cb);
    });
    afterEach(db.wipe);
    after(db.close);

    it("should return search results", function (done) {
        request(app)
            .get("/search?q=foo")
            .expect(200)
            .end(function (err, res) {
            expect(res.text).to.include("Foo Title");
            expect(res.text).to.include("Baz");
            expect(res.text).to.include("/foobar");
            expect(res.text).to.include("/foobaz");

            done(err);
        });
    });

    it("should order the results correctly", function (done) {
        request(app)
            .get("/search?q=foo")
            .expect(200)
            .end(function (err, res) {
                expect(res.text).to.match(/Search Results.*Foo Title.*Baz/);
                expect(res.text).to.not.match(/Search Results.*Baz.*Foo Title/);

                done();
            });
    });

    it("should order the results correctly", function (done) {
        request(app)
            .get("/search?q=baz")
            .expect(200)
            .end(function (err, res) {
                expect(res.text).to.match(/Search Results.*Baz/);
                expect(res.text).to.not.match(/Search Results.*Foo Title/);

                done();
            });
    });

});
<|endoftext|>


<commit_before>'use strict'

var hat = require('hat')
var Socket = require('../src/Socket')

describe('#AppRTC-socket features', function () {
  this.timeout(5000)

  it('two sockets should be able to ping-pong', function (done) {
    var aliceId = hat()
    var bobId = hat()
    var socketAlice = new Socket(aliceId, bobId)
    var socketBob = new Socket(bobId, aliceId)

    var testQuestion = 'What is the meaning of life?'
    var testAnswer = 'A movie.'
    var testRuns = 10
    var messagesSent = 0

    var sendRequest = function () {
      socketAlice.send(testQuestion)
    }

    var sendReply = function () {
      socketBob.send(testAnswer)
    }

    socketAlice.on('message', function (message) {
      console.log('alice received response: ' + message)
      if (messagesSent === testRuns) {
        socketAlice.closeP()
          .then(function () {
            return socketBob.closeP()
          })
          .then(function () {
            console.log("that's all folks")
            done()
          })
          .catch(function (error) {
            done(error)
          })
      } else {
        sendRequest()
        messagesSent++
      }
    })

    socketBob.on('message', function (message) {
      console.log('bob received request: ' + message)
      sendReply()
    })

    socketAlice.on('error', done)
    socketBob.on('error', done)

    socketAlice.connectP()
      .then(function () {
        return socketBob.connectP()
      })
      .then(function () {
        sendRequest()
        messagesSent++
      })
      .catch(function (error) {
        done(error)
      })
  })
})
<commit_msg>increased timeout of mocha tests to 10 seconds<commit_after>'use strict'

var hat = require('hat')
var Socket = require('../src/Socket')

describe('#AppRTC-socket features', function () {
  this.timeout(10000)

  it('two sockets should be able to ping-pong', function (done) {
    var aliceId = hat()
    var bobId = hat()
    var socketAlice = new Socket(aliceId, bobId)
    var socketBob = new Socket(bobId, aliceId)

    var testQuestion = 'What is the meaning of life?'
    var testAnswer = 'A movie.'
    var testRuns = 10
    var messagesSent = 0

    var sendRequest = function () {
      socketAlice.send(testQuestion)
    }

    var sendReply = function () {
      socketBob.send(testAnswer)
    }

    socketAlice.on('message', function (message) {
      console.log('alice received response: ' + message)
      if (messagesSent === testRuns) {
        socketAlice.closeP()
          .then(function () {
            return socketBob.closeP()
          })
          .then(function () {
            console.log("that's all folks")
            done()
          })
          .catch(function (error) {
            done(error)
          })
      } else {
        sendRequest()
        messagesSent++
      }
    })

    socketBob.on('message', function (message) {
      console.log('bob received request: ' + message)
      sendReply()
    })

    socketAlice.on('error', done)
    socketBob.on('error', done)

    socketAlice.connectP()
      .then(function () {
        return socketBob.connectP()
      })
      .then(function () {
        sendRequest()
        messagesSent++
      })
      .catch(function (error) {
        done(error)
      })
  })
})
<|endoftext|>


<commit_before>var SyncError = require('logux-sync').SyncError
var TestTime = require('logux-core').TestTime
var BaseSync = require('logux-sync').BaseSync
var TestPair = require('logux-sync').TestPair

var status = require('../status')

function wait (ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms)
  })
}

function createTest (options) {
  var pair = new TestPair()
  pair.leftSync = new BaseSync('client', TestTime.getLog(), pair.left)
  pair.leftSync.catch(function () {})
  return pair.left.connect().then(function () {
    pair.calls = []
    pair.args = []
    status({ sync: pair.leftSync }, function (state, details) {
      pair.calls.push(state)
      pair.args.push(details)
    }, options)
    return pair
  })
}

it('notifies about states', function () {
  return createTest({ duration: 10 }).then(function (test) {
    test.leftSync.connected = false
    test.leftSync.setState('disconnected')
    test.leftSync.setState('connecting')
    wait(105).then(function () {
      test.leftSync.connected = true
      test.leftSync.setState('synchronized')
      expect(test.calls).toEqual([
        'disconnected', 'connecting', 'synchronized'
      ])
    })
  })
})

it('notifies only about wait for sync actions', function () {
  var test
  return createTest({ duration: 10 }).then(function (created) {
    test = created

    test.leftSync.connected = false
    test.leftSync.setState('disconnected')
    expect(test.calls).toEqual(['disconnected'])

    return test.leftSync.log.add({ type: 'A' }, { sync: true, reasons: ['t'] })
  }).then(function () {
    test.leftSync.setState('connecting')
    return wait(105).then(function () {
      test.leftSync.setState('disconnected')
      test.leftSync.setState('connecting')
      return wait(105).then(function () {
        test.leftSync.setState('sending')
        test.leftSync.setState('synchronized')
        expect(test.calls).toEqual([
          'disconnected',
          'wait',
          'connectingAfterWait',
          'wait',
          'connectingAfterWait',
          'sendingAfterWait',
          'synchronizedAfterWait'
        ])
        return wait(15)
      })
    })
  }).then(function () {
    expect(test.calls).toEqual([
      'disconnected',
      'wait',
      'connectingAfterWait',
      'wait',
      'connectingAfterWait',
      'sendingAfterWait',
      'synchronizedAfterWait',
      'synchronized'
    ])
  })
})

it('skips "connecting" notification if it took less than 100ms', function () {
  return createTest().then(function (test) {
    test.leftSync.connected = false
    test.leftSync.setState('disconnected')
    test.leftSync.setState('connecting')
    test.leftSync.connected = true
    test.leftSync.setState('synchronized')
    expect(test.calls).toEqual(['disconnected', 'synchronized'])
  })
})

it('notifies about synchronization error', function () {
  return createTest().then(function (test) {
    var error1 = { type: 'any error' }
    test.leftSync.emitter.emit('error', error1)

    var error2 = new SyncError(test.leftSync, 'test', 'type', true)
    test.leftSync.emitter.emit('clientError', error2)

    expect(test.calls).toEqual(['syncError', 'syncError'])
    expect(test.args).toEqual([{ error: error1 }, { error: error2 }])
  })
})

it('ignores timeout error', function () {
  return createTest().then(function (test) {
    var error1 = { type: 'timeout' }
    test.leftSync.emitter.emit('error', error1)
    expect(test.calls).toEqual([])
  })
})

it('notifies about old client', function () {
  return createTest().then(function (test) {
    var protocol = new SyncError(test.leftSync, 'wrong-protocol', { })
    test.leftSync.emitter.emit('error', protocol)

    var subprotocol = new SyncError(test.leftSync, 'wrong-subprotocol', { })
    test.leftSync.emitter.emit('error', subprotocol)

    expect(test.calls).toEqual(['protocolError', 'protocolError'])
  })
})

it('notifies about server error', function () {
  return createTest().then(function (test) {
    test.leftSync.log.add({ type: 'logux/undo', reason: 'error' })
    expect(test.calls).toEqual(['sending', 'error'])
    expect(test.args[1].action.type).toEqual('logux/undo')
    expect(test.args[1].meta.time).toEqual(1)
  })
})

it('notifies about problem with access', function () {
  return createTest().then(function (test) {
    test.leftSync.log.add({ type: 'logux/undo', reason: 'denied' })
    expect(test.calls).toEqual(['sending', 'denied'])
    expect(test.args[1].action.type).toEqual('logux/undo')
    expect(test.args[1].meta.time).toEqual(1)
  })
})

it('removes listeners', function () {
  var pair = new TestPair()
  var sync = new BaseSync('client', TestTime.getLog(), pair.left)

  var calls = 0
  var unbind = status({ sync: sync }, function (state) {
    if (state === 'denied') {
      calls += 1
    }
  })

  sync.log.add({ type: 'logux/undo', reason: 'denied' })
  unbind()
  sync.log.add({ type: 'logux/undo', reason: 'denied' })

  expect(calls).toEqual(1)
})
<commit_msg>Clean up tests<commit_after>var SyncError = require('logux-sync').SyncError
var TestTime = require('logux-core').TestTime
var BaseSync = require('logux-sync').BaseSync
var TestPair = require('logux-sync').TestPair

var status = require('../status')

function wait (ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms)
  })
}

function createTest (options) {
  var pair = new TestPair()
  pair.leftSync = new BaseSync('client', TestTime.getLog(), pair.left)
  pair.leftSync.catch(function () {})
  return pair.left.connect().then(function () {
    pair.calls = []
    pair.args = []
    status({ sync: pair.leftSync }, function (state, details) {
      pair.calls.push(state)
      pair.args.push(details)
    }, options)
    return pair
  })
}

it('notifies about states', function () {
  var test
  return createTest().then(function (created) {
    test = created
    test.leftSync.connected = false
    test.leftSync.setState('disconnected')
    test.leftSync.setState('connecting')
    return wait(105)
  }).then(function () {
    test.leftSync.connected = true
    test.leftSync.setState('synchronized')
    expect(test.calls).toEqual([
      'disconnected', 'connecting', 'synchronized'
    ])
  })
})

it('notifies only about wait for sync actions', function () {
  var test
  return createTest({ duration: 10 }).then(function (created) {
    test = created

    test.leftSync.connected = false
    test.leftSync.setState('disconnected')
    expect(test.calls).toEqual(['disconnected'])

    return test.leftSync.log.add({ type: 'A' }, { sync: true, reasons: ['t'] })
  }).then(function () {
    test.leftSync.setState('connecting')
    return wait(105)
  }).then(function () {
    test.leftSync.setState('disconnected')
    test.leftSync.setState('connecting')
    return wait(105)
  }).then(function () {
    test.leftSync.setState('sending')
    test.leftSync.setState('synchronized')
    expect(test.calls).toEqual([
      'disconnected',
      'wait',
      'connectingAfterWait',
      'wait',
      'connectingAfterWait',
      'sendingAfterWait',
      'synchronizedAfterWait'
    ])
    return wait(15)
  }).then(function () {
    expect(test.calls).toEqual([
      'disconnected',
      'wait',
      'connectingAfterWait',
      'wait',
      'connectingAfterWait',
      'sendingAfterWait',
      'synchronizedAfterWait',
      'synchronized'
    ])
  })
})

it('skips connecting notification if it took less than 100ms', function () {
  return createTest().then(function (test) {
    test.leftSync.connected = false
    test.leftSync.setState('disconnected')
    test.leftSync.setState('connecting')
    test.leftSync.connected = true
    test.leftSync.setState('synchronized')
    expect(test.calls).toEqual(['disconnected', 'synchronized'])
  })
})

it('notifies about synchronization error', function () {
  return createTest().then(function (test) {
    var error1 = { type: 'any error' }
    test.leftSync.emitter.emit('error', error1)

    var error2 = new SyncError(test.leftSync, 'test', 'type', true)
    test.leftSync.emitter.emit('clientError', error2)

    expect(test.calls).toEqual(['syncError', 'syncError'])
    expect(test.args).toEqual([{ error: error1 }, { error: error2 }])
  })
})

it('ignores timeout error', function () {
  return createTest().then(function (test) {
    var error1 = { type: 'timeout' }
    test.leftSync.emitter.emit('error', error1)
    expect(test.calls).toEqual([])
  })
})

it('notifies about old client', function () {
  return createTest().then(function (test) {
    var protocol = new SyncError(test.leftSync, 'wrong-protocol', { })
    test.leftSync.emitter.emit('error', protocol)

    var subprotocol = new SyncError(test.leftSync, 'wrong-subprotocol', { })
    test.leftSync.emitter.emit('error', subprotocol)

    expect(test.calls).toEqual(['protocolError', 'protocolError'])
  })
})

it('notifies about server error', function () {
  return createTest().then(function (test) {
    test.leftSync.log.add({ type: 'logux/undo', reason: 'error' })
    expect(test.calls).toEqual(['sending', 'error'])
    expect(test.args[1].action.type).toEqual('logux/undo')
    expect(test.args[1].meta.time).toEqual(1)
  })
})

it('notifies about problem with access', function () {
  return createTest().then(function (test) {
    test.leftSync.log.add({ type: 'logux/undo', reason: 'denied' })
    expect(test.calls).toEqual(['sending', 'denied'])
    expect(test.args[1].action.type).toEqual('logux/undo')
    expect(test.args[1].meta.time).toEqual(1)
  })
})

it('removes listeners', function () {
  var pair = new TestPair()
  var sync = new BaseSync('client', TestTime.getLog(), pair.left)

  var calls = 0
  var unbind = status({ sync: sync }, function (state) {
    if (state === 'denied') {
      calls += 1
    }
  })

  sync.log.add({ type: 'logux/undo', reason: 'denied' })
  unbind()
  sync.log.add({ type: 'logux/undo', reason: 'denied' })

  expect(calls).toEqual(1)
})
<|endoftext|>


<commit_before>"use strict";

describe("stream/pipe", function () {

    it("chains an IReadableStream with a IWritableStream", function (done) {
        var iWritableStream = new gpf.stream.WritableString();
        gpf.stream.pipe(new gpf.stream.ReadableString("Hello World"), iWritableStream)
            .then(function () {
                assert(iWritableStream.toString() === "Hello World");
                done();
            })["catch"](done);
    });

});
<commit_msg>WIP (#202)<commit_after>"use strict";

describe("stream/pipe", function () {

    describe("parameters validation", function () {

        it("fails if the first parameter is not an IReadableStream", function () {
            var exceptionCaught;
            try {
                gpf.stream.pipe({});
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof gpf.Error.InterfaceExpected);
        });

        it("fails if no destination", function () {
            var exceptionCaught;
            try {
                gpf.stream.pipe({
                    read: function (iWritableStream) {
                        return Promise.resolve(iWritableStream);
                    }
                });
            } catch (e) {
                exceptionCaught = e;
            }
            assert(exceptionCaught instanceof gpf.Error.InterfaceExpected);
        });

    });

    it("chains an IReadableStream with a IWritableStream", function (done) {
        var iWritableStream = new gpf.stream.WritableString();
        gpf.stream.pipe(new gpf.stream.ReadableString("Hello World"), iWritableStream)
            .then(function () {
                assert(iWritableStream.toString() === "Hello World");
                done();
            })["catch"](done);
    });

});
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var assert = require('proclaim');
var sinon = require('sinon');

var eventEmitter = require('minimal-event-emitter');
var inherits = require('../../src/util/inherits');

var Stage = require('../../src/stages/Stage');

// Stage is an abstract class and cannot be instantiated directly.
// We must stub methods and properties expected to be implemented by subclasses.
function TestStage() {
  this.constructor.super_.call(this);
  this._validateLayer = sinon.stub();
}

inherits(TestStage, Stage);

// Mock layer.
function MockLayer() {}

eventEmitter(MockLayer);

suite('Stage', function() {

  test('manages the layer stack correctly', function() {
    var stage = new TestStage();

    var layer1 = new MockLayer();
    var layer2 = new MockLayer();
    var layer3 = new MockLayer();

    assert.isFalse(stage.hasLayer(layer1));
    assert.deepEqual([], stage.listLayers());
    assert.throws(function() { stage.addLayer(layer1, 1); });
    assert.throws(function() { stage.moveLayer(layer1, 1); });
    assert.throws(function() { stage.removeLayer(layer1); });

    stage.addLayer(layer1);
    assert.isTrue(stage.hasLayer(layer1));
    assert.deepEqual([layer1], stage.listLayers());

    stage.addLayer(layer2, 1);
    assert.isTrue(stage.hasLayer(layer2));
    assert.deepEqual([layer1, layer2], stage.listLayers());

    assert.throws(function() { stage.addLayer(layer3, -1); });
    assert.throws(function() { stage.addLayer(layer3, 3); });

    stage.addLayer(layer3, 1);
    assert.isTrue(stage.hasLayer(layer3));
    assert.deepEqual([layer1, layer3, layer2], stage.listLayers());

    assert.throws(function() { stage.moveLayer(layer1, -1); });
    assert.throws(function() { stage.moveLayer(layer1, 3); });

    stage.moveLayer(layer1, 2);
    assert.isTrue(stage.hasLayer(layer1));
    assert.deepEqual([layer3, layer2, layer1], stage.listLayers());

    stage.removeLayer(layer2);
    assert.isFalse(stage.hasLayer(layer2));
    assert.deepEqual([layer1, layer3], stage.listLayers());

    stage.removeLayer(layer1);
    assert.isFalse(stage.hasLayer(layer1));
    assert.deepEqual([layer3], stage.listLayers());
  });

  test('throws if layer validation fails', function() {
    var stage = new TestStage();
    var layer = new MockLayer();

    stage._validateLayer.throws();
    assert.throws(function() { stage.addLayer(layer); });
  });

});
<commit_msg>Test that Stage emits invalidation events correctly.<commit_after>/*
 * Copyright 2016 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

var assert = require('proclaim');
var sinon = require('sinon');

var eventEmitter = require('minimal-event-emitter');
var inherits = require('../../src/util/inherits');

var Stage = require('../../src/stages/Stage');

// Stage is an abstract class and cannot be instantiated directly.
// We must stub methods and properties expected to be implemented by subclasses.
function TestStage() {
  this.constructor.super_.call(this);
  this._validateLayer = sinon.stub();
}

inherits(TestStage, Stage);

// Mock layer.
function MockLayer() {}

eventEmitter(MockLayer);

suite('Stage', function() {

  test('manages the layer stack correctly', function() {
    var stage = new TestStage();

    var layer1 = new MockLayer();
    var layer2 = new MockLayer();
    var layer3 = new MockLayer();

    assert.isFalse(stage.hasLayer(layer1));
    assert.deepEqual([], stage.listLayers());
    assert.throws(function() { stage.addLayer(layer1, 1); });
    assert.throws(function() { stage.moveLayer(layer1, 1); });
    assert.throws(function() { stage.removeLayer(layer1); });

    stage.addLayer(layer1);
    assert.isTrue(stage.hasLayer(layer1));
    assert.deepEqual([layer1], stage.listLayers());

    stage.addLayer(layer2, 1);
    assert.isTrue(stage.hasLayer(layer2));
    assert.deepEqual([layer1, layer2], stage.listLayers());

    assert.throws(function() { stage.addLayer(layer3, -1); });
    assert.throws(function() { stage.addLayer(layer3, 3); });

    stage.addLayer(layer3, 1);
    assert.isTrue(stage.hasLayer(layer3));
    assert.deepEqual([layer1, layer3, layer2], stage.listLayers());

    assert.throws(function() { stage.moveLayer(layer1, -1); });
    assert.throws(function() { stage.moveLayer(layer1, 3); });

    stage.moveLayer(layer1, 2);
    assert.isTrue(stage.hasLayer(layer1));
    assert.deepEqual([layer3, layer2, layer1], stage.listLayers());

    stage.removeLayer(layer2);
    assert.isFalse(stage.hasLayer(layer2));
    assert.deepEqual([layer1, layer3], stage.listLayers());

    stage.removeLayer(layer1);
    assert.isFalse(stage.hasLayer(layer1));
    assert.deepEqual([layer3], stage.listLayers());
  });

  test('throws if layer validation fails', function() {
    var stage = new TestStage();
    var layer = new MockLayer();

    stage._validateLayer.throws();
    assert.throws(function() { stage.addLayer(layer); });
  });

  test('emits invalidation event', function() {
    var stage = new TestStage();
    var layer = new MockLayer();

    var spy = sinon.spy();
    stage.addEventListener('renderInvalid', spy);

    stage.addLayer(layer);
    assert(spy.callCount === 1);

    layer.emit('viewChange');
    layer.emit('effectsChange');
    layer.emit('fixedLevelChange');
    layer.emit('textureStoreChange');
    assert(spy.callCount === 5);

    stage.moveLayer(layer, 0);
    assert(spy.callCount === 6);

    stage.removeLayer(layer);
    assert(spy.callCount === 7);

    layer.emit('viewChange');
    layer.emit('effectsChange');
    layer.emit('fixedLevelChange');
    layer.emit('textureStoreChange');
    assert(spy.callCount === 7);
  });
});
<|endoftext|>


<commit_before>describe('temper', function () {
  'use strict';

  var assume = require('assume')
    , Temper = require('../')
    , path = require('path')
    , fs = require('fs')
    , temper;

  beforeEach(function () {
    temper = new Temper();
  });

  afterEach(function () {
    temper.destroy();
  });

  it('has list with supported types', function () {
    assume(temper.supported).to.have.property('.ejs');
    assume(temper.supported).to.have.property('.jade');
    assume(temper.supported).to.have.property('.mustache');
    assume(temper.supported).to.have.property('.hbs');
    assume(temper.supported).to.have.property('.jsx');
    assume(temper.supported).to.have.property('.handlebars');

    assume(temper.supported['.ejs']).to.include('ejs');
    assume(temper.supported['.jade']).to.include('jade');
    assume(temper.supported['.mustache']).to.include('hogan.js');
    assume(temper.supported['.mustache']).to.include('mustache');
    assume(temper.supported['.mustache']).to.include('handlebars');
    assume(temper.supported['.hbs']).to.include('handlebars');
    assume(temper.supported['.handlebars']).to.include('handlebars');
    assume(temper.supported['.html']).to.include('html');
    assume(temper.supported['.jsx']).to.include('react-jsx');
  });

  describe('#read', function () {
    it('should read the file contents and return a string', function () {
      var data = temper.read(__dirname +'/fixtures/template.jade');

      assume(data).is.a('string');
      assume(data).to.contain('doctype 5');
    });

    it('should cache the file lookup', function () {
      var data = temper.read(__dirname +'/fixtures/template.jade');
      assume(data).is.a('string');
      assume(data).to.contain('doctype 5');

      assume(temper.file).to.have.property(__dirname +'/fixtures/template.jade');

      data = temper.read(__dirname +'/fixtures/template.jade');
      assume(data).is.a('string');
      assume(data).to.contain('doctype 5');
    });
  });

  describe('#require', function () {
    it('requires the module and returns it', function () {
      var jade = temper.require('jade');

      assume(jade).equals(require('jade'));
    });

    it('caches the module', function () {
      var jade = temper.require('jade');

      assume(jade).equals(require('jade'));
      assume(temper.required.jade).equals(require('jade'));
    });

    it('registers engine `null` for HTML', function () {
      var html = temper.require('html');

      assume(html).equals(null);
      assume(temper.required.html).equals(null);
    });

    it('throws an error if a module doesnt exist', function () {
      try { temper.require('cowdoodlesack'); }
      catch (e) {
        assume(e).to.be.instanceOf(Error);
        assume(e.message).to.include('npm install');
        return assume(e.message).to.include('cowdoodlesack');
      }

      throw new Error('I should have failed');
    });
  });

  describe('#discover', function () {
    it('should throw an error for a unknown extension', function () {
      try { temper.discover('/care/bear/path/template.trololol'); }
      catch (e) {
        assume(e).to.be.instanceOf(Error);
        assume(e.message).to.include('trololol');
        return assume(e.message).to.include('Unknown file extension');
      }

      throw new Error('I should have failed');
    });

    it('returns the correct engine', function () {
      assume(temper.discover('foo.jade')).equals('jade');
      assume(temper.discover('foo.ejs')).equals('ejs');
      assume(temper.discover('foo.mustache')).equals('hogan.js');
      assume(temper.discover('foo.html')).equals('html');
    });
  });

  describe('#compile', function () {
    describe('jade', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'jade.jade'), 'utf-8');

      it('compiles a jade template', function () {
        var obj = temper.compile(template, {
          engine: 'jade'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' })).equals('
content
');
        assume(obj.engine).equals('jade');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('react-jsx', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'react-jsx.jsx'), 'utf-8');

      it('compiles a jsx template', function () {
        var obj = temper.compile(template, {
          engine: 'react-jsx'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' }, { html: true })).equals('
content
');
        assume(obj.engine).equals('react-jsx');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('ejs', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'ejs.ejs'), 'utf-8');

      it('compiles a ejs template', function () {
        var obj = temper.compile(template, {
          engine: 'ejs'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' }).trim()).equals('
content
');
        assume(obj.engine).equals('ejs');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('hogan.js', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'hogan.mustache'), 'utf-8');

      it('compiles a .mustache template', function () {
        var obj = temper.compile(template, {
          engine: 'hogan.js'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' }).trim()).equals('
content
');
        assume(obj.engine).equals('hogan.js');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('handlebars', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'handlebars.handlebars'), 'utf-8');

      it('compiles a .handlebars template', function () {
        var obj = temper.compile(template, {
          engine: 'handlebars'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' }).trim()).equals('
content
');
        assume(obj.engine).equals('handlebars');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('.html', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'html.html'), 'utf-8');

      it('returns surrogate compiler for HTML', function () {
        var obj = temper.compile(template, {
          engine: 'html'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.library).equals('');
        assume(obj.server).is.a('function');
        assume(obj.engine).equals('html');
        assume(obj.server({ V1: 'content' }).trim()).equals('
content
');

        var client = (new Function('return '+ obj.client))();
        assume(client).is.a('function');
        assume(client({ V1: 'content' }).trim()).equals('
content
');
      });

      it('supports basic replacements of data', function () {
        var obj = temper.compile('
{key}
', {
          engine: 'html'
        });

        obj.client = (new Function('return '+ obj.client))();

        assume(obj.server({ key: 'bar' })).equals('
bar
');
        assume(obj.client({ key: 'bar' })).equals('
bar
');
      });

      it('doesn\'t die when supplied with an Object.create(null)', function () {
        var obj = temper.compile('
{key}
', { engine: 'html' })
          , data = Object.create(null);

        obj.client = (new Function('return '+ obj.client))();

        data.key = 'bar';
        assume(obj.server(data)).equals('
bar
');
        assume(obj.client(data)).equals('
bar
');
      });
    });
  });

  describe('#normalizeName', function () {
    it('handles filenames without special characters', function () {
      var name = temper.normalizeName('/home/templates/template.jade');

      assume(name).equals('template');
    });

    it('handles filenames with special characters in filenames', function () {
      var name = temper.normalizeName('/home/templates/09$-money_$00-test.jade');

      assume(name).equals('$money_$00test');
    });
  });

  describe('#fetch', function () {
    var template = path.join(__dirname, 'fixtures', 'react-jsx.jsx');

    it('returns a compiled thing', function () {
      var obj = temper.fetch(template);

      assume(obj.client).is.a('string');
      assume(obj.library).is.a('string');
      assume(obj.server).is.a('function');
      assume(obj.server({ V1: 'content' }, { html: true })).equals('
content
');
      assume(obj.engine).equals('react-jsx');
      assume(obj.hash).is.a('object');
      assume(obj.hash.client).is.a('string');
      assume(obj.hash.server).is.a('string');
      assume(obj.hash.library).is.a('string');
    });

    it('can cache the compiled result', function () {
      temper.cache = true;

      assume(temper.compiled).does.not.include(template);
      temper.fetch(template);
      assume(temper.compiled).does.include(template);

      temper.compiled[template].foo = 'bar';

      var cached = temper.fetch(template);
      assume(cached.foo).equals('bar');
    });
  });
});
<commit_msg>[test] Adding test for replace edgecase<commit_after>describe('temper', function () {
  'use strict';

  var assume = require('assume')
    , Temper = require('../')
    , path = require('path')
    , fs = require('fs')
    , temper;

  beforeEach(function () {
    temper = new Temper();
  });

  afterEach(function () {
    temper.destroy();
  });

  it('has list with supported types', function () {
    assume(temper.supported).to.have.property('.ejs');
    assume(temper.supported).to.have.property('.jade');
    assume(temper.supported).to.have.property('.mustache');
    assume(temper.supported).to.have.property('.hbs');
    assume(temper.supported).to.have.property('.jsx');
    assume(temper.supported).to.have.property('.handlebars');

    assume(temper.supported['.ejs']).to.include('ejs');
    assume(temper.supported['.jade']).to.include('jade');
    assume(temper.supported['.mustache']).to.include('hogan.js');
    assume(temper.supported['.mustache']).to.include('mustache');
    assume(temper.supported['.mustache']).to.include('handlebars');
    assume(temper.supported['.hbs']).to.include('handlebars');
    assume(temper.supported['.handlebars']).to.include('handlebars');
    assume(temper.supported['.html']).to.include('html');
    assume(temper.supported['.jsx']).to.include('react-jsx');
  });

  describe('#read', function () {
    it('should read the file contents and return a string', function () {
      var data = temper.read(__dirname +'/fixtures/template.jade');

      assume(data).is.a('string');
      assume(data).to.contain('doctype 5');
    });

    it('should cache the file lookup', function () {
      var data = temper.read(__dirname +'/fixtures/template.jade');
      assume(data).is.a('string');
      assume(data).to.contain('doctype 5');

      assume(temper.file).to.have.property(__dirname +'/fixtures/template.jade');

      data = temper.read(__dirname +'/fixtures/template.jade');
      assume(data).is.a('string');
      assume(data).to.contain('doctype 5');
    });
  });

  describe('#require', function () {
    it('requires the module and returns it', function () {
      var jade = temper.require('jade');

      assume(jade).equals(require('jade'));
    });

    it('caches the module', function () {
      var jade = temper.require('jade');

      assume(jade).equals(require('jade'));
      assume(temper.required.jade).equals(require('jade'));
    });

    it('registers engine `null` for HTML', function () {
      var html = temper.require('html');

      assume(html).equals(null);
      assume(temper.required.html).equals(null);
    });

    it('throws an error if a module doesnt exist', function () {
      try { temper.require('cowdoodlesack'); }
      catch (e) {
        assume(e).to.be.instanceOf(Error);
        assume(e.message).to.include('npm install');
        return assume(e.message).to.include('cowdoodlesack');
      }

      throw new Error('I should have failed');
    });
  });

  describe('#discover', function () {
    it('should throw an error for a unknown extension', function () {
      try { temper.discover('/care/bear/path/template.trololol'); }
      catch (e) {
        assume(e).to.be.instanceOf(Error);
        assume(e.message).to.include('trololol');
        return assume(e.message).to.include('Unknown file extension');
      }

      throw new Error('I should have failed');
    });

    it('returns the correct engine', function () {
      assume(temper.discover('foo.jade')).equals('jade');
      assume(temper.discover('foo.ejs')).equals('ejs');
      assume(temper.discover('foo.mustache')).equals('hogan.js');
      assume(temper.discover('foo.html')).equals('html');
    });
  });

  describe('#compile', function () {
    describe('jade', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'jade.jade'), 'utf-8');

      it('compiles a jade template', function () {
        var obj = temper.compile(template, {
          engine: 'jade'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' })).equals('
content
');
        assume(obj.engine).equals('jade');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('react-jsx', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'react-jsx.jsx'), 'utf-8');

      it('compiles a jsx template', function () {
        var obj = temper.compile(template, {
          engine: 'react-jsx'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' }, { html: true })).equals('
content
');
        assume(obj.engine).equals('react-jsx');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('ejs', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'ejs.ejs'), 'utf-8');

      it('compiles a ejs template', function () {
        var obj = temper.compile(template, {
          engine: 'ejs'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' }).trim()).equals('
content
');
        assume(obj.engine).equals('ejs');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('hogan.js', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'hogan.mustache'), 'utf-8');

      it('compiles a .mustache template', function () {
        var obj = temper.compile(template, {
          engine: 'hogan.js'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' }).trim()).equals('
content
');
        assume(obj.engine).equals('hogan.js');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('handlebars', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'handlebars.handlebars'), 'utf-8');

      it('compiles a .handlebars template', function () {
        var obj = temper.compile(template, {
          engine: 'handlebars'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.server).is.a('function');
        assume(obj.server({ V1: 'content' }).trim()).equals('
content
');
        assume(obj.engine).equals('handlebars');
        assume(obj.hash).is.a('object');
        assume(obj.hash.client).is.a('string');
        assume(obj.hash.server).is.a('string');
        assume(obj.hash.library).is.a('string');
      });
    });

    describe('.html', function () {
      var template = fs.readFileSync(path.join(__dirname, 'fixtures', 'html.html'), 'utf-8');

      it('returns surrogate compiler for HTML', function () {
        var obj = temper.compile(template, {
          engine: 'html'
        });

        assume(obj.client).is.a('string');
        assume(obj.library).is.a('string');
        assume(obj.library).equals('');
        assume(obj.server).is.a('function');
        assume(obj.engine).equals('html');
        assume(obj.server({ V1: 'content' }).trim()).equals('
content
');

        var client = (new Function('return '+ obj.client))();
        assume(client).is.a('function');
        assume(client({ V1: 'content' }).trim()).equals('
content
');
      });

      it('supports basic replacements of data', function () {
        var obj = temper.compile('
{key}
', {
          engine: 'html'
        });

        obj.client = (new Function('return '+ obj.client))();

        assume(obj.server({ key: 'bar' })).equals('
bar
');
        assume(obj.client({ key: 'bar' })).equals('
bar
');
      });

      it('doesnt die on replace $\' in strings', function () {
        var obj = temper.compile('
{key}
', {
          engine: 'html'
        });

        obj.client = (new Function('return '+ obj.client))();

        assume(obj.server({ key: '$\'bar' })).equals('
$\'bar
');
        assume(obj.client({ key: '$\'bar' })).equals('
$\'bar
');
      });

      it('doesn\'t die when supplied with an Object.create(null)', function () {
        var obj = temper.compile('
{key}
', { engine: 'html' })
          , data = Object.create(null);

        obj.client = (new Function('return '+ obj.client))();

        data.key = 'bar';
        assume(obj.server(data)).equals('
bar
');
        assume(obj.client(data)).equals('
bar
');
      });
    });
  });

  describe('#normalizeName', function () {
    it('handles filenames without special characters', function () {
      var name = temper.normalizeName('/home/templates/template.jade');

      assume(name).equals('template');
    });

    it('handles filenames with special characters in filenames', function () {
      var name = temper.normalizeName('/home/templates/09$-money_$00-test.jade');

      assume(name).equals('$money_$00test');
    });
  });

  describe('#fetch', function () {
    var template = path.join(__dirname, 'fixtures', 'react-jsx.jsx');

    it('returns a compiled thing', function () {
      var obj = temper.fetch(template);

      assume(obj.client).is.a('string');
      assume(obj.library).is.a('string');
      assume(obj.server).is.a('function');
      assume(obj.server({ V1: 'content' }, { html: true })).equals('
content
');
      assume(obj.engine).equals('react-jsx');
      assume(obj.hash).is.a('object');
      assume(obj.hash.client).is.a('string');
      assume(obj.hash.server).is.a('string');
      assume(obj.hash.library).is.a('string');
    });

    it('can cache the compiled result', function () {
      temper.cache = true;

      assume(temper.compiled).does.not.include(template);
      temper.fetch(template);
      assume(temper.compiled).does.include(template);

      temper.compiled[template].foo = 'bar';

      var cached = temper.fetch(template);
      assume(cached.foo).equals('bar');
    });
  });
});
<|endoftext|>


<commit_before>const {EditorState, Selection} = require("prosemirror-state")
const {history, undo, redo, closeHistory} = require("prosemirror-history")
const {schema, eq, doc, p} = require("prosemirror-model/test/build")
const ist = require("ist")

const {collab, receiveTransaction, sendableSteps} = require("../dist/collab")

const histPlugin = history({preserveItems: true})

class DummyServer {
  constructor(doc, n = 2) {
    this.states = []
    this.plugins = []
    for (let i = 0; i < n; i++) {
      let plugin = collab()
      this.plugins.push(plugin)
      this.states.push(EditorState.create({doc, schema, plugins: [histPlugin, plugin]}))
    }
    this.steps = []
    this.clientIDs = []
    this.delayed = []
  }

  sync(n) {
    let state = this.states[n], version = this.plugins[n].getState(state).version
    if (version != this.steps.length)
      this.states[n] = state.apply(receiveTransaction(state, this.steps.slice(version), this.clientIDs.slice(version)))
  }

  send(n) {
    let sendable = sendableSteps(this.states[n])
    if (sendable && sendable.version == this.steps.length) {
      this.steps = this.steps.concat(sendable.steps)
      for (let i = 0; i < sendable.steps.length; i++) this.clientIDs.push(sendable.clientID)
    }
  }

  broadcast(n) {
    if (this.delayed.indexOf(n) > -1) return
    this.sync(n)
    this.send(n)
    for (let i = 0; i < this.states.length; i++) if (i != n) this.sync(i)
  }

  update(n, f) {
    this.states[n] = this.states[n].apply(f(this.states[n]))
    this.broadcast(n)
  }

  type(n, text, pos) {
    this.update(n, s => s.tr.insertText(text, pos || s.selection.head))
  }

  undo(n) {
    undo(this.states[n], tr => this.update(n, () => tr))
  }

  redo(n) {
    redo(this.states[n], tr => this.update(n, () => tr))
  }

  conv(d) {
    if (typeof d == "string") d = doc(p(d))
    this.states.forEach(state => ist(state.doc, d, eq))
  }

  delay(n, f) {
    this.delayed.push(n)
    f()
    this.delayed.pop()
    this.broadcast(n)
  }
}

function sel(near) {
  return s => s.tr.setSelection(Selection.near(s.doc.resolve(near)))
}

describe("collab", () => {
  it("converges for simple changes", () => {
    let s = new DummyServer
    s.type(0, "hi")
    s.type(1, "ok", 3)
    s.type(0, "!", 5)
    s.type(1, "...", 1)
    s.conv("...hiok!")
  })

  it("converges for multiple local changes", () => {
    let s = new DummyServer
    s.type(0, "hi")
    s.delay(0, () => {
      s.type(0, "A")
      s.type(1, "X")
      s.type(0, "B")
      s.type(1, "Y")
    })
    s.conv("hiXYAB")
  })

  it("converges with three peers", () => {
    let s = new DummyServer(null, 3)
    s.type(0, "A")
    s.type(1, "U")
    s.type(2, "X")
    s.type(0, "B")
    s.type(1, "V")
    s.type(2, "C")
    s.conv("AUXBVC")
  })

  it("converges with three peers with multiple steps", () => {
    let s = new DummyServer(null, 3)
    s.type(0, "A")
    s.delay(1, () => {
      s.type(1, "U")
      s.type(2, "X")
      s.type(0, "B")
      s.type(1, "V")
      s.type(2, "C")
    })
    s.conv("AXBCUV")
  })

  it("supports undo", () => {
    let s = new DummyServer
    s.type(0, "A")
    s.type(1, "B")
    s.type(0, "C")
    s.undo(1)
    s.conv("AC")
    s.type(1, "D")
    s.type(0, "E")
    s.conv("ACDE")
  })

  it("supports redo", () => {
    let s = new DummyServer
    s.type(0, "A")
    s.type(1, "B")
    s.type(0, "C")
    s.undo(1)
    s.redo(1)
    s.type(1, "D")
    s.type(0, "E")
    s.conv("ABCDE")
  })

  it("supports deep undo", () => {
    let s = new DummyServer(doc(p("hello"), p("bye")))
    s.update(0, sel(6))
    s.update(1, sel(11))
    s.type(0, "!")
    s.type(1, "!")
    s.update(0, closeHistory)
    s.delay(0, () => {
      s.type(0, " ...")
      s.type(1, " ,,,")
    })
    s.update(0, closeHistory)
    s.type(0, "*")
    s.type(1, "*")
    s.undo(0)
    s.conv(doc(p("hello! ..."), p("bye! ,,,*")))
    s.undo(0)
    s.undo(0)
    s.conv(doc(p("hello"), p("bye! ,,,*")))
    s.redo(0)
    s.redo(0)
    s.redo(0)
    s.conv(doc(p("hello! ...*"), p("bye! ,,,*")))
    s.undo(0)
    s.undo(0)
    s.conv(doc(p("hello!"), p("bye! ,,,*")))
    s.undo(1)
    s.conv(doc(p("hello!"), p("bye")))
  })

  it("support undo with clashing events", () => {
    let s = new DummyServer(doc(p("hello")))
    s.update(0, sel(6))
    s.type(0, "A")
    s.delay(0, () => {
      s.type(0, "B", 4)
      s.type(0, "C", 5)
      s.type(0, "D", 1)
      s.update(1, s => s.tr.delete(2, 5))
    })
    s.conv("DhoA")
    s.undo(0)
    s.undo(0)
    s.conv("ho")
    ist(s.states[0].selection.head, 3)
  })
})
<commit_msg>Add better test for history rebasing<commit_after>const {EditorState, Selection} = require("prosemirror-state")
const {history, undo, redo, closeHistory} = require("prosemirror-history")
const {schema, eq, doc, p} = require("prosemirror-model/test/build")
const ist = require("ist")

const {collab, receiveTransaction, sendableSteps} = require("../dist/collab")

const histPlugin = history({preserveItems: true})

class DummyServer {
  constructor(doc, n = 2) {
    this.states = []
    this.plugins = []
    for (let i = 0; i < n; i++) {
      let plugin = collab()
      this.plugins.push(plugin)
      this.states.push(EditorState.create({doc, schema, plugins: [histPlugin, plugin]}))
    }
    this.steps = []
    this.clientIDs = []
    this.delayed = []
  }

  sync(n) {
    let state = this.states[n], version = this.plugins[n].getState(state).version
    if (version != this.steps.length)
      this.states[n] = state.apply(receiveTransaction(state, this.steps.slice(version), this.clientIDs.slice(version)))
  }

  send(n) {
    let sendable = sendableSteps(this.states[n])
    if (sendable && sendable.version == this.steps.length) {
      this.steps = this.steps.concat(sendable.steps)
      for (let i = 0; i < sendable.steps.length; i++) this.clientIDs.push(sendable.clientID)
    }
  }

  broadcast(n) {
    if (this.delayed.indexOf(n) > -1) return
    this.sync(n)
    this.send(n)
    for (let i = 0; i < this.states.length; i++) if (i != n) this.sync(i)
  }

  update(n, f) {
    this.states[n] = this.states[n].apply(f(this.states[n]))
    this.broadcast(n)
  }

  type(n, text, pos) {
    this.update(n, s => s.tr.insertText(text, pos || s.selection.head))
  }

  undo(n) {
    undo(this.states[n], tr => this.update(n, () => tr))
  }

  redo(n) {
    redo(this.states[n], tr => this.update(n, () => tr))
  }

  conv(d) {
    if (typeof d == "string") d = doc(p(d))
    this.states.forEach(state => ist(state.doc, d, eq))
  }

  delay(n, f) {
    this.delayed.push(n)
    f()
    this.delayed.pop()
    this.broadcast(n)
  }
}

function sel(near) {
  return s => s.tr.setSelection(Selection.near(s.doc.resolve(near)))
}

describe("collab", () => {
  it("converges for simple changes", () => {
    let s = new DummyServer
    s.type(0, "hi")
    s.type(1, "ok", 3)
    s.type(0, "!", 5)
    s.type(1, "...", 1)
    s.conv("...hiok!")
  })

  it("converges for multiple local changes", () => {
    let s = new DummyServer
    s.type(0, "hi")
    s.delay(0, () => {
      s.type(0, "A")
      s.type(1, "X")
      s.type(0, "B")
      s.type(1, "Y")
    })
    s.conv("hiXYAB")
  })

  it("converges with three peers", () => {
    let s = new DummyServer(null, 3)
    s.type(0, "A")
    s.type(1, "U")
    s.type(2, "X")
    s.type(0, "B")
    s.type(1, "V")
    s.type(2, "C")
    s.conv("AUXBVC")
  })

  it("converges with three peers with multiple steps", () => {
    let s = new DummyServer(null, 3)
    s.type(0, "A")
    s.delay(1, () => {
      s.type(1, "U")
      s.type(2, "X")
      s.type(0, "B")
      s.type(1, "V")
      s.type(2, "C")
    })
    s.conv("AXBCUV")
  })

  it("supports undo", () => {
    let s = new DummyServer
    s.type(0, "A")
    s.type(1, "B")
    s.type(0, "C")
    s.undo(1)
    s.conv("AC")
    s.type(1, "D")
    s.type(0, "E")
    s.conv("ACDE")
  })

  it("supports redo", () => {
    let s = new DummyServer
    s.type(0, "A")
    s.type(1, "B")
    s.type(0, "C")
    s.undo(1)
    s.redo(1)
    s.type(1, "D")
    s.type(0, "E")
    s.conv("ABCDE")
  })

  it("supports deep undo", () => {
    let s = new DummyServer(doc(p("hello"), p("bye")))
    s.update(0, sel(6))
    s.update(1, sel(11))
    s.type(0, "!")
    s.type(1, "!")
    s.update(0, closeHistory)
    s.delay(0, () => {
      s.type(0, " ...")
      s.type(1, " ,,,")
    })
    s.update(0, closeHistory)
    s.type(0, "*")
    s.type(1, "*")
    s.undo(0)
    s.conv(doc(p("hello! ..."), p("bye! ,,,*")))
    s.undo(0)
    s.undo(0)
    s.conv(doc(p("hello"), p("bye! ,,,*")))
    s.redo(0)
    s.redo(0)
    s.redo(0)
    s.conv(doc(p("hello! ...*"), p("bye! ,,,*")))
    s.undo(0)
    s.undo(0)
    s.conv(doc(p("hello!"), p("bye! ,,,*")))
    s.undo(1)
    s.conv(doc(p("hello!"), p("bye")))
  })

  it("support undo with clashing events", () => {
    let s = new DummyServer(doc(p("hello")))
    s.update(0, sel(6))
    s.type(0, "A")
    s.delay(0, () => {
      s.type(0, "B", 4)
      s.type(0, "C", 5)
      s.type(0, "D", 1)
      s.update(1, s => s.tr.delete(2, 5))
    })
    s.conv("DhoA")
    s.undo(0)
    s.undo(0)
    s.conv("ho")
    ist(s.states[0].selection.head, 3)
  })

  it("can undo simultaneous typing", () => {
    let s = new DummyServer(doc(p("A"), p("B")))
    s.update(0, sel(2))
    s.update(1, sel(5))
    s.delay(0, () => {
      s.type(0, "1")
      s.type(0, "2")
      s.type(1, "x")
      s.type(1, "y")
    })
    s.conv(doc(p("A12"), p("Bxy")))
    s.undo(0)
    s.conv(doc(p("A"), p("Bxy")))
    s.undo(1)
    s.conv(doc(p("A"), p("B")))
  })
})
<|endoftext|>


<commit_before>var should = require('should');

var lib = './../lib/';

var Graph = require(lib + 'model/graph');
var Node = require(lib + 'model/node');
var Port = require(lib + 'model/port');
var CardinalPortPosition = require(lib + 'model/cardinalPortPosition');

var LayoutEngine = require(lib + 'layout/dummyLayoutV2');

var generateGraph = function() {
    // the world's simplest graph
    var port = new Port('a+a', 'input', new CardinalPortPosition(50, 'N'));
    var node = new Node('a', [port], []);
    var graph = new Graph([node], []);
    return graph;
};

describe('layout engine', function() {
    it('should take a graph and not blow up', function(done) {
      LayoutEngine(generateGraph());
      done();
    });
});
<commit_msg>Test that the graph is still a Graph after running through layoutengine<commit_after>var should = require('should');

var lib = './../lib/';

var Graph = require(lib + 'model/graph');
var Node = require(lib + 'model/node');
var Port = require(lib + 'model/port');
var CardinalPortPosition = require(lib + 'model/cardinalPortPosition');

var LayoutEngine = require(lib + 'layout/dummyLayoutV2');

var generateGraph = function() {
  // the world's simplest graph
  var port = new Port('a+a', 'input', new CardinalPortPosition(50, 'N'));
  var node = new Node('a', [port], []);
  var graph = new Graph([node], []);
  return graph;
};

describe('layout engine', function() {
  it('should take a graph and not blow up', function(done) {
    var testGraph = generateGraph();
    LayoutEngine(testGraph);
    testGraph.should.be.an.instanceOf(Graph);
  });
});
<|endoftext|>


<commit_before>var chai = require('chai')
  , expect = chai.expect
  , HMRMAIN = require('../src/cli/main')
  , CHALK = require('chalk')
  , FS = require('fs')
  , PATH = require('path')
  , PKG = require('../package.json')
  , _ = require('underscore');

var gather = '';
var ConsoleLogOrg = console.log;
var ProcessExitOrg = process.exit;

describe('Testing Ouput interface', function () {

  function MyConsoleLog( msg ) {
    gather += msg;
    ConsoleLogOrg.apply(this, arguments);
  }

  function MyProcessExit() {

  }

  function HackMyResumeStub( args ) {

    console.log = MyConsoleLog;
    process.exit = MyProcessExit;
    CHALK.enabled = false;

    try {
      args.unshift( process.argv[1] );
      args.unshift( process.argv[0] );
      var HMRMAIN = require('../src/cli/main');
      HMRMAIN( args );
    }
    catch( ex ) {
      require('../src/core/error-handler').err( ex, false );
    }
    CHALK.enabled = true;
    process.exit = ProcessExitOrg;
    console.log = ConsoleLogOrg;

  }

  function run( title, args, tests ) {
    it( title, function() {

      gather = '';
      HackMyResumeStub( args );

      expect(
        _.all( tests, function(t) {
          return gather.indexOf(t) > -1;
        })
      ).to.equal(true);

    });
  }

  var title = '*** HackMyResume v' + PKG.version + ' ***';
  var feedMe = 'Please feed me a resume in FRESH or JSON Resume format.';
  var manPage = FS.readFileSync( PATH.resolve( __dirname, '../src/cli/use.txt' ), 'utf8');

  run('HMR should output a help string when no command is specified',
      [], [ title, 'Please give me a command (BUILD, ANALYZE, VALIDATE, CONVERT, or NEW).' ]);

  run('BUILD should output a tip when no source is specified',
      ['build'], [ title, feedMe ]);

  run('VALIATE should output a tip when no source is specified',
     ['validate'], [ title, feedMe ]);

  run('ANALYZE should output a tip when no source is specified',
      ['analyze'], [ title, feedMe ]);

  run('CONVERT should output a tip when no source is specified',
      ['convert'], [ title, feedMe ]);

  run('NEW should output a tip when no source is specified',
      ['new'], [ title, 'Please specify the filename of the resume to create.' ]);

  // This will cause the HELP doc to be emitted, followed by an "unknown option --help"
  // error in the log, based on the way we're calling into HMR. As long as the test
  // passes, any extraneous error messages can be ignored here.
  run('HMR should output help doc with --help',
      ['--help'], [ manPage ]);

  run('HMR should accept raw JSON via --options',
      [
        'build',
        'node_modules/fresh-test-resumes/src/jane-fullstacker.fresh.json',
        '-o',
        "{ theme: 'compact', debug: true, pdf: 'wkhtmltopdf' }"],
      [ 'Applying COMPACT theme', '(with wkhtmltopdf)'] );

  run('HMR should accept a JSON settings file via --options',
      [
        'build',
        'node_modules/fresh-test-resumes/src/jane-fullstacker.fresh.json',
        '--options',
        "test/hmr-options.json"],
      [ 'Applying POSITIVE theme'] );
});
<commit_msg>Improve --options tests.<commit_after>var chai = require('chai')
  , expect = chai.expect
  , HMRMAIN = require('../src/cli/main')
  , CHALK = require('chalk')
  , FS = require('fs')
  , PATH = require('path')
  , PKG = require('../package.json')
  , _ = require('underscore');

var gather = '';
var ConsoleLogOrg = console.log;
var ProcessExitOrg = process.exit;

describe('Testing Ouput interface', function () {

  function MyConsoleLog( msg ) {
    gather += msg;
    ConsoleLogOrg.apply(this, arguments);
  }

  function MyProcessExit() {

  }

  function HackMyResumeStub( args ) {

    console.log = MyConsoleLog;
    process.exit = MyProcessExit;
    CHALK.enabled = false;

    try {
      args.unshift( process.argv[1] );
      args.unshift( process.argv[0] );
      var HMRMAIN = require('../src/cli/main');
      HMRMAIN( args );
    }
    catch( ex ) {
      require('../src/core/error-handler').err( ex, false );
    }
    CHALK.enabled = true;
    process.exit = ProcessExitOrg;
    console.log = ConsoleLogOrg;

  }

  function run( title, args, tests ) {
    it( title, function() {

      gather = '';
      HackMyResumeStub( args );

      expect(
        _.all( tests, function(t) {
          return gather.indexOf(t) > -1;
        })
      ).to.equal(true);

    });
  }

  var title = '*** HackMyResume v' + PKG.version + ' ***';
  var feedMe = 'Please feed me a resume in FRESH or JSON Resume format.';
  var manPage = FS.readFileSync( PATH.resolve( __dirname, '../src/cli/use.txt' ), 'utf8');

  run('HMR should output a help string when no command is specified',
      [], [ title, 'Please give me a command (BUILD, ANALYZE, VALIDATE, CONVERT, or NEW).' ]);

  run('BUILD should output a tip when no source is specified',
      ['build'], [ title, feedMe ]);

  run('VALIATE should output a tip when no source is specified',
     ['validate'], [ title, feedMe ]);

  run('ANALYZE should output a tip when no source is specified',
      ['analyze'], [ title, feedMe ]);

  run('CONVERT should output a tip when no source is specified',
      ['convert'], [ title, feedMe ]);

  run('NEW should output a tip when no source is specified',
      ['new'], [ title, 'Please specify the filename of the resume to create.' ]);

  // This will cause the HELP doc to be emitted, followed by an "unknown option --help"
  // error in the log, based on the way we're calling into HMR. As long as the test
  // passes, any extraneous error messages can be ignored here.
  run('HMR should output help doc with --help',
      ['--help'], [ manPage ]);

  run('HMR should accept raw JSON via --options',
      [
        'build',
        'node_modules/fresh-test-resumes/src/jane-fullstacker.fresh.json',
        'to',
        'test/sandbox/temp/janeq-1.all',
        '-o',
        "{ theme: 'compact', debug: true, pdf: 'wkhtmltopdf' }"],
      [ 'Applying COMPACT theme', '(with wkhtmltopdf)'] );

  run('HMR should accept a JSON settings file via --options',
      [
        'build',
        'node_modules/fresh-test-resumes/src/jane-fullstacker.fresh.json',
        'to',
        'test/sandbox/temp/janeq-2.all',
        '--options',
        "test/hmr-options.json"],
      [ 'Applying POSITIVE theme'] );

  run('Explicit command line options should override --options',
      [
        'build',
        'node_modules/fresh-test-resumes/src/jane-fullstacker.fresh.json',
        'to',
        'test/sandbox/temp/janeq-3.all',
        '--options',
        "test/hmr-options.json",
        "-t",
        "modern"
      ],
      [ 'Applying MODERN theme'] );
});
<|endoftext|>


<commit_before>
var zmq = require('../')
  , should = require('should');

// alias

zmq.createSocket.should.equal(zmq.socket);
console.log(zmq)

// .socket

var sock = zmq.socket('req');
sock.type.should.equal('req');
sock.close.should.be.a('function');

// setsockopt

sock.getsockopt(zmq.ZMQ_BACKLOG).should.not.equal(75);
sock.setsockopt(zmq.ZMQ_BACKLOG, 75).should.equal(sock);
sock.getsockopt(zmq.ZMQ_BACKLOG).should.equal(75);
sock.setsockopt(zmq.ZMQ_BACKLOG, 100);

// setsockopt + string sugar

sock.getsockopt('backlog').should.not.equal(75);
sock.setsockopt('backlog', 75).should.equal(sock);
sock.getsockopt('backlog').should.equal(75);

// setsockopt sugar

sock.backlog.should.be.a('number');
sock.backlog.should.not.equal(50);
sock.backlog = 50;
sock.backlog.should.equal(50);

sock.close();

// options

sock = zmq.socket('req', { backlog: 30 });
sock.backlog.should.equal(30);
sock.close();
<commit_msg>Rogue console.log removed.<commit_after>
var zmq = require('../')
  , should = require('should');

// alias

zmq.createSocket.should.equal(zmq.socket);

// .socket

var sock = zmq.socket('req');
sock.type.should.equal('req');
sock.close.should.be.a('function');

// setsockopt

sock.getsockopt(zmq.ZMQ_BACKLOG).should.not.equal(75);
sock.setsockopt(zmq.ZMQ_BACKLOG, 75).should.equal(sock);
sock.getsockopt(zmq.ZMQ_BACKLOG).should.equal(75);
sock.setsockopt(zmq.ZMQ_BACKLOG, 100);

// setsockopt + string sugar

sock.getsockopt('backlog').should.not.equal(75);
sock.setsockopt('backlog', 75).should.equal(sock);
sock.getsockopt('backlog').should.equal(75);

// setsockopt sugar

sock.backlog.should.be.a('number');
sock.backlog.should.not.equal(50);
sock.backlog = 50;
sock.backlog.should.equal(50);

sock.close();

// options

sock = zmq.socket('req', { backlog: 30 });
sock.backlog.should.equal(30);
sock.close();
<|endoftext|>


<commit_before>var assert = require('assert');
var fs = require('fs');
var path = require('path');
var temp = require('temp').track();
var ghslug = require('github-slug');
var rewire = require('rewire');
var offline = rewire('../lib/offline');

describe('Offline', function() {
  var oldWd;
  beforeEach(function() {
    oldWd = process.cwd();
  });

  afterEach(function() {
    process.chdir(oldWd);
    offline.__set__('ghslug', ghslug);
  });

  it('should create offline-worker.js in the destination directory', function() {
    var dir = temp.mkdirSync('tmp');

    return offline({
      rootDir: dir,
    }).then(function() {
      assert.doesNotThrow(fs.accessSync.bind(fs, path.join(dir, 'offline-worker.js')));
    });
  });

  it('should not fail if the destination directory already contains a offline-worker.js file', function() {
    var dir = temp.mkdirSync('tmp');

    fs.writeFileSync(path.join(dir, 'offline-worker.js'), 'something');

    return offline({
      rootDir: dir,
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content, 'something');
    });
  });

  it('should use importScript in the service worker if the importScripts option is defined', function() {
    var dir = temp.mkdirSync('tmp');

    fs.writeFileSync('a-script.js', 'something');

    return offline({
      rootDir: dir,
      importScripts: [ 'a-script.js', ],
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content.indexOf('importScripts("a-script.js");'), -1);
    });
  });

  it('should use the GitHub slug as the cache ID if it is available', function() {
    var rootDir = temp.mkdirSync('tmp');
    var dir = path.join(rootDir, 'dist');
    fs.mkdirSync(dir);

    offline.__set__('ghslug', function(path, callback) {
      callback(null, 'mozilla/oghliner');
    });

    process.chdir(rootDir);

    return offline({
      rootDir: dir,
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content.indexOf('mozilla/oghliner'), -1);
    });
  });

  it('should use the app name from package.json as the cache ID if the GitHub slug is not available', function() {
    var rootDir = temp.mkdirSync('tmp');
    var dir = path.join(rootDir, 'dist');
    fs.mkdirSync(dir);

    fs.writeFileSync(path.join(rootDir, 'package.json'), JSON.stringify({
      name: 'test_name',
    }));

    process.chdir(rootDir);

    return offline({
      rootDir: dir,
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content.indexOf('test_name'), -1);
    });
  });

  it('should not fail if both the GitHub slug and package.json are not available', function() {
    var rootDir = temp.mkdirSync('tmp');
    var dir = path.join(rootDir, 'dist');
    fs.mkdirSync(dir);

    process.chdir(rootDir);

    return offline({
      rootDir: dir,
    }).then(function() {
      assert.doesNotThrow(fs.accessSync.bind(fs, path.join(dir, 'offline-worker.js')));
    });
  });
});
<commit_msg>Test that files in rootDir are cached<commit_after>var assert = require('assert');
var fs = require('fs');
var path = require('path');
var temp = require('temp').track();
var ghslug = require('github-slug');
var rewire = require('rewire');
var offline = rewire('../lib/offline');

describe('Offline', function() {
  var oldWd;
  beforeEach(function() {
    oldWd = process.cwd();
  });

  afterEach(function() {
    process.chdir(oldWd);
    offline.__set__('ghslug', ghslug);
  });

  it('should create offline-worker.js in the destination directory', function() {
    var dir = temp.mkdirSync('tmp');

    return offline({
      rootDir: dir,
    }).then(function() {
      assert.doesNotThrow(fs.accessSync.bind(fs, path.join(dir, 'offline-worker.js')));
    });
  });

  it('should not fail if the destination directory already contains a offline-worker.js file', function() {
    var dir = temp.mkdirSync('tmp');

    fs.writeFileSync(path.join(dir, 'offline-worker.js'), 'something');

    return offline({
      rootDir: dir,
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content, 'something');
    });
  });

  it('should use importScript in the service worker if the importScripts option is defined', function() {
    var dir = temp.mkdirSync('tmp');

    fs.writeFileSync('a-script.js', 'something');

    return offline({
      rootDir: dir,
      importScripts: [ 'a-script.js', ],
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content.indexOf('importScripts("a-script.js");'), -1);
    });
  });

  it('should use the GitHub slug as the cache ID if it is available', function() {
    var rootDir = temp.mkdirSync('tmp');
    var dir = path.join(rootDir, 'dist');
    fs.mkdirSync(dir);

    offline.__set__('ghslug', function(path, callback) {
      callback(null, 'mozilla/oghliner');
    });

    process.chdir(rootDir);

    return offline({
      rootDir: dir,
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content.indexOf('mozilla/oghliner'), -1);
    });
  });

  it('should use the app name from package.json as the cache ID if the GitHub slug is not available', function() {
    var rootDir = temp.mkdirSync('tmp');
    var dir = path.join(rootDir, 'dist');
    fs.mkdirSync(dir);

    fs.writeFileSync(path.join(rootDir, 'package.json'), JSON.stringify({
      name: 'test_name',
    }));

    process.chdir(rootDir);

    return offline({
      rootDir: dir,
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content.indexOf('test_name'), -1);
    });
  });

  it('should not fail if both the GitHub slug and package.json are not available', function() {
    var rootDir = temp.mkdirSync('tmp');
    var dir = path.join(rootDir, 'dist');
    fs.mkdirSync(dir);

    process.chdir(rootDir);

    return offline({
      rootDir: dir,
    }).then(function() {
      assert.doesNotThrow(fs.accessSync.bind(fs, path.join(dir, 'offline-worker.js')));
    });
  });

  it('should cache files in rootDir', function() {
    var rootDir = temp.mkdirSync('tmp');
    var dir = path.join(rootDir, 'dist');
    fs.mkdirSync(dir);

    fs.writeFileSync(path.join(dir, 'test_file_1.js'), 'test_file_1');
    fs.writeFileSync(path.join(dir, 'test_file_2.js'), 'test_file_2');
    fs.writeFileSync(path.join(dir, 'test_file_3.js'), 'test_file_3');

    process.chdir(rootDir);

    return offline({
      rootDir: dir,
    }).then(function() {
      var content = fs.readFileSync(path.join(dir, 'offline-worker.js'), 'utf8');
      assert.notEqual(content.indexOf('test_file_1.js'), -1);
      assert.notEqual(content.indexOf('test_file_2.js'), -1);
      assert.notEqual(content.indexOf('test_file_3.js'), -1);
    });
  });
});
<|endoftext|>


<commit_before>/**
 * TODO
 *
 * @class ReadWriteLock
 * @constructor
 */
module.exports = function ReadWriteLock() {
	'use strict';

	var table = {};

	/**
	 * TODO
	 *
	 * @method readLock
	 * @param key {String} TODO
	 * @param callback {Function} TODO
	 * @param callback.release {Function} TODO
	 * @param [timeout] {Number} TODO
	 */
	function readLock(key, callback) {
		var release = (function () {
			var released = false;
			return function () {
				if (!released) {
					released = true;
					if (--table[key].readers < 1) {
						if (table[key].callbacks.length) {
							table[key].callbacks.shift()();
						} else {
							delete table[key];
						}
					}
				}
			};
		}());
		if (key in table) {
			if (table[key].readers > 0) {
				table[key].readers++;
				callback(release);
			} else {
				table[key].callbacks(function () {
					table[key].readers++;
					// TODO
				});
			}
		} else {
			table[key] = {
				readers: 1,
				callbacks: []
			};
			callback(release);
		}
	}

	/**
	 * TODO
	 *
	 * @method writeLock
	 * @param key {String} TODO
	 * @param callback {Function} TODO
	 * @param callback.release {Function} TODO
	 * @param [timeout] {Number} TODO
	 */
	function writeLock(key, callback) {
		var release = (function () {
			var released = false;
			return function () {
				if (!released) {
					released = true;
					table[key].readers = 0;
					if (table[key].callbacks.length) {
						table[key].callbacks.shift()();
					} else {
						delete table[key];
					}
				}
			};
		}());
		if (key in table) {
			table[key].callbacks.push(function () {
				// TODO
			});
		} else {
			table[key] = {
				readers: -1,
				callbacks: []
			};
			callback(release);
		}
	}

	this.readLock = readLock;
	this.writeLock = writeLock;

	/**
	 * TODO
	 *
	 * @method criticalSection
	 * @param key {String} TODO
	 * @param callback {Function} TODO
	 * @param [timeout] {Number} TODO
	 */
	this.criticalSection = function (key, callback, timeout) {
		writeLock(key, function (release) {
			callback();
			release();
		}, timeout);
	};
};
<commit_msg>Completing implementation.<commit_after>/**
 * TODO
 *
 * @class ReadWriteLock
 * @constructor
 */
module.exports = function ReadWriteLock() {
	'use strict';

	var table = {};

	/**
	 * TODO
	 *
	 * @method readLock
	 * @param key {String} TODO
	 * @param callback {Function} TODO
	 * @param callback.release {Function} TODO
	 * @param [timeout] {Number} TODO
	 */
	function readLock(key, callback) {
		var release = (function () {
			var released = false;
			return function () {
				if (!released) {
					released = true;
					table[key].readers--;
					if (table[key].queue.length) {
						table[key].queue[0]();
					} else {
						delete table[key];
					}
				}
			};
		}());
		if (key in table) {
			if ((table[key].readers < 0) || table[key].queue.length) {
				table[key].queue.push(function () {
					if (table[key].readers >= 0) {
						table[key].queue.shift();
						table[key].readers++;
						callback(release);
						if (table[key].queue.length) {
							table[key].queue[0]();
						}
					}
				});
			} else {
				table[key].readers++;
			}
		} else {
			table[key] = {
				readers: 1,
				queue: []
			};
			callback(release);
		}
	}

	/**
	 * TODO
	 *
	 * @method writeLock
	 * @param key {String} TODO
	 * @param callback {Function} TODO
	 * @param callback.release {Function} TODO
	 * @param [timeout] {Number} TODO
	 */
	function writeLock(key, callback) {
		var release = (function () {
			var released = false;
			return function () {
				if (!released) {
					released = true;
					table[key].readers = 0;
					if (table[key].queue.length) {
						table[key].queue[0]();
					} else {
						delete table[key];
					}
				}
			};
		}());
		if (key in table) {
			if (table[key].readers || table[key].queue.length) {
				table[key].queue.push(function () {
					if (!table[key].readers) {
						table[key].queue.shift();
						table[key].readers = -1;
						callback(release);
					}
				});
			} else {
				table[key].readers = -1;
				callback(release);
			}
		} else {
			table[key] = {
				readers: -1,
				queue: []
			};
			callback(release);
		}
	}

	this.readLock = readLock;
	this.writeLock = writeLock;

	/**
	 * TODO
	 *
	 * @method criticalSection
	 * @param key {String} TODO
	 * @param callback {Function} TODO
	 * @param [timeout] {Number} TODO
	 */
	this.criticalSection = function (key, callback, timeout) {
		writeLock(key, function (release) {
			callback();
			release();
		}, timeout);
	};
};
<|endoftext|>